Friday, 7 October 2011

JFreeChart in Websphere Portal Server

JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications. JFreeChart is an open-source framework for the programming language Java, which allows the creation of a wide variety of both interactive and non-interactive charts.

Charts are available

1.       AreaChart
2.       BarChart.
3.       BarChart3D.
4.       BoxAndWhiskerChart
5.       BubbleChart
6.       CandlestickChart
7.       Gantt chart
8.       HighLowChart
9.       HistogramChart
10.   LineChart
11.   LineChart3D
12.   MultiplePieChart
13.   MultiplePieChart3D
14.   PieChart
15.   PieChart3D
16.   PolarChart
17.   RingChart
18.   ScatterPlot
19.   StackedAreaChart
20.   StackedBarChart3D
21.   StackedXYAreaChart
22.   TimeSeriesChart
23.   WaferMapChart
24.   WaterfallChart
25.   WindPlotChart
26.   XYAreaChart
27.   XYLineChart
28.   XYStepAreaChart 

In this example,i have drawn few charts using JSR 286API Portlet.

Required libraries  for drawing charts:
Sample code:

In this example,i have create mutiple charts by calling a resourceserve url with multiple resource.

package com.ibm.jfreechart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.io.*;
import java.util.*;
import javax.portlet.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * A sample portlet based on GenericPortlet
 */
public class JFreeChartPortlet extends GenericPortlet {

    public static final String JSP_FOLDER    = "/_JFreeChart/jsp/";    // JSP folder name

    public static final String VIEW_JSP      = "JFreeChartPortletView";         // JSP file name to be rendered on the view mode
    public static final String SESSION_BEAN  = "JFreeChartPortletSessionBean";  // Bean name for the portlet session
    public static final String FORM_SUBMIT   = "JFreeChartPortletFormSubmit";   // Action name for submit form
    public static final String FORM_TEXT     = "JFreeChartPortletFormText";     // Parameter name for the text input
    /**
     * @see javax.portlet.Portlet#init()
     */
    public void init() throws PortletException{
        super.init();
    }

    /**
     * Serve up the <code>view</code> mode.
     *
     * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
     */
    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        // Set the MIME type for the render response
        response.setContentType(request.getResponseContentType());

