[RESOLVIDO] JFreeChart com Servlet

5 respostas
diogoprosoft

Galera estou tentando inicializar um JfreeChart através de um Servlet no JSF, porém está dando um erro.

Meu Servlet

package com.br.isdra.piloto.servlet;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;

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 org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.dial.DialBackground;
import org.jfree.chart.plot.dial.DialPlot;
import org.jfree.chart.plot.dial.DialTextAnnotation;
import org.jfree.chart.plot.dial.StandardDialFrame;
import org.jfree.chart.plot.dial.StandardDialRange;
import org.jfree.chart.plot.dial.StandardDialScale;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.ui.GradientPaintTransformType;
import org.jfree.ui.StandardGradientPaintTransformer;

@WebServlet("/graficoJFreeChartServelt")
public class GraficoJFreeChartServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("image/png");
		OutputStream output = response.getOutputStream();
		try {
			ChartUtilities.saveChartAsJPEG(new File("img/graficometa.jpg"),
					criarGrafico(), 230, 230);
		} catch (Exception e) {
			e.printStackTrace();
		}
		output.close();
	}
	
	private JFreeChart criarGrafico() throws Exception {
		Double porcentagem = 1000D;
		DefaultValueDataset dataset1 = new DefaultValueDataset(porcentagem);
		DefaultValueDataset dataset2 = new DefaultValueDataset(500D);

		DialPlot dialplot = new DialPlot();
		dialplot.setView(0.0D, 0.0D, 1.0D, 1.0D);
		dialplot.setDataset(0, dataset1);
		dialplot.setDataset(1, dataset2);

		StandardDialFrame standarddialframe = new StandardDialFrame();
		standarddialframe.setBackgroundPaint(Color.lightGray);
		standarddialframe.setForegroundPaint(Color.GRAY);
		dialplot.setDialFrame(standarddialframe);

		GradientPaint gradientpaint = new GradientPaint(new Point(),
				new Color(255, 255, 255), new Point(), new Color(170, 170,
						220));
		DialBackground dialbackground = new DialBackground(gradientpaint);
		dialbackground
				.setGradientPaintTransformer(new StandardGradientPaintTransformer(
						GradientPaintTransformType.VERTICAL));
		dialplot.setBackground(dialbackground);

		DialTextAnnotation dialtextannotation = new DialTextAnnotation(
				"Meta");
		dialtextannotation.setFont(new Font("Dialog", 1, 14));
		dialtextannotation.setRadius(0.15D);
		dialplot.addLayer(dialtextannotation);

		Integer meta = 10000;
		DialTextAnnotation dialtextaMeta = new DialTextAnnotation("R$ "
				+ meta + "mi");
		dialtextaMeta.setFont(new Font("Dialog", 0, 14));
		dialtextaMeta.setRadius(0.30D);
		dialplot.addLayer(dialtextaMeta);

		StandardDialScale standarddialscale = new StandardDialScale(0, 150,
				270D, -300D, 10D, 1);
		standarddialscale.setTickRadius(0.88D);
		standarddialscale.setTickLabelOffset(0.18999999999999999D);
		standarddialscale.setTickLabelFont(new Font("Dialog", 0, 12));
		standarddialscale.setTickLabelFormatter(DecimalFormat
				.getNumberInstance());
		dialplot.addScale(0, standarddialscale);

		dialplot.mapDatasetToScale(1, 1);

		StandardDialRange standarddialrange = new StandardDialRange(100D,
				150D, Color.GREEN);

		standarddialrange.setScaleIndex(0);

		standarddialrange.setInnerRadius(0.50999999999999997D);
		standarddialrange.setOuterRadius(0.50999999999999997D);
		dialplot.addLayer(standarddialrange);
		
		StandardDialRange standarddialrangeb = new StandardDialRange(0D,
				100D, Color.RED);
		
		standarddialrangeb.setScaleIndex(0);

		standarddialrangeb.setInnerRadius(0.50999999999999997D);
		standarddialrangeb.setOuterRadius(0.50999999999999997D);
		dialplot.addLayer(standarddialrangeb);

		StandardDialScale standarddialscale1 = new StandardDialScale();
		standarddialscale1.setTickRadius(0.5D);
		standarddialscale1.setTickLabelOffset(0.14999999999999999D);
		standarddialscale1.setTickLabelFont(new Font("Dialog", 0, 10));
		standarddialscale1.setMajorTickPaint(Color.red);
		standarddialscale1.setMinorTickPaint(Color.red);
		dialplot.addScale(1, standarddialscale1);
		dialplot.mapDatasetToScale(1, 1);

		org.jfree.chart.plot.dial.DialPointer.Pointer pointer = new org.jfree.chart.plot.dial.DialPointer.Pointer(
				0);
		dialplot.addPointer(pointer);

		org.jfree.chart.plot.dial.DialPointer.Pointer pin = new org.jfree.chart.plot.dial.DialPointer.Pointer(
				1);
		
		dialplot.addPointer(pin);

		JFreeChart jfreechart = new JFreeChart(dialplot);
		ChartPanel chartpanel = new ChartPanel(jfreechart);
		chartpanel.setPreferredSize(new Dimension(400, 400));				

		return jfreechart;
	}
}

