使用JFreeChart来创建基于web的带交互功能的PIE图表(二)

来源:互联网 发布:json怎么调用接口数据 编辑:程序博客网 时间:2024/06/06 01:06

下面是一个通用的饼图生成sevlet
用法是<IMG alt="Pie chart of summary by reason" useMap=#svcGroupCodeMap border=0
            src="pieChart?width=760&height=200&formName=eRAMMISummaryReasonCodeForm&property=result&field1=reasonCode&field2=totalCharge&elemCount=5&numFlag=$&showPercent=true&mapName=svcGroupCodeMap&linkBase=mmiSummaryByReason.do&linkParaKey=svcGroupCode" />
  pieChart在session内存中生成了一个图形的MAP对象,如果要使用则应放在最后面并有一段延时:
<%
try{
out.flush();
java.lang.Thread.sleep(1000);
}
catch (Exception delayEx){

}
%>
            <logic:notEmpty name="svcGroupCodeMap" scope="session">
                <bean:write name="svcGroupCodeMap" scope="session" filter="false"/>
            </logic:notEmpty>


下面的这个这个通用的饼图sevlet的代码,基本思路是利用Session中的一些数据生成饼图,formName一般是struts中的一个form, property是这个form中的一个List对象它保存有一系列饼图需要的数据,field1,field2指的是List元素中的两个属性用来提取饼图需求的数据,其它的参数可有可无,不重要, mapName表示需求生成img的MAP图 .
package com.medi.TO.TOOL;

import java.io.*;
import java.lang.reflect.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.awt.*;

import org.jfree.chart.*;
import org.jfree.chart.labels.*;
import org.jfree.chart.plot.*;
import org.jfree.data.*;
import org.jfree.chart.urls.StandardPieURLGenerator;
/**
 * Title: 
 * Description: send a PIE chart to brower show the data from session of request refer to

 * Copyright: Copyright (c) 2004
 * Company: medi.com
 * @author Xuxi.Chen
 * @version 1.0
 */