        // Check if portlet session exists
        JFreeChartPortletSessionBean sessionBean = getSessionBean(request);
        if( sessionBean==null ) {
            response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
            return;
        }
            PrintWriter writer=response.getWriter();
             ResourceURL resURL = response.createResourceURL();
            resURL.setResourceID("pie");
            writer.println("<IMG src=\""+resURL+"\"><br/>");
            resURL.setResourceID("bar");
            writer.println("<IMG src=\""+resURL+"\"><br/>");
            resURL.setResourceID("XYArea");
            writer.println("<IMG src=\""+resURL+"\"><br/>");
            resURL.setResourceID("XYLine");
            writer.println("<IMG src=\""+resURL+"\"><br/>");
            resURL.setResourceID("bar3d");
            writer.println("<IMG src=\""+resURL+"\"><br/>");
    }

    /**
     * Process an action request.
     *
     * @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
     */
    public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
        if( request.getParameter(FORM_SUBMIT) != null ) {
            // Set form text in the session bean
            JFreeChartPortletSessionBean sessionBean = getSessionBean(request);
            if( sessionBean != null )
                sessionBean.setFormText(request.getParameter(FORM_TEXT));
        }
    }

    /**
     * Get SessionBean.
     *
     * @param request PortletRequest
     * @return JFreeChartPortletSessionBean
     */
    private static JFreeChartPortletSessionBean getSessionBean(PortletRequest request) {
        PortletSession session = request.getPortletSession();
        if( session == null )
            return null;
        JFreeChartPortletSessionBean sessionBean = (JFreeChartPortletSessionBean)session.getAttribute(SESSION_BEAN);
        if( sessionBean == null ) {
            sessionBean = new JFreeChartPortletSessionBean();
            session.setAttribute(SESSION_BEAN,sessionBean);
        }
        return sessionBean;
    }

    /**
     * Returns JSP file path.
     *
     * @param request Render request
     * @param jspFile JSP file name
     * @return JSP file path
     */
    private static String getJspFilePath(RenderRequest request, String jspFile) {
        String markup = request.getProperty("wps.markup");
        if( markup == null )
            markup = getMarkup(request.getResponseContentType());
        return JSP_FOLDER + markup + "/" + jspFile + "." + getJspExtension(markup);
    }

    /**
     * Convert MIME type to markup name.
     *
     * @param contentType MIME type
     * @return Markup name
     */
    private static String getMarkup(String contentType) {
        if( "text/vnd.wap.wml".equals(contentType) )
            return "wml";
        else
            return "html";
    }

    /**
     * Returns the file extension for the JSP file
     *
     * @param markupName Markup name
     * @return JSP extension
     */
    private static String getJspExtension(String markupName) {
        return "jsp";
    }
   
   
    public JFreeChart createPieChart() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Ford", 23.3);
        dataset.setValue("Chevy", 32.4);
        dataset.setValue("Yugo", 44.2);
        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;
        JFreeChart chart = ChartFactory.createPieChart("Cars", dataset, legend, tooltips, urls);
        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);
        return chart;
    }

    private JFreeChart createBarChart() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        // row keys...
        String series1 = "First";
        String series2 = "Second";
        // column keys...
        String category1 = "Label1";
        dataset.addValue(1.0, series1, category1);
        dataset.addValue(5.0, series2, category1);
        JFreeChart chart = ChartFactory.createBarChart("Bar Chart", // chart
                // title
                "Labels", // domain axis label
                "Values", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
                );

        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.white);
        return chart;
    }

    private JFreeChart createXYAreaChart() {
        XYSeries series = new XYSeries("Average Weight");
          series.add(20.0, 20.0);
          series.add(40.0, 25.0);
          series.add(55.0, 50.0);
          series.add(70.0, 65.0);
          XYDataset xyDataset = new XYSeriesCollection(series);
          JFreeChart chart = ChartFactory.createXYAreaChart
          ("XY Chart using JFreeChart", "Age", "Weight",
           xyDataset, PlotOrientation.VERTICAL, true,  true, false);
        return chart;
    }

    private JFreeChart createXYLineChart()
    {
        XYSeries series = new XYSeries("Average Weight");
          series.add(20.0, 20.0);
          series.add(40.0, 25.0);
          series.add(55.0, 50.0);
          series.add(70.0, 65.0);
          XYDataset xyDataset = new XYSeriesCollection(series);
          JFreeChart chart = ChartFactory.createXYLineChart
          ("XYLine Chart using JFreeChart", "Age", "Weight",
         xyDataset, PlotOrientation.VERTICAL, true, true, false);
          return chart;
    }
   
    private JFreeChart createBarChart3D()
    {
         DefaultCategoryDataset dataset = new DefaultCategoryDataset();
          dataset.setValue(6, "Science", "Rahul");
          dataset.setValue(8, "Maths", "Rahul");
          dataset.setValue(5, "Science", "Deepak");
          dataset.setValue(3, "Maths", "Deepak");
          dataset.setValue(6, "Science", "Vinod");
          dataset.setValue(9, "Maths", "Vinod");
          dataset.setValue(2, "Science", "Chandan");
          dataset.setValue(4, "Maths", "Chandan");
          JFreeChart chart = ChartFactory.createBarChart3D
          ("Comparison between Students","Students", "Marks",
          dataset, PlotOrientation.VERTICAL, true,true, false);
          return chart;
    }
    @Override
    public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
        if(request.getResourceID().equals("pie"))
        {
        response.setContentType("image/png");
        OutputStream outputStream = response.getPortletOutputStream();
        JFreeChart chart = createPieChart();
        int width = 500;
        int height = 350;
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        else if(request.getResourceID().equals("bar"))
        {
        response.setContentType("image/png");
        OutputStream outputStream = response.getPortletOutputStream();
        JFreeChart chart = createBarChart();
        int width = 300;
        int height = 300;
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }   
        else if(request.getResourceID().equals("XYArea"))
        {
            response.setContentType("image/png");
            OutputStream outputStream = response.getPortletOutputStream();
            JFreeChart chart = createXYAreaChart();
            int width = 300;
            int height = 300;
            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        else if(request.getResourceID().equals("XYLine"))
        {
            response.setContentType("image/png");
            OutputStream outputStream = response.getPortletOutputStream();
            JFreeChart chart = createXYLineChart();
            int width = 300;
            int height = 300;
            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        else if(request.getResourceID().equals("XYLine"))
        {
            response.setContentType("image/png");
            OutputStream outputStream = response.getPortletOutputStream();
            JFreeChart chart = createXYLineChart();
            int width = 300;
            int height = 300;
            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        else if(request.getResourceID().equals("bar3d"))
        {
            response.setContentType("image/png");
            OutputStream outputStream = response.getPortletOutputStream();
            JFreeChart chart = createBarChart3D();
            int width = 300;
            int height = 300;
            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
}

ScreenShot

Click to download the source code






No comments:

Post a Comment