Meu JSP

<h:panelGroup style="text-align: center" >
			<h:graphicImage value="/graficoJFreeChartServelt"/>
			<br/>
		</h:panelGroup>

Erro

GRAVE: Allocate exception for servlet com.br.isdra.piloto.servlet.GraficoJFreeChartServelt
java.lang.ClassNotFoundException: org.jfree.data.general.ValueDataset
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
	at java.lang.Class.getDeclaredConstructors0(Native Method)
	at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
	at java.lang.Class.getConstructor0(Unknown Source)
	at java.lang.Class.newInstance0(Unknown Source)
	at java.lang.Class.newInstance(Unknown Source)
	at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:119)
	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1062)
	at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:813)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)

O que pode ser? Como devo fazer?

5 Respostas

M

Ao que parece o jar jcommon não está no classpath, o jfreechart depende dele
http://www.jfree.org/jfreechart/download.html

diogoprosoft

realmente os .jars estavam pegando externos agora coloquei direto na pasta lib, o exemplo que fiz funcionou mais com o gráfico específico não está mostrado deve ser porcausa do servlet pois ele pega uma imagem referenciada vou mostrar como ficou o código.

Esse código funciona perfeitamente

package com.br.isdra.piloto.servlet;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
 
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 org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

@WebServlet("/pieChartGen")
public class PieChartGen extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
            genPieChart(req, resp);
      }
 
      public void genPieChart(HttpServletRequest req,
                              HttpServletResponse resp) {
            try {
                  OutputStream out = resp.getOutputStream();
                  // Create a simple Bar chart
                  DefaultPieDataset dataset = new DefaultPieDataset();
 
                  dataset.setValue("SCIENCE CLASS", 65);
                  dataset.setValue("ECONOMICS CLASS", 25);
                  dataset.setValue("LANGUAGE CLASS", 10);
 
                  JFreeChart chart =
                        ChartFactory.createPieChart(
                              "Students by Classes",
                              dataset,
                              true,
                              true,
                              false);
                  chart.setBackgroundPaint(Color.white);
 
                  resp.setContentType("image/png");
                  ChartUtilities.writeChartAsPNG(out, chart, 625, 500);
 
            } catch (Exception e) {
                  System.err.println(
                        "Problem occurred while creating chart." + e.getMessage());
            }
      }
}

Porém nesse outro que é o que preciso fazer funcionar não dá erro mais não mostra

package com.br.isdra.piloto.servlet;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;

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 org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.dial.DialBackground;
import org.jfree.chart.plot.dial.DialPlot;
import org.jfree.chart.plot.dial.DialTextAnnotation;
import org.jfree.chart.plot.dial.StandardDialFrame;
import org.jfree.chart.plot.dial.StandardDialRange;
import org.jfree.chart.plot.dial.StandardDialScale;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.ui.GradientPaintTransformType;
import org.jfree.ui.StandardGradientPaintTransformer;

