JfreeChart on GWT (Google Web Toolkit)

A free public discussion forum for the JFreeChart class library.

JfreeChart on GWT (Google Web Toolkit)

Postby williamreg » Fri Oct 13, 2006 10:24 am

I can dispaly JFreechart on GWT with org.jfree.chart.servlet.DisplayChart but not the image map. Any one has an idea on this? Thanks.


Module
Code: Select all
<servlet path='/displayChart' class='org.jfree.chart.servlet.DisplayChart'/>


Server code
Code: Select all
public  String getChart() {
JFreeChart chart = AreaChartDemo1.createChart();
      
// save chart to web server
try {
      // Write the chart image to the temporary directory
     ChartRenderingInfo info =
          new ChartRenderingInfo(new StandardEntityCollection());
     HttpSession session = getThreadLocalRequest().getSession();
     chartName = ServletUtilities.saveChartAsPNG(
          chart, 500, 350, info, session);         
     HttpServletResponse response = getThreadLocalResponse();
     ServletOutputStream os = response.getOutputStream();
     Writer w = new OutputStreamWriter(os);
     PrintWriter writer = new PrintWriter(w);
     ImageMapUtilities.writeImageMap(writer, chartName, info,false);   
} catch (Exception e) {
   // handle your exception here }          
   
return "<img style=\"border: 0;\" src=\"./displayChart?filename=" +
     chartName + "\" " + "usemap=\"#./displayChart?filename=" +
     chartName + "\" " + "/>";
}


Client Code
Code: Select all
public VerticalPanel getDemoChart(){
      
  final VerticalPanel panel = new VerticalPanel();
  AsyncCallback callback = new AsyncCallback(){

      public void onFailure(Throwable caught) {
           Window.alert("An internal error has occurred" );}
   
     public void onSuccess(Object result) {
           String str = (String)result;
           panel.add(new HTML(str));      
      }           
  };
      
  myService.getChart(callback);
      
  return panel;
}

williamreg
 
Posts: 3
Joined: Fri Oct 13, 2006 9:52 am
Location: Singapore

Postby angel » Fri Oct 13, 2006 11:32 am

Code: Select all
"usemap=\"#./displayChart?filename=" +
     chartName + "\" " + "/>";


What is the generatedd html-code for "usemap"?
angel
 
Posts: 899
Joined: Thu Jan 15, 2004 12:07 am
Location: Germany - Palatinate

Postby williamreg » Fri Oct 13, 2006 12:28 pm

The generated code is

Code: Select all
<img style="border: 0;" src="./displayChart?filename=jfreechart-61045.png" usemap="#./displayChart?filename=jfreechart-61045.png" />


src is okay but usemap is not. I also do not see any image map code appeared from the HTML page rendered by GWT.
williamreg
 
Posts: 3
Joined: Fri Oct 13, 2006 9:52 am
Location: Singapore

Postby angel » Fri Oct 13, 2006 1:42 pm

I don't know anything about GWT, but I have 2 reamarks:

1) Your "usemap" parameter is compleatly wrong. Should be the name of the map.

2) You create a new ServletOutputStream but I suppose this is the main problem. Your method returns a string so I assume there is already a ServletOutputStruam.
angel
 
Posts: 899
Joined: Thu Jan 15, 2004 12:07 am
Location: Germany - Palatinate

Postby williamreg » Sat Oct 14, 2006 7:51 am

Thanks to Angel for highlighting the error.

I've solve the problem.

Remove
Code: Select all
HttpServletResponse response = getThreadLocalResponse();
ServletOutputStream os = response.getOutputStream();
Writer w = new OutputStreamWriter(os);
PrintWriter writer = new PrintWriter(w);
ImageMapUtilities.writeImageMap(writer, chartName, info,false);


Add
Code: Select all
String usemap= ChartUtilities.getImageMap(chartName,info);


Change
Code: Select all
return "<img style=\"border: 0;\" src=\"./displayChart?filename=" +
chartName + "\" " + "usemap=\"#" +  chartName + "\" /> " + usemap ;


result
Code: Select all
<img style="border: 0;" src="./displayChart?filename=jfreechart-26849.png" usemap="#jfreechart-26849.png" /> <map id="jfreechart-26849.png" name="jfreechart-26849.png">
<area shape="poly" coords="480,106,486,106,486,112,480,112,480,106,480,106" title="Series 1 Jun-2006 805" alt=""/>
<area shape="poly" coords="394,173,400,173,400,179,394,179,394,173,394,173" title="Series 1 May-2006 732" alt=""/>
<area shape="poly" coords="310,99,316,99,316,105,310,105,310,99,310,99" title="Series 1 Apr-2006 813" alt=""/>
<area shape="poly" coords="224,235,230,235,230,241,224,241,224,235,224,235" title="Series 1 Mar-2006 664" alt=""/>
<area shape="poly" coords="146,35,152,35,152,41,146,41,146,35,146,35" title="Series 1 Feb-2006 883" alt=""/>
<area shape="poly" coords="60,106,66,106,66,112,60,112,60,106,60,106" title="Series 1 Jan-2006 805" alt=""/>
</map>

