Interview Questions

Spring JFreeChart Integration

In this article let's discuss about how to integrate JFreeChart API with Spring framework.

What is JFreeChart?

JFreeChart is an API used for creating and displaying charts such as bar, pie etc in java applications. It supports several output types like Swing components, image files (including PNG and JPEG), and vector graphics file formats (including PDF, EPS and SVG). JFreeChart is an open source distributed under the terms of (LGPL).

Lets consider an example to display a Bar and Pie chart using JFreeChart in Spring Application.

Consider the ChartController class as follows.

ChartController.java

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSES ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.spring.example;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.keypoint.PngEncoder;

public class ChartController extends MultiActionController
{
        public void getBarChartView(HttpServletRequest request, HttpServletResponse response) throws Exception
        {

                System.out.println("In Chart View Controller");

                DefaultCategoryDataset dataset = new DefaultCategoryDataset();

                dataset.addValue(1.0, "1985-90", "1985-90");

                dataset.addValue(2.5, "1990-95", "1990-95");

                dataset.addValue(4.0, "1995-2000", "1995-2000");

                dataset.addValue(5.0, "2000-05", "2000-05");

                final JFreeChart chart = ChartFactory.createBarChart("Bar Chart", "Year", "Population (in millions)",
                dataset, PlotOrientation.VERTICAL, true, true, false);

                chart.setBackgroundPaint(Color.white);
                final TextTitle subtitle = new TextTitle(
                " The below Bar Chart shows population growth in Chennai(India), every 5 years from 1985 .");
                subtitle.setFont(new Font("SansSerif", Font.PLAIN, 12));

                chart.addSubtitle(subtitle);

                final CategoryPlot plot = chart.getCategoryPlot();
                plot.setForegroundAlpha(0.5f);

                plot.setBackgroundPaint(Color.lightGray);
                plot.setDomainGridlinesVisible(true);
                plot.setDomainGridlinePaint(Color.white);
                plot.setRangeGridlinesVisible(true);
                plot.setRangeGridlinePaint(Color.white);

                final CategoryAxis domainAxis = plot.getDomainAxis();
                domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
                domainAxis.setLowerMargin(0.0);
                domainAxis.setUpperMargin(0.0);

                final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();

                rangeAxis.setLabelAngle(1 * Math.PI / 2.0);

                ChartRenderingInfo info = null;

                info = new ChartRenderingInfo(new StandardEntityCollection());
                response.setContentType("image/png");
                BufferedImage chartImage = chart.createBufferedImage(700, 400, info);

                PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);

                response.getOutputStream().write(encoder.pngEncode());
        }

        public void getPieChartView(HttpServletRequest request, HttpServletResponse response) throws Exception
        {
                System.out.println("In Chart View Controller");

                final DefaultPieDataset dataset = new DefaultPieDataset();
                dataset.setValue("1985-90", new Double(1.02));
                dataset.setValue("1990-95", new Double(2.5));
                dataset.setValue("1995-2000", new Double(4.0));
                dataset.setValue("2000-2005", new Double(5.0));

                final JFreeChart chart = ChartFactory.createPieChart3D("Pie Chart ", dataset, true, true, false);

                chart.setBackgroundPaint(Color.white);
                final TextTitle subtitle = new TextTitle(
                " The below Pie Chart shows population growth in Chennai(India), every 5 years from 1985 .");
                subtitle.setFont(new Font("SansSerif", Font.PLAIN, 12));

                chart.addSubtitle(subtitle);

                ChartRenderingInfo info = null;

                info = new ChartRenderingInfo(new StandardEntityCollection());
                response.setContentType("image/png");
                BufferedImage chartImage = chart.createBufferedImage(700, 400, info);

                PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);

                response.getOutputStream().write(encoder.pngEncode());
        }
}

The above class is a Spring controller class, which extends MultiActionController. It consist of two methods

1. getBarChartView - to display a Bar Chart
2. getPieChartView - to display a Pie Chart

Both the methods return void, meaning we are committing the response to the ServelOutPutStream, so that the chart gets displayed in the view. We have used PNGEncoder class to convert the BufferedChartImage in to PNG format, so that it can be displayed in the browser. We need to the set the content type of the response to "image/png".

Have a look at the spring configuration file as follows.

springChart-Context.xml

<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="urlMap">
      <map>
       <entry key="/barChart.htm" value-ref = "chartController"/>
       <entry key="/pieChart.htm" value-ref = "chartController"/>
      </map>
   </property>
</bean>

<bean id="chartController" class="in.techdive.spring.example.ChartController">
  <property name="methodNameResolver">
        <bean id="schemaMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
        <property name="mappings">
                <props>
                   <prop key="/barChart.htm">getBarChartView</prop>
                   <prop key="/pieChart.htm">getPieChartView</prop>
                </props>
        </property>
        </bean>
  </property>
</bean>
   
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"> </property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>        
</bean>

In this way we can integrate JFreeChart with spring application.

Note: Please include jcommon-1.0.0.jar, jfreechart-1.0.1.jar in the library path.