@WebServlet("/graficoJFreeChartServelt")
public class GraficoJFreeChartServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			criarGrafico(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private JFreeChart criarGrafico(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		OutputStream out = resp.getOutputStream();
		
		Double porcentagem = 1000D;
		DefaultValueDataset dataset1 = new DefaultValueDataset(porcentagem);
		DefaultValueDataset dataset2 = new DefaultValueDataset(500D);

		DialPlot dialplot = new DialPlot();
		dialplot.setView(0.0D, 0.0D, 1.0D, 1.0D);
		dialplot.setDataset(0, dataset1);
		dialplot.setDataset(1, dataset2);

		StandardDialFrame standarddialframe = new StandardDialFrame();
		standarddialframe.setBackgroundPaint(Color.lightGray);
		standarddialframe.setForegroundPaint(Color.GRAY);
		dialplot.setDialFrame(standarddialframe);

		GradientPaint gradientpaint = new GradientPaint(new Point(),
				new Color(255, 255, 255), new Point(), new Color(170, 170,
						220));
		DialBackground dialbackground = new DialBackground(gradientpaint);
		dialbackground
				.setGradientPaintTransformer(new StandardGradientPaintTransformer(
						GradientPaintTransformType.VERTICAL));
		dialplot.setBackground(dialbackground);

		DialTextAnnotation dialtextannotation = new DialTextAnnotation(
				"Meta");
		dialtextannotation.setFont(new Font("Dialog", 1, 14));
		dialtextannotation.setRadius(0.15D);
		dialplot.addLayer(dialtextannotation);

		Integer meta = 10000;
		DialTextAnnotation dialtextaMeta = new DialTextAnnotation("R$ "
				+ meta + "mi");
		dialtextaMeta.setFont(new Font("Dialog", 0, 14));
		dialtextaMeta.setRadius(0.30D);
		dialplot.addLayer(dialtextaMeta);

		StandardDialScale standarddialscale = new StandardDialScale(0, 150,
				270D, -300D, 10D, 1);
		standarddialscale.setTickRadius(0.88D);
		standarddialscale.setTickLabelOffset(0.18999999999999999D);
		standarddialscale.setTickLabelFont(new Font("Dialog", 0, 12));
		standarddialscale.setTickLabelFormatter(DecimalFormat
				.getNumberInstance());
		dialplot.addScale(0, standarddialscale);

		dialplot.mapDatasetToScale(1, 1);

		StandardDialRange standarddialrange = new StandardDialRange(100D,
				150D, Color.GREEN);

		standarddialrange.setScaleIndex(0);

		standarddialrange.setInnerRadius(0.50999999999999997D);
		standarddialrange.setOuterRadius(0.50999999999999997D);
		dialplot.addLayer(standarddialrange);
		
		StandardDialRange standarddialrangeb = new StandardDialRange(0D,
				100D, Color.RED);
		
		standarddialrangeb.setScaleIndex(0);

		standarddialrangeb.setInnerRadius(0.50999999999999997D);
		standarddialrangeb.setOuterRadius(0.50999999999999997D);
		dialplot.addLayer(standarddialrangeb);

		StandardDialScale standarddialscale1 = new StandardDialScale();
		standarddialscale1.setTickRadius(0.5D);
		standarddialscale1.setTickLabelOffset(0.14999999999999999D);
		standarddialscale1.setTickLabelFont(new Font("Dialog", 0, 10));
		standarddialscale1.setMajorTickPaint(Color.red);
		standarddialscale1.setMinorTickPaint(Color.red);
		dialplot.addScale(1, standarddialscale1);
		dialplot.mapDatasetToScale(1, 1);

		org.jfree.chart.plot.dial.DialPointer.Pointer pointer = new org.jfree.chart.plot.dial.DialPointer.Pointer(
				0);
		dialplot.addPointer(pointer);

		org.jfree.chart.plot.dial.DialPointer.Pointer pin = new org.jfree.chart.plot.dial.DialPointer.Pointer(
				1);
		
		dialplot.addPointer(pin);

		JFreeChart jfreechart = new JFreeChart(dialplot);
		ChartPanel chartpanel = new ChartPanel(jfreechart);
		chartpanel.setPreferredSize(new Dimension(400, 400));				

		resp.setContentType("image/png");
		//ChartUtilities.writeChartAsPNG(out, jfreechart, 625, 500);		
		ChartUtilities.saveChartAsJPEG(new File("img/graficometa.jpg"),
				jfreechart, 230, 230);
		
		return jfreechart;
	}
}

Deve ser porque não estou passando o OutputStream? Como posso passar ele?

M

Basta ver como foi feito no exemplo que está funcionando.
Aparentemente, é só descomentar a linha que estaria fazendo isso

diogoprosoft

Executando direto pelo Servlet está funcionando

package com.br.isdra.piloto.servlet;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Image;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;

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 org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.dial.DialBackground;
import org.jfree.chart.plot.dial.DialPlot;
import org.jfree.chart.plot.dial.DialTextAnnotation;
import org.jfree.chart.plot.dial.StandardDialFrame;
import org.jfree.chart.plot.dial.StandardDialRange;
import org.jfree.chart.plot.dial.StandardDialScale;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.ui.GradientPaintTransformType;
import org.jfree.ui.StandardGradientPaintTransformer;