williamreg
 
Posts: 3
Joined: Fri Oct 13, 2006 9:52 am
Location: Singapore

Postby angel » Mon Oct 16, 2006 7:29 am

I'm glad I could help :D
angel
 
Posts: 899
Joined: Thu Jan 15, 2004 12:07 am
Location: Germany - Palatinate

GWT and JFreechart

Postby saritha517 » Tue Dec 05, 2006 12:27 am

Could you please post your whole code? I am trying to integrate GWT and JFreechart. I would like to know how interactive the UI could be with GWT. We are trying to decide betn Applet and Ajax.

Thanks.
saritha517
 
Posts: 1
Joined: Tue Dec 05, 2006 12:25 am

Postby alg0 » Wed Dec 06, 2006 11:52 pm

Yeap i'm also interested in some simple code to build it up to my needs. Also sent you a personal message...
alg0
 
Posts: 1
Joined: Wed Dec 06, 2006 11:08 pm

Postby equuelus » Wed Dec 27, 2006 10:03 am

I'm also interested in this!
equuelus
 
Posts: 1
Joined: Wed Dec 27, 2006 10:01 am

can i get a more detailed example from anyone

Postby jansyndesis » Tue Jan 09, 2007 1:42 am

hello,

i have tried this example, gettin the result back(in string - looks fine) but having issues displaying the chart

would anybody share in detail the code that worked for them

please feel free to contact me directly? does the developer guide that is available for purchase give a proper working example for GWT + JFree?

Thank you,
Jan Banda
jansyndesis
 
Posts: 1
Joined: Tue Jan 09, 2007 1:34 am

Re: can i get a more detailed example from anyone

Postby angel » Tue Jan 09, 2007 10:20 am

jansyndesis wrote:does the developer guide that is available for purchase give a proper working example for GWT + JFree?


Not in the last 1.02 version.
angel
 
Posts: 899
Joined: Thu Jan 15, 2004 12:07 am
Location: Germany - Palatinate

GWT + JFreeChart

Postby ksiomelo » Tue Feb 20, 2007 6:30 pm

I would like to get this code! Does someone know any tutorial?

Thanks!
ksiomelo
 
Posts: 1
Joined: Tue Feb 20, 2007 6:27 pm

Postby justindsmith » Sat Feb 24, 2007 12:03 am

I've just recently created a tutorial / starting example on how to get the two working together for some documentation I'm having to put together. Hopefully it will get you going. I used a lot of the information from this thread to get me going, but I had to fill in the missing details.

Oh, and it should be noted that the code provided was written from memory. In other words, I'm dumbing down my working code to make the example easier. So while I'm pretty sure everything is going to work, there might be a few minor hitches along the way for you. The idea is all there though. Feel free to post corrections or updates and I'll try to keep them all updated.

I'll post it in full... now:

GWT and JFreeChart

This article describes how to integrate JFreeChart and GWT. It assumes development is being done in Eclipse. It also assumes that the reader has an understanding on how Remote Procedure Calls (RPCs) are created and accessed in GWT. For more information on this, go to the GWT Developer Guide (apparently I can't have urls in my post since I'm new, so just do a web search and find it) and follow the Remote Procedure Calls link.

The included example will create two services running as servlets. The first service will be a chart generator service that has one function, which generates a standard pie chart with data created on the server. It will store the pie chart as an image and return the name of the image to the GWT caller. The second service will - given the chart name - return the image data, allowing it to be displayed.

Download JFreeChart

Get the latest JFreeChart version. Be sure to get the package that contains the latest JCommon version. Unpack the download, which will leave you with a number of JARs. For the included example, you will only be concerned with `jfreechart-{version}.jar` and `jcommon-{version}.jar`.

Update Project Classpath

Update your project's classpath with references to the two JARs mentioned above.

Create Chart Generator Service

Create a service interface for generating charts. The service will create the chart and store it on the server, so it should return the name of the chart that it generates.

For this example, there will only be one function and it will accept no parameters. All of the data for the chart will be created on the server. In the real world, this function could receive a collection objected containing the dataset the caller wishes to be plotted. It could also allow the caller to pass in chart display properties to affect how the chart is presented, such as dimensions and colors.

Note: It is important to understand how GWT creates RPCs for the following code examples.

Create the interface (client):

Code: Select all
package com.example.client;

import com.google.gwt.user.client.rpc.RemoteService;

public interface ChartGenerator extends RemoteService {
    public String generateChart();
}

Create the asynchronous implementation interface (client):

Code: Select all
package com.example.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

public interface ChartGeneratorAsync {
    public void generateChart(AsyncCallback callback);
}

Create the implementation of the interface (server):

Code: Select all
package com.example.server;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.general.DefaultPieDataset;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import com.example.client.ChartGenerator;