public class PieChartServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "image/png";

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException {
        execute(request, response);
    }

    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException {
        execute(request, response);
    }

    public void execute(HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException {
        try {
            String title = request.getParameter("title");
            String formName = request.getParameter("formName");
            boolean bLegend = true;
            if (request.getParameter("legend") != null && request.getParameter("legend").equals("false")) {
                bLegend = false;
            }
            boolean bShowLabel = true;
            if (request.getParameter("showLabel") != null && request.getParameter("showLabel").equals("false")) {
                bShowLabel = false;
            }
            int iLegDire = 3;
            if (request.getParameter("legDire") != null) {
                try {
                    iLegDire = Integer.parseInt(request.getParameter("legDire"));
                } catch (NumberFormatException ex2) {
                }
            }
            boolean bShowPercent = false;
            if (request.getParameter("showPercent") != null && request.getParameter("showPercent").equals("true")) {
                bShowPercent = true;
            }
            int iLabelHeight = 10;
            if (request.getParameter("labelHeight") != null) {
                try {
                    iLabelHeight = Integer.parseInt(request.getParameter("labelHeight"));
                } catch (NumberFormatException ex2) {
                }
            }
            int elemCount = 100;
            if (request.getParameter("elemCount") != null) {
                try {
                    elemCount = Integer.parseInt(request.getParameter("elemCount"));
                } catch (NumberFormatException ex3) {
                }
            }
            HttpSession session = request.getSession();
            Object formInSession = session.getAttribute(formName);
            String propName = request.getParameter("property");
            String methodName1 = getGetMethodName(request.getParameter("field1"));
            String methodName2 = getGetMethodName(request.getParameter("field2"));
            Method m = formInSession.getClass().getMethod(getGetMethodName(propName),
                new Class[0]);
            Collection coll = (Collection) m.invoke(formInSession, null);
            DefaultPieDataset data = getDataSet(coll, methodName1, methodName2, elemCount);
            JFreeChart chart = ChartFactory.createPieChart3D(title,
                data,
                bLegend,
                false,
                false
                );
            int width = 400;
            int height = 300;
            try {
                width = Integer.parseInt(request.getParameter("width"));
                height = Integer.parseInt(request.getParameter("height"));
            } catch (NumberFormatException ex) {
            }
            PiePlot pie = (PiePlot) chart.getPlot();
            //pie.setSectionLabelType(PiePlot.NAME_AND_PERCENT_LABELS);
            //pie.setSectionLabelType(PiePlot.VALUE_AND_PERCENT_LABELS);
            pie.setInteriorGap(0.15);
            if (!bShowLabel) {
                pie.setLabelGenerator(null);
            }
            String numFlag = "";
            if (request.getParameter("numFlag") != null) {
                numFlag = request.getParameter("numFlag");
            }
            if (bShowPercent) {
                pie.setLabelGenerator(new StandardPieItemLabelGenerator(
                    "{0}=" + numFlag + "{1}({2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()
                    ));
            } else {
                pie.setLabelGenerator(new StandardPieItemLabelGenerator(
                    "{0}=" + numFlag + "{1}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()
                    ));
            }
            pie.setInteriorGap(0.23);
            pie.setLabelFont(new Font("dialog", Font.TRUETYPE_FONT, iLabelHeight));
            pie.setMaximumLabelWidth(0.3);
            //pie.setLabelGap(0.0);
            chart.getLegend().setAnchor(iLegDire);
            chart.setBackgroundPaint(java.awt.Color.white);

            if (request.getParameter("fieldColor") != null) {
                String colorMethodName = getGetMethodName(request.getParameter("fieldColor"));
                setPieSecColor(coll, pie, colorMethodName);
            }

            String mapName = request.getParameter("mapName");
            ChartRenderingInfo info = null;
            if(mapName != null && mapName.length() > 0){
                info = new ChartRenderingInfo();
                String linkBase = request.getParameter("linkBase");
                String linkParaKey = request.getParameter("linkParaKey"); // would like "svcCodeGroup"
                pie.setURLGenerator(new  StandardPieURLGenerator(linkBase,linkParaKey));
            }

            //response.setDateHeader("Expires", System.currentTimeMillis());
            //response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
            response.reset();
            response.setHeader("Cache-Control", "no-store"); //HTTP 1.1
            response.setHeader("Pragma", "no-cache"); //HTTP 1.0
            response.setDateHeader("Expires", 0); //prevents caching at the proxy server
            response.setContentType(CONTENT_TYPE);
            ChartUtilities.writeChartAsPNG(response.getOutputStream(),
                                           chart, width, height, info);
            if(info != null){
                StringWriter strWriter = new java.io.StringWriter();
                PrintWriter w  =  new java.io.PrintWriter(strWriter);
                ChartUtilities.writeImageMap(w,  mapName,  info);
                w.close();
                strWriter.close();
                request.getSession().setAttribute(mapName, strWriter.getBuffer());
            }
        }
        catch (java.net.SocketException ex1){
        }
        catch (Exception ex1) {
            ex1.printStackTrace(System.out);
        }

    }

    private void setPieSecColor(Collection coll, PiePlot pie, String colorMethodName) {
        try {
            Iterator iter = coll.iterator();
            int iRow = 0;
            while (iter.hasNext()) {
                Object item = (Object) iter.next();
                Method m1 = item.getClass().getMethod(colorMethodName, new Class[0]);
                Color clr = (Color) m1.invoke(item, null);
                pie.setSectionPaint(iRow, clr);
                iRow++;
            }
        } catch (Exception ex2) {
            ex2.printStackTrace();
        }
    }

    private String getGetMethodName(String name) {
        StringBuffer strBuf = new StringBuffer("get");
        strBuf.append(name);
        char ch0 = name.charAt(0);
        ch0 = java.lang.Character.toUpperCase(ch0);
        strBuf.setCharAt(3, ch0);
        return strBuf.toString();
    }

    private static DefaultPieDataset getDataSet(Collection coll, String methodName1, String methodName2, int elemCount) throws
        Exception {
        DefaultPieDataset dataset = new DefaultPieDataset();
        int iCount = 0;
        Iterator iter = coll.iterator();
        while (iter.hasNext()) {
            if (iCount >= elemCount) {
                break;
            }
            Object item = (Object) iter.next();
            Method m1 = item.getClass().getMethod(methodName1, new Class[0]);
            java.lang.Comparable data1 = (Comparable) m1.invoke(item, null);
            if (data1 == null) {
                data1 = "";
            }
            Method m2 = item.getClass().getMethod(methodName2, new Class[0]);
            Number data2 = (Number) m2.invoke(item, null);
            //dataset.setValue(data1.toString().trim(), data2);
            //System.out.println("data1="+data1+" data2="+data2);
            double data = data2.doubleValue();
            if(data < 0){
                data *= -1.0;
            }
            dataset.setValue(data1.toString().trim(), data);
            iCount++;
        }
        return dataset;
    }

}