@WebServlet("/graficoJFreeChartServelt")
public class GraficoJFreeChartServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("image/jpeg");
			OutputStream out = response.getOutputStream();
			ChartUtilities.writeChartAsJPEG(out, criarGrafico(), 625, 500);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private JFreeChart criarGrafico() throws Exception {
		
		Double porcentagem = 1000D;
		DefaultValueDataset dataset1 = new DefaultValueDataset(porcentagem);
		DefaultValueDataset dataset2 = new DefaultValueDataset(500D);

		DialPlot dialplot = new DialPlot();
		dialplot.setView(0.0D, 0.0D, 1.0D, 1.0D);
		dialplot.setDataset(0, dataset1);
		dialplot.setDataset(1, dataset2);

		StandardDialFrame standarddialframe = new StandardDialFrame();
		standarddialframe.setBackgroundPaint(Color.lightGray);
		standarddialframe.setForegroundPaint(Color.GRAY);
		dialplot.setDialFrame(standarddialframe);

		GradientPaint gradientpaint = new GradientPaint(new Point(),
				new Color(255, 255, 255), new Point(), new Color(170, 170,
						220));
		DialBackground dialbackground = new DialBackground(gradientpaint);
		dialbackground
				.setGradientPaintTransformer(new StandardGradientPaintTransformer(
						GradientPaintTransformType.VERTICAL));
		dialplot.setBackground(dialbackground);

		DialTextAnnotation dialtextannotation = new DialTextAnnotation(
				"Meta");
		dialtextannotation.setFont(new Font("Dialog", 1, 14));
		dialtextannotation.setRadius(0.15D);
		dialplot.addLayer(dialtextannotation);

		Integer meta = 10000;
		DialTextAnnotation dialtextaMeta = new DialTextAnnotation("R$ "
				+ meta + "mi");
		dialtextaMeta.setFont(new Font("Dialog", 0, 14));
		dialtextaMeta.setRadius(0.30D);
		dialplot.addLayer(dialtextaMeta);

		StandardDialScale standarddialscale = new StandardDialScale(0, 150,
				270D, -300D, 10D, 1);
		standarddialscale.setTickRadius(0.88D);
		standarddialscale.setTickLabelOffset(0.18999999999999999D);
		standarddialscale.setTickLabelFont(new Font("Dialog", 0, 12));
		standarddialscale.setTickLabelFormatter(DecimalFormat
				.getNumberInstance());
		dialplot.addScale(0, standarddialscale);

		dialplot.mapDatasetToScale(1, 1);

		StandardDialRange standarddialrange = new StandardDialRange(100D,
				150D, Color.GREEN);

		standarddialrange.setScaleIndex(0);

		standarddialrange.setInnerRadius(0.50999999999999997D);
		standarddialrange.setOuterRadius(0.50999999999999997D);
		dialplot.addLayer(standarddialrange);
		
		StandardDialRange standarddialrangeb = new StandardDialRange(0D,
				100D, Color.RED);
		
		standarddialrangeb.setScaleIndex(0);

		standarddialrangeb.setInnerRadius(0.50999999999999997D);
		standarddialrangeb.setOuterRadius(0.50999999999999997D);
		dialplot.addLayer(standarddialrangeb);

		StandardDialScale standarddialscale1 = new StandardDialScale();
		standarddialscale1.setTickRadius(0.5D);
		standarddialscale1.setTickLabelOffset(0.14999999999999999D);
		standarddialscale1.setTickLabelFont(new Font("Dialog", 0, 10));
		standarddialscale1.setMajorTickPaint(Color.red);
		standarddialscale1.setMinorTickPaint(Color.red);
		dialplot.addScale(1, standarddialscale1);
		dialplot.mapDatasetToScale(1, 1);

		org.jfree.chart.plot.dial.DialPointer.Pointer pointer = new org.jfree.chart.plot.dial.DialPointer.Pointer(
				0);
		dialplot.addPointer(pointer);

		org.jfree.chart.plot.dial.DialPointer.Pointer pin = new org.jfree.chart.plot.dial.DialPointer.Pointer(
				1);
		
		dialplot.addPointer(pin);
		
		JFreeChart jfreechart = new JFreeChart(dialplot);
		ChartPanel chartpanel = new ChartPanel(jfreechart);
		chartpanel.setPreferredSize(new Dimension(400, 400));				
		
		return jfreechart;
	}
}

Porém abrindo pelo JSF não está funcionando, alguém sabe me dizer o pq?

Chamada JSF

<h:panelGroup style="text-align: center">
				<h:graphicImage value="/graficoJFreeChartServlet" />
				<br />
			</h:panelGroup>
diogoprosoft

Resolvido tava em cache o exemplo acima está correto.

Criado 12 de setembro de 2011
Ultima resposta 13 de set. de 2011
Respostas 5
Participantes 2