public class ChartGeneratorImpl extends RemoteServiceServlet implements ChartGenerator {
    public String generateChart() {
        /*
         * Hold our stored chart name, it will be returned to the GWT caller.
         */
        String chartName = "";
       
        /*
         * Create the data for this example.
         */
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("One", 10.0);
        dataset.setValue("Two", 50.0);
        dataset.setValue("Three", 30.0);

        /*
         * Generate the generic pie chart.
         */
        JFreeChart chart = ChartFactory.createPieChart("New Pie Chart", dataset, false, false, false);
       
        /*
         * Save the chart as an '300px x 250px' jpeg image.
         */
        try {
            HttpSession session = getThreadLocalRequest().getSession();
            chartName = ServletUtilities.saveChartAsJPEG(chart, 300, 250, null, session);
        } catch(Exception e) {
            // handle exception
        }

        /*
         * Finally, return the chart name to the caller.
         */
        return chartName;
    }
}

Your chart generator service is now complete, all that is needed now is to define the service in the `.gwt.xml` module descriptor.

Code: Select all
<servlet path='/chartGenerator'
         class='com.example.server.ChartGeneratorImpl'/>

Setup Chart Display Service

JFreeChart provides a servlet for displaying a previously stored chart. All you need to do is call the service, providing the chart name as a parameter. So simply define the service in your module descriptor as follows.

Code: Select all
<servlet path='/displayChart'
         class='org.jfree.chart.servlet.DisplayChart'/>

Making a Call from the Client

Now that the services have been defined, implemented, and deployed, all that is left is to make calls from the client to the services.

For this example, we'll create a new `Widget` called `ChartImage` which will - in its constructor - setup a connection to the chart generator service, make a call to the service to generate a new chart, receive the new chart's name back from the generator service, and finally use the chart display service to add the chart on the client side.

To use the chart display service, you simply need to set your image source to call the service with the proper parameters. For our example, this will look as follows.

Code: Select all
<img src="./displayChart?filename={chart-name}"/>

Note: It is important to understand how GWT use RPCs for the following code examples.

Code: Select all
package com.example.client;

import com.google.gwt.user.client.ui.Image;

public class ChartImage extends Image {

    private ChartGeneratorAsync chartGeneratorService;

    public ChartImage() {
        super();
       
        /*
         * Setup connection to chart generator service.
         */
        chartGeneratorService = (ChartGeneratorAsync) GWT.create(ChartGenerator.class);
        ServiceDefTarget endpoint = (ServiceDefTarget)chartGeneratorService;
        String url = GWT.getModuleBaseURL() + "chartGenerator";
        endpoint.setServiceEntryPoint(url);

        /*
         * Setup the callback from the chart generator service.
         */
        AsyncCallback callback = new AsyncCallback() {
            /*
             * If the call was successful, we will get back the name of the chart
             * that was created and stored on the server.
             */
            public void onSuccess(Object s) {
                String chartName = (String)s;
                String imageUrl = "./displayChart?filename=" + chartName;
                setUrl(imageUrl);
            }
           
            /*
             * Something went wrong with the call. Handle the issue how you'd like.
             */
            public void onFailure(Throwable ex) {
                // do nothing for now
            }
        };
       
        /*
         * Make the call to the chart generator service with the previously created
         * callback.
         */
        chartGeneratorService.generateChart(callback);

        /*
         * Since we've made an asynchronous call, we don't need to do anything further.
         * The callback object will handle the remainder of the work for us.
         */
    }
}

In the example above, the image will not be shown until the callback is run, since we didn't include any initial setup code. We could, for example, choose to start the image with a loading icon, which would change into the chart itself once the asynchronous callback is run.

Deploy Project

And that's it! You can now compile and run your code!

Hopefully this helps you get started down a workable path.
justindsmith
 
Posts: 1
Joined: Fri Feb 23, 2007 11:44 pm

Thanks

Postby f3rg13 » Thu Aug 23, 2007 9:58 am

hey, I actually just joined to say thanks. thank you, thank you. Great help!!!
f3rg13
 
Posts: 1
Joined: Thu Aug 23, 2007 9:55 am

GWT and jfreechart servlet error

Postby tking » Fri Oct 19, 2007 4:19 pm

First, thanks for the documentation and code example. I was able to integrate your example code into my app but I seem to have an issue with the entry in the xml module:

Code: Select all
<servlet path='/displayChart' class='org.jfree.chart.servlet.DisplayChart'/>


When I compile (both server and client) and run in hosted mode, I get the following error messsage.

Code: Select all
[ERROR] Unable to instantiate 'org.jfree.chart.servlet.DisplayChart'
java.lang.ClassNotFoundException: org.jfree.chart.servlet.DisplayChart


I have the jar in both my referenced libraries and in the APPDIR. What is causing this error?

TNX
tking
 
Posts: 1
Joined: Thu Oct 18, 2007 6:34 pm
Location: Houston, TX

Next

Return to JFreeChart - General

Who is online

Users browsing this forum: No registered users and 2 guests