display jfreecharts using servlets - java

I have a scenario where I need to display charts(generated using jfreecharts) converted it into a png image and then display them using servlets.
When the chart code extends either ApplicationFrame or Jframe I see the following exception when I display it using servlets :
java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159)
at java.awt.Window.(Window.java:317)
at java.awt.Frame.(Frame.java:419)
at javax.swing.JFrame.(JFrame.java:194)
I read through a couple of places and this seems to be because of the ApplicationFrame and JFrame would cause this error.
If i pass just the chart object this throws a
java.lang.IllegalArgumentException: Null 'chart' argument.
org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:181)
org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:136)
Is there any solution for this?

ChartUtilities is the right choice; streams are supported, too. One approach requires Using Headless Mode in the Java SE Platform, but I've also gotten it to work with VNC.
Addendum: here's a related forum thread.

I will explain you in simple way as I faced the same problem as i was new.
Steps
Create a servlet
In doPost create outputstream
set content type to text/png
Create datasets
set values to dataset
create instance of jfreechart and call createchart(the chart you wanna use) using ChartFqactory.
finally call WriteChartAsPNG using ChartUtilities and pass the Jfreechart instance,outputstream,width,height.
DONE:
Sample below
package polo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
/**
* Servlet implementation class PieChartDemo1Serv
*/
public class PieServ extends HttpServlet implements useme {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PieServ() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("image/png");
ServletOutputStream out = response.getOutputStream();
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("In-Network ", .80);
pieDataset.setValue("Out-of-Network ", .20);
JFreeChart chart = ChartFactory.createPieChart("", pieDataset, true, true, false);
ChartUtilities.writeChartAsPNG(out, chart, 202, 182);
System.out.println("done23");
}
}
Now I know you what further.Study Pieplots/Legends to setup border and formatting.You can do a lot further.

Related

Previously working Java servlet now no longer working after 'Clean' - Tomcat v7.0 and Eclipse

So I had an Eclipse project given to me, which I opened in Eclipse and converted to a web project and began writing a servlet + JSP pages for it. It was working fine, until this morning when I cleaned the project using Eclipse's in-built clean function.
Now I am getting the 404 with 'Requested resource is not available' where it was working fine before.
Here is the Servlet code:
package servlets;
import is2.data.SentenceData09;
import is2.lemmatizer.Lemmatizer;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FYPServlet
*/
#WebServlet("/FYPServlet")
public class FYPServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public FYPServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("sentence")!=null){
//Create container
SentenceData09 sentence = new SentenceData09();
//Split input up
String[] words = request.getParameter("sentence").split(" ");
String lastword = words[words.length-1];
int sizeoflastword = lastword.length();
//If sentence has a full stop, remove it
if(lastword.charAt(sizeoflastword-1)=='.'){
words[words.length-1] = lastword.substring(0,sizeoflastword-1);
}
//Add <root> to start and a full stop to end
String[] fullsentencewords = new String[words.length+2];
fullsentencewords[0] = "<root>";
int i=1;
for(String word : words){
fullsentencewords[i] = word;
i++;
}
fullsentencewords[fullsentencewords.length-1] = ".";
//Initialise the container
sentence.init(fullsentencewords);
//Give lemmatizer location of model
is2.lemmatizer.Options optsLemmatizer = new is2.lemmatizer.Options(new String[] {"-model","C:/Users/Illuria/Downloads/small-models-english/small-models-english/models/lemmatizer-eng-4M-v36.mdl"});
//Create lemmatizer
Lemmatizer lemmatizer = new Lemmatizer(optsLemmatizer);
//Apply the lemmatizer
lemmatizer.apply(sentence);
//Display the lemmata
for (String l : sentence.plemmas) System.out.println("lemma : "+l); //TODO: Push this to the new page
request.setAttribute("lemmas", sentence.plemmas);
request.getRequestDispatcher("ParseDisplay.jsp").forward(request, response);
}else{
response.sendRedirect("EntryForm.jsp");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
The exact 404 I am getting is:
HTTP Status 404 - /mate-tools-2/FYPServlet
type: Status report
message: /mate-tools-2/FYPServlet
description: The requested resource is not available
Unfortunately I'm a bit of a newbie at web development so any help would be greatly appreciated!
Not sure if you are still having trouble but sometimes just cleaning wont help. I remove webapp from Tomcat eclipse (right click on Tomcat and do 'Add or Remove'), clean it and add it back. Let us know if this helps.

display an image from a blob field using servlet

i created a jsp page that calls another jsp page that show an image took from a blob field in my mysql db:
<img src="blob.jsp">
it works. But, somewhere in this forum i read that this is not the right way to do it. I should, instead, using a servlet this way:
<img src="servlet_name">
I created a servlet, but it doesent show me the image it shows me this
ÿØÿàJFIFHHÿí$Photoshop 3.08BIMí ResolutionHH8BIM FX Global Lighting Anglex8BIMFX Global Altitude8BIMó Print Flags 8BIM Copyright Flag8BIM'Japanese Print Flags 8BIMõColor Halftone SettingsH/fflff/ff¡™š2Z5-8BIMøColor Transfer Settingspÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿè8BIM Layer State8BIM Layer Groups8BIMGuides##8BIM URL overrides8BIMSlicesuƒD Untitled-1Dƒ8BIMICC Untagged Flag
This is my simple servlet
package Jeans;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BlobDisplay")
public class BlobDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
GestioneDB gestioneDB ;
public BlobDisplay() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Blob image = null;
byte[ ] imgData = null ;
String query = null;
query = request.getParameter(query);
gestioneDB = new GestioneDB();
ResultSet rs = gestioneDB.rs("select immagine_principale from news where id ='217'");
try{
if (rs.next()) {
image = rs.getBlob("immagine_principale");
imgData = image.getBytes(1,(int)image.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
}
}
catch(Exception e){}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
Here is a debugging hint for now.
JSPs are just "inside out" servlets and they are translated to servlets by the container. Since your JSP works and your servlet doesn't, why don't you check out (and post) the generated servlet. If you are using tomcat, it would be in a file called blob__jsp.java deep in the work directory. Then compare the calls and set up of your servlet and the generated servlet.
(My first guess is the content type, but you seem to be setting that)

NoClassDefFoundError when trying to load a dll in servlet with tomcat

I am trying to build a simple java servlet that runs in tomcat server on my machine.
My servlet code is :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class javaservlet
*/
#WebServlet(description = "java servlet", urlPatterns = { "/javaservlet" })
public class javaservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public javaservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter writer = response.getWriter();
calldll callingdll = new calldll();
ServletContext context = getServletConfig().getServletContext();
String path = context.getContextPath();
writer.println(path);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
and it works fine (not of the calldll callingdll = new calldll(); part i will explain below what error i get there)
I also have a second class that loads the dll file called "calldll.dll" (did all the work with javac , javah and stuff and it works ) my dll is placed in C:\apache-tomcat-7.0.37\wtpwebapps\myServlet\WEB-INF\lib and i have pointed build path of native there and my class code is
public class calldll {
private native void print();
public static void main (String[] args){
new calldll().print();
}
static {
System.loadLibrary("calldll");
}
}
My c file where i made the dll from is a really simple
#include<jni.h>
#include<stdio.h>
#include<windows.h>
#include "calldll.h"
JNIEXPORT void JNICALL
Java_calldll_print(JNIEnv*env,jobject obj)
{
printf("It Works!");
return;
}
when i run the javaservlet where i call the call dll class that loads the dll i get this :
java.lang.NoClassDefFoundError: Could not initialize class calldll
javaservlet.doGet(javaservlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
The weird thing is that when i run the java class alone the message "It works" comes up so the class loads the dll successfully. But when when i create an instance of the class in the servlet it doesnt it from the servlet is doesn't that is my problem....
i added to the calldll class
catch(UnsatisfiedLinkError e)
{
System.err.println("Native code library failed to load.\n" + e);
}
to see if it is a problem with static and i get the following error when i run the servlet
Native code library failed to load.
java.lang.UnsatisfiedLinkError: no calldll in java.library.path
but my calldll class if i execute it alone it still works... so what is happening in the servlet that i do wrong :s
If your webapp is hosted in tomcat app server copy the dll to bin folder, then in your servlet use :
System.load(System.getProperty("catalina.base")+"/bin/yourdll.dll");

create report in pdf by using jasper and servlet [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to create a report in pdf format by using servlet, .jasper file,but there is a exception:
HTTP Status 500 - Servlet execution threw an exception
--------------------------------------------------------------------------------
type Exception report
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError:
net/sf/jasperreports/engine/JasperRunManager
one.Patient.doGet(Patient.java:46)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache
Tomcat/7.0.34 logs.
servlet code is:
package one;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.HashMap;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
/**
* Servlet implementation class Patient
*/
#WebServlet("/Patient")
public class Patient extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Patient() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Connection con=DBCon.getConnection();
InputStream inS=getServletContext().getResourceAsStream("/report-src/ganeshaji.jashper");
OutputStream outS=response.getOutputStream();
response.setContentType("application/pdf");
try {
JasperRunManager.runReportToPdfStream(inS, outS, new HashMap<String, Object>(),con);
outS.flush();
con.close();
} catch (Exception e) {
// TODO Auto-generated catch block
response.setContentType("text/html");
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
pls. provide me solution
By looking into the root Cause
java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/JasperRunManager
it seems like you either miss the jasper jar or have the wrong version which doesn't support JasperRunManager.
Including the proper jar in the class path will solve your issue.
Please download these jars:
itext-4.2.0.jar
itextpdf-5.3.4.jar
jasperreports-4.0.1.jar
jasperreports-fonts-4.0.0.jar
and code something like:
try {
FileInputStream fis = new FileInputStream(YOURREPORTPATH.jasper");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
} catch (Exception e2) {
e2.printStackTrace();
}
and then after filling the parameters and the datasource create pdf like this:
JasperExportManager.exportReportToPdfFile(jasperPrint, OUTPUTFILENAME+".pdf");
Thanks...
Mr.777
detected the root Exception, which was thrown before NoClassDefFoundError:net/sf/jasperreports/engine/util/JRStyledTextParser :
java.lang.NoClassDefFoundError: sun/awt/X11GraphicsEnvironment
The Sun AWT classes on Unix and Linux have a dependence on the X Window System. When you use these classes, they expect to load X client libraries and be able to talk to an X display server. This makes sense if your client has a GUI; unfortunately, it's required even if your client uses AWT but does not have a GUI (which is my case, generating a report from a web application)
The way to bypass this, is setting a system property java.awt.headless=true on system startup.
For Example
Let java execute the static block as early as possible by moving it to the top of the class!
public class Foo() {
static { /* works fine! ! */
System.setProperty("java.awt.headless", "true");
}
public static void main() {}
}
or
I think this parameter can be set by passing it as an argument to Java Virtual Machine e.g.
-Djava.awt.headless=true. Not sure if this would have impact on other components of your application.
or
Try putting this in your ${CATALINA_HOME}/bin/catalina.sh script:
export JAVA_OPTS="${JAVA_OPTS} -Djava.awt.headless=true"
refered from-https://stackoverflow.com/a/3651196/1602230

Amazon Credentials Method not found

So my next problem with this code. It seemse to not be finding a method and my eyes are untrained. Any help available on this?
package packeging;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.auth.BasicAWSCredentials;
import org.apache.http.*;
/**
* Servlet implementation class Hashtastic
*/
#WebServlet("/Hashtastic")
public class Hashtastic extends HttpServlet {
private static final long serialVersionUID = 1L;
private final static String BUCKET_NAME = "idlatestingbucket";//http://s3.amazonaws.com/THESISDB/techy.jpg
private final static String FILE_NAME = "TestPicture/wallpaper-264411.png";
private final static String ACCESS_KEY = "Fakepass";
private final static String SECRET_KEY = "Fakekey";
/**
* Default constructor.
*/
public Hashtastic() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 1000);
Date expDate = cal.getTime();
out.println(expDate+"\n");
BasicAWSCredentials cre = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonS3 s3 = new AmazonS3Client(cre);
String url = s3.generatePresignedUrl(BUCKET_NAME, FILE_NAME, expDate, HttpMethod.GET).toString();
out.println(url);
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I am getting this 500 error. It says that it is missing a method. I have the jar in my lib and plugins for eclipse.
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager: method <init>()V not found
com.amazonaws.http.ConnectionManagerFactory.createThreadSafeClientConnManager(ConnectionManagerFactory.java:26)
com.amazonaws.http.HttpClientFactory.createHttpClient(HttpClientFactory.java:83)
com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:116)
com.amazonaws.AmazonWebServiceClient.<init>(AmazonWebServiceClient.java:60)
com.amazonaws.services.s3.AmazonS3Client.<init>(AmazonS3Client.java:291)
com.amazonaws.services.s3.AmazonS3Client.<init>(AmazonS3Client.java:273)
packeging.Hashtastic.doGet(Hashtastic.java:48)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.27 logs.
This could happen if you have the wrong version of the httpclient jar in your classpath, or if you have more than one version of that jar in your classpath (e.g. having both httpclient-4.0.1.jar and httpclient-4.1.1.jar).
It could also be caused by another jar containing a different version of the same class. For example, I know that gwt-dev.jar contains a version of ThreadSafeClientConnManager. If this is the case, the problem could probably be solved by adjusting the build path order to put httpclient.jar before gwt-dev.jar (or the other jar causing problem).
From experience with this exact same Exception, the chances are fairly good that it is caused by gwt-dev appearing before aws-java-sdk in your classpath and due to gwt-dev containing a conflicting (in terms of classloading) version of org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager
If you happen to be using Maven, re-order your dependencies as follows and perhaps add a warning to fellow maintainers on the significance of the ordering.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.3.26</version>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-dev</artifactId>
<version>2.3.0</version>
</dependency>

Categories

Resources