码迷,mamicode.com
首页 > 编程语言 > 详细

Java封装FushionCharts

时间:2015-03-20 12:55:50      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:fusioncharts   xml   json   java   报表   

最近公司接了个关于数据统计的系统,需要用到报表功能,找了几天觉得还是FushionCharts

适合,所以就对FushionCharts进行了java代码封装,方便,前台,后台调用。


1.报表Model 文件,数据封装

package hh.com.fushionchart.Model;
/**
 * 报表Model 文件,数据封装
 * @author 尹晶晶
 *
 */
public class FChart {
	/**
	 * 报表swf文件,默认线形图
	 */
	private String fileName="MSLine.swf";
	
	/**
	 * 数据
	 */
	private String xmlData="";//数据
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getXmlData() {
		return xmlData;
	}
	public void setXmlData(String xmlData) {
		this.xmlData = xmlData;
	}
	/**
	 * Model转成JSON
	 * @return
	 */
	public String getJSON(){
		return "{\"fileName\":\""+this.fileName+"\",\"xmlData\":\""+this.xmlData+"\"}";
	}
}


2.FushionChart功能报表封装

package hh.com.fushionchart;


import hh.com.carrier.DataTable;
import hh.com.carrier.SHashMap;
import hh.com.control.flashchart.model.AmbarDataSetModel;
import hh.com.control.flashchart.model.AmlineDataSetModel;
import hh.com.control.flashchart.model.AmpieDataSetModel;
import hh.com.control.flashchart.util.FlashChartHandler;
import hh.com.fushionchart.Model.FChart;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 画图工具,主要用来画二维和三维图形(饼状图,柱状图,曲线图) 使用说明:
 * 1,创建该类的一个构造函数,如果构造函数里的参数不是你想要的,你可以通过get/set方法设置. 2, 根据自己的需要画什么样的图就调用什么方法。 3,
 * 例子: DrawDesigns d = new DrawDesigns(......); String str = d.drawPie2D();
 * 这个str参数就是全部数据,前台可以直接使用这个参数(str),注意页面不用导入js文件。 前台页面:(比如jsp页面) ${str}
 * 或者<%=str%>
 * 
 */
public class FushionChart {
	// 默认参数
	private static final String CAPTION = "统计分析图";// 标题

	private static final String XAXISNAME = "数据源名称";// 横坐标名称

	private static final String YAXISNAME = "Value";// 纵坐标名称

	private static final String WIDTH = "600";// 默认的宽度,意思同width变量一样

	private static final String HEIGHT = "400";// 默认的高度,意思同height变量一样

	private static final String JSPATH = "../FusionCharts/JSClass/FusionCharts.js";// JS路径

	private static final String SWFPATH = "../FusionCharts/INFOSOFTGLOBAL.COM/";// SWF路径

	private static final String XMLHEADER = "<?xml version='1.0' encoding='UTF-8'?>";// XML默认开头

	// 用户自定义
	private Integer chartType=1;//图形类型 1柱形图,2线形图,3饼形图
	private Integer chartShowType=2;//图形类型默认为2=2D,3=3D
	private Integer chartWeiType=2;//图形默认为2维,3=多维
	private String[] groupColumn;//多维图形列英文名
	private String[] groupName;//多维图形列中文名
	private String chartRightMargin="35";//X轴最右边距离框架最右边多宽
	
	
	private String caption;// 图形的标题名称

	private String xAxisName;// 横向坐标轴(x轴)名称

	private String yAxisName;// 纵向坐标轴(y轴)名称
	
	private String numberPrefix="";//纵向坐标轴(y轴)值前缀
	private String numberSuffix="";//纵向坐标轴(y轴)值后缀

	private String width;// x轴宽,其实设置成Double类型的变量也可以,但是没有必要精算到浮点型,Integer就够了,除非业务有必要的说明

	private String height;// y轴宽,其实设置成Double类型的变量也可以,但是没有必要精算到浮点型,Integer就够了,除非业务有必要的说明

	private String jsPath;// 这种写法意思是FusionCharts这个包和你自己写的文件包处于同一个目录下,默认的js路径就是这个

	private String swfPath;// 这个只能指定包名,因为这个Charts包下面全是swf文件,只能根据客户需求加swf文件

	private String divId = "drawDiv" + UUID.randomUUID().toString();// 把封装好的xml数据放到前台页面显示在哪个区域,比如div,所以areaName意思是指定这个区域的名字,这里给他一个默认的。

	private String colors[] = { "1D8BD1", "F1683C", "2AD62A", "DBDC25",
			"649665", "4169E1", "087eb6", "BA55D3", "D2691E", "FF7F50",
			"32CD32", "4682B4" };// 指定颜色,可以根据自己的喜欢随便写,这个数组的长度不限,主要是显示图形时好区分,如果你弄成统一的颜色,会很单调,可以考虑编写个随机颜色程序。

	private String myChartName;

	// 一维数据(意思是比如曲线图上只显示一条曲线)
	private List<Map<Object, Object>> oneDimensionsList = new ArrayList<Map<Object, Object>>();

	// 多维数据(意思是比如曲线图上显示多条曲线)
	private Map<Object, Map<Object, Object>> manyDimensionsMap = new HashMap<Object, Map<Object, Object>>();

	// x轴名称集合(是用来做多条曲线用的,主要是多个集合共享x轴名称)
	private List<String> xAxisNameList = new ArrayList<String>();

	private boolean benchmark = false;// 是否显示基准线

	private String benchmarkName;// 基准线名称

	private Object benchmarkValue;// 基准线值

	/**
	 * 默认的构造方法
	 */
	public FushionChart() {
		this.verifyParams();// 赋默认值
	}

	/**
	 * 针对一维数据所建立的构造方法
	 * 
	 * @param caption
	 * @param xAxisName
	 * @param yAxisName
	 * @param width
	 * @param height
	 * @param oneDimensionsList
	 */
	public FushionChart(String caption, String xAxisName, String yAxisName,
			String width, String height,
			List<Map<Object, Object>> oneDimensionsList) {
		this.caption = caption;
		this.xAxisName = xAxisName;
		this.yAxisName = yAxisName;
		this.width = width;
		this.height = height;
		this.oneDimensionsList = oneDimensionsList;
		this.verifyParams();
	}

	/**
	 * 针对一维数据所建立的构造方法,该方法含有js路径
	 * 
	 * @param caption
	 * @param xAxisName
	 * @param yAxisName
	 * @param width
	 * @param height
	 * @param jsPath
	 * @param swfPath
	 * @param oneDimensionsList
	 */
	public FushionChart(String caption, String xAxisName, String yAxisName,
			String width, String height, String jsPath, String swfPath,
			List<Map<Object, Object>> oneDimensionsList) {
		this.caption = caption;
		this.xAxisName = xAxisName;
		this.yAxisName = yAxisName;
		this.width = width;
		this.height = height;
		this.jsPath = jsPath;
		this.swfPath = swfPath;
		this.oneDimensionsList = oneDimensionsList;
		this.verifyParams();
	}

	/**
	 * 该构造方法是为多维数据写的(带js路径): List<String>含义是x轴的名称, Map<Object, Map<Object,
	 * Object>>含义是每一维所对应的值的集合. 例子:List<String> = {"一月","二月","三月","四月","五月"}
	 * Map<Map<Object, Map<Object, Object>>> = {
	 * {2009年,{{"一月",100},{"二月",200},{"三月",300}...}},
	 * {2010年,{{"一月",100},{"二月",200},{"三月",300}...}}... }
	 * 
	 * @param caption
	 * @param xAxisName
	 * @param yAxisName
	 * @param width
	 * @param height
	 * @param jsPath
	 * @param swfPath
	 * @param xAxisNameList
	 * @param manyDimensionsMap
	 */
	public FushionChart(String caption, String xAxisName, String yAxisName,
			String width, String height, String jsPath, String swfPath,
			List<String> xAxisNameList,
			Map<Object, Map<Object, Object>> manyDimensionsMap) {
		this.caption = caption;
		this.xAxisName = xAxisName;
		this.yAxisName = yAxisName;
		this.width = width;
		this.height = height;
		this.jsPath = jsPath;
		this.swfPath = swfPath;
		this.xAxisNameList = xAxisNameList;
		this.manyDimensionsMap = manyDimensionsMap;
	}

	/**
	 * 针对多维数据所建立的构造方法 同上一样,只不过是不带js路径
	 * 
	 * @param caption
	 * @param xAxisName
	 * @param yAxisName
	 * @param width
	 * @param height
	 * @param xAxisNameList
	 * @param manyDimensionsMap
	 */
	public FushionChart(String caption, String xAxisName, String yAxisName,
			String width, String height, List<String> xAxisNameList,
			Map<Object, Map<Object, Object>> manyDimensionsMap) {
		this.caption = caption;
		this.xAxisName = xAxisName;
		this.yAxisName = yAxisName;
		this.width = width;
		this.height = height;
		this.xAxisNameList = xAxisNameList;
		this.manyDimensionsMap = manyDimensionsMap;
		this.verifyParams();
	}

	/**
	 * 获取swf动画的路径
	 * 
	 * @param swfName
	 * @return
	 */
	private String getSWFPath(String swfName) {
		return this.swfPath + swfName;
	}

	/**
	 * 客户有可能需要达标线,所以这里设置一下达标线的参数
	 * 
	 * @param ifBenchmark
	 *            是否显示达标线
	 * @param benchmarkName
	 *            达标线名称
	 * @param benchmarkValue
	 *            达标线值
	 */
	public void setBenchmark(boolean ifBenchmark, String benchmarkName,
			Object benchmarkValue) {
		this.benchmark = ifBenchmark;
		this.benchmarkName = benchmarkName;
		this.benchmarkValue = benchmarkValue;
	}

	/**
	 * 如果用户在前台不设置参数,例如这个参数为null或者是"",那么这里给他一个默认的参数值
	 */
	private void verifyParams() {
		if (this.width == null || this.width.equals("")) {
			this.width = WIDTH;
		}
		if (this.height == null || this.height.equals("")) {
			this.height = HEIGHT;
		}
		if (this.xAxisName == null || this.xAxisName.equals("")) {
			this.xAxisName = XAXISNAME;
		}
		if (this.yAxisName == null || this.yAxisName.equals("")) {
			this.yAxisName = YAXISNAME;
		}
		if (this.caption == null || this.caption.equals("")) {
			this.caption = CAPTION;
		}
		if (this.jsPath == null || this.jsPath.equals("")) {
			this.jsPath = JSPATH;
		}
		if (this.swfPath == null || this.swfPath.equals("")) {
			this.swfPath = SWFPATH;
		}
		if (this.myChartName == null || this.myChartName.equals("")) {
			this.myChartName = "myChart" + (new Random()).nextInt(10000);
		}
		if (this.oneDimensionsList.isEmpty()) {
			this.oneDimensionsList = new ArrayList<Map<Object, Object>>();
		}
		if (this.manyDimensionsMap.isEmpty()) {
			this.manyDimensionsMap = new HashMap<Object, Map<Object, Object>>();
		}
		if (this.xAxisNameList.isEmpty()) {
			this.xAxisNameList = new ArrayList<String>();
		}

	}

	/**
	 * 加载js
	 * 
	 * @return
	 */
	private String getDivAndJs() {
		return "<div style=\"width: 0px; height: 0px\"><script type=\"text/javascript\" src=\""
				+ this.jsPath
				+ "\"></script></div>"
				+ "<div id=\""
				+ this.divId + "\" align = \"center\">无数据显示.</div>";
	}

	/**
	 * 解析一维图形的xml数据
	 * 
	 * @return
	 */
	private String getOneDimensionsXmlData() {
		StringBuffer buffer = new StringBuffer("");
		buffer
				.append("<chart caption='")
				.append(this.caption)
				.append("' xAxisName='")
				.append(this.xAxisName)
				.append("' yAxisName='")
				.append(this.yAxisName)
				.append("' numberPrefix='")
				.append(this.numberPrefix)
				.append("' numberSuffix='")
				.append(this.numberSuffix)
				.append("' chartRightMargin='")
				.append(this.chartRightMargin)
				.append(
						"' showNames='1' decimalPrecision='0' baseFontSize='12'  formatNumberScale='0' >");
		for (Map<Object, Object> map : this.oneDimensionsList) {
			buffer.append("<set label='").append(map.get("x")).append(
					"' value='").append(map.get("y")).append("' color='")
					.append(this.getRandomColor()).append("' />");
		}
		buffer.append("</chart>");
		return buffer.toString();
	}

	/**
	 * 画图,主要是把js,xml,swf等数据封装起来
	 * 
	 * @param swfName
	 * @param xmlData
	 * @return
	 */
	private FChart getDrawChart(String swfName, String xmlData) {
	/*yc	StringBuffer buffer = new StringBuffer(this.getDivAndJs()
				+ "<script type=\"text/javascript\"> ");
		buffer.append("var ").append(this.myChartName).append(
				"= new FusionCharts(\"" + this.getSWFPath(swfName)
						+ "\", \"myChart" + UUID.randomUUID().toString()
						+ "\", \"" + this.width + "\", \"" + this.height
						+ "\", \"0\", \"0\"); ").append(this.myChartName)
				.append(".setDataXML(\"" + XMLHEADER + xmlData + "\"); ")
				.append(this.myChartName).append(".render(\"").append(
						this.divId).append("\");</script>");
		return buffer.toString();*/
		FChart fc=new FChart();
		fc.setFileName(swfName);
		fc.setXmlData(XMLHEADER+xmlData);
		return fc;
	}

	/**
	 * 解析多维图形的xml数据
	 * 
	 * @return
	 */
	private String getManyDimensionsXmlData() {
		StringBuffer buffer = new StringBuffer("");
		buffer
				.append("<chart caption='")
				.append(this.caption)
				.append("' xAxisName='")
				.append(this.xAxisName)
				.append("' yAxisName='")
				.append(this.yAxisName)
				.append("' numberPrefix='")
				.append(this.numberPrefix)
				.append("' numberSuffix='")
				.append(this.numberSuffix)
				.append("' chartRightMargin='")
				.append(this.chartRightMargin)
				.append(
						"' showValues='0' baseFontSize='12' palette='1' showFCMenuItem='1' imageSave='1' formatNumberScale='0' >");
		buffer.append("<categories>");
		for (String str : xAxisNameList) {
			buffer.append("<category label='" + str + "' />");
		}
		buffer.append("</categories>");
		for (Map.Entry<Object, Map<Object, Object>> values : this.manyDimensionsMap
				.entrySet()) {
			buffer.append("<dataset seriesName='").append(values.getKey())
					.append("'>");
			for (String str : this.xAxisNameList) {
				buffer.append("<set value='")
						.append(values.getValue().get(str)).append("'/>");
			}
			buffer.append("</dataset>");
		}
		buffer.append(this.benchmark());
		buffer.append("</chart>");
		return buffer.toString();
	}

	/**
	 * 封装达标线的xml数据
	 * 
	 * @return
	 */
	private String benchmark() {
		StringBuffer buffer = new StringBuffer("");
		if (this.benchmark
				&& (this.benchmarkName != null && !this.benchmarkName
						.equals(""))
				&& (this.benchmarkValue != null && !this.benchmarkValue
						.equals(""))) {
			buffer.append("<trendlines><line startValue='").append(
					this.benchmarkValue).append(
					"' color='91C728' displayValue='").append(
					this.benchmarkName).append(
					"' showOnTop='1' /></trendlines>");
		}
		return buffer.toString();
	}

	/**
	 * 从colors数组随机选取一个颜色
	 * 
	 * @return
	 */
	private String getColor() {
		if (oneDimensionsList.size() <= 0) {
			return this.colors[(new Random()).nextInt(this.colors.length)];
		} else {
			return this.colors[(new Random()).nextInt(oneDimensionsList.size())];
		}
	}

	/**
	 * 生产随机颜色
	 * 
	 * @return
	 */
	private String getRandomColor() {
		return (UUID.randomUUID().toString()).substring(0, 6);
	}

	/**
	 * 2维饼状图
	 * 
	 * @return
	 */
	public FChart drawPie2D() {
		return this.getDrawChart("Pie2D.swf", this.getOneDimensionsXmlData());

	}

	/**
	 * 3维饼状图
	 * 
	 * @return
	 */
	public FChart drawPie3D() {
		return this.getDrawChart("Pie3D.swf", this.getOneDimensionsXmlData());
	}

	/**
	 * 2维柱状图
	 * 
	 * @return
	 */
	public FChart drawColumn2D() {
		return this
				.getDrawChart("Column2D.swf", this.getOneDimensionsXmlData());
	}

	/**
	 * 3维柱状图
	 * 
	 * @return
	 */
	public FChart drawColumn3D() {
		return this
				.getDrawChart("Column3D.swf", this.getOneDimensionsXmlData());
	}

	/**
	 * 2维曲线图
	 * 
	 * @return
	 */
	public FChart drawLine2D() {
		return this.getDrawChart("Line.swf", this.getOneDimensionsXmlData());
	}

	/**
	 * 3维曲线图 这个方法暂时不能使用,因为关于曲线图一维数据的swf文件暂时没找到
	 * 
	 * @return
	 */
	public FChart drawLine3D() {
		return this.getDrawChart("Line.swf", this.getOneDimensionsXmlData());
	}

	// ==============以下是多维数据柱状图,曲线图===============

	/**
	 * 多维2D柱状图
	 * 
	 * @return
	 */
	public FChart drawColumn2DGroup() {
		return this.getDrawChart("MSColumn2D.swf", this
				.getManyDimensionsXmlData());
	}

	/**
	 * 多维2D曲线图
	 * 
	 * @return
	 */
	public FChart drawLine2DGroup() {
		return this.getDrawChart("MSLine.swf", this.getManyDimensionsXmlData());
	}

	/**
	 * 多维3D柱状图
	 * 
	 * @return
	 */
	public FChart drawColumn3DGroup() {
		return this.getDrawChart("MSColumn3D.swf", this
				.getManyDimensionsXmlData());
	}

	/**
	 * 多维3D曲线图
	 * 
	 * @return
	 */
	public FChart drawLine3DGroup() {
		return this.getDrawChart("MSLine.swf", this.getManyDimensionsXmlData());
	}

	// ==========get/set方法begin==============

	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	public String getXAxisName() {
		return xAxisName;
	}

	public void setXAxisName(String axisName) {
		xAxisName = axisName;
	}

	public String getYAxisName() {
		return yAxisName;
	}

	public void setYAxisName(String axisName) {
		yAxisName = axisName;
	}

	public String getWidth() {
		return width;
	}

	public void setWidth(String width) {
		this.width = width;
	}

	public String getHeight() {
		return height;
	}

	public void setHeight(String height) {
		this.height = height;
	}

	public String getJsPath() {
		return jsPath;
	}

	public void setJsPath(String jsPath) {
		this.jsPath = jsPath;
	}

	public String getSwfPath() {
		return swfPath;
	}

	public void setSwfPath(String swfPath) {
		this.swfPath = swfPath;
	}

	public String getDivId() {
		return divId;
	}

	public void setDivId(String divId) {
		this.divId = divId;
	}

	public String[] getColors() {
		return colors;
	}

	public void setColors(String[] colors) {
		this.colors = colors;
	}

	public String getMyChartName() {
		return myChartName;
	}

	public void setMyChartName(String myChartName) {
		this.myChartName = myChartName;
	}

	public List<Map<Object, Object>> getOneDimensionsList() {
		return oneDimensionsList;
	}

	public void setOneDimensionsList(List<Map<Object, Object>> oneDimensionsList) {
		this.oneDimensionsList = oneDimensionsList;
	}

	public Map<Object, Map<Object, Object>> getManyDimensionsMap() {
		return manyDimensionsMap;
	}

	public void setManyDimensionsMap(
			Map<Object, Map<Object, Object>> manyDimensionsMap) {
		this.manyDimensionsMap = manyDimensionsMap;
	}

	public List<String> getXAxisNameList() {
		return xAxisNameList;
	}

	public void setXAxisNameList(List<String> axisNameList) {
		xAxisNameList = axisNameList;
	}

	public boolean isBenchmark() {
		return benchmark;
	}

	public void setBenchmark(boolean benchmark) {
		this.benchmark = benchmark;
	}

	public String getBenchmarkName() {
		return benchmarkName;
	}

	public void setBenchmarkName(String benchmarkName) {
		this.benchmarkName = benchmarkName;
	}

	public Object getBenchmarkValue() {
		return benchmarkValue;
	}

	public void setBenchmarkValue(Object benchmarkValue) {
		this.benchmarkValue = benchmarkValue;
	}

	

	public Integer getChartType() {
		return chartType;
	}

	public void setChartType(Integer chartType) {
		this.chartType = chartType;
	}



	public Integer getChartShowType() {
		return chartShowType;
	}

	public void setChartShowType(Integer chartShowType) {
		this.chartShowType = chartShowType;
	}

	public Integer getChartWeiType() {
		return chartWeiType;
	}

	public void setChartWeiType(Integer chartWeiType) {
		this.chartWeiType = chartWeiType;
	}

	public String[] getGroupColumn() {
		return groupColumn;
	}

	public void setGroupColumn(String[] groupColumn) {
		this.groupColumn = groupColumn;
	}

	public String[] getGroupName() {
		return groupName;
	}

	public void setGroupName(String[] groupName) {
		this.groupName = groupName;
	}

	

	public String getNumberPrefix() {
		return numberPrefix;
	}

	public void setNumberPrefix(String numberPrefix) {
		this.numberPrefix = numberPrefix;
	}

	public String getNumberSuffix() {
		return numberSuffix;
	}

	public void setNumberSuffix(String numberSuffix) {
		this.numberSuffix = numberSuffix;
	}

	public String getChartRightMargin() {
		return chartRightMargin;
	}

	public void setChartRightMargin(String chartRightMargin) {
		this.chartRightMargin = chartRightMargin;
	}

	// ------------------------------------------------------
	/**
	 * 获取十六进制的颜色代码.例如 "#6E36B4" , For HTML ,
	 * 
	 * @return String
	 */
	public static String getRandColorCode() {
		String r, g, b;
		Random random = new Random();
		r = Integer.toHexString(random.nextInt(256)).toUpperCase();
		g = Integer.toHexString(random.nextInt(256)).toUpperCase();
		b = Integer.toHexString(random.nextInt(256)).toUpperCase();

		r = r.length() == 1 ? "0" + r : r;
		g = g.length() == 1 ? "0" + g : g;
		b = b.length() == 1 ? "0" + b : b;

		return r + g + b;
	}
	
	/**
	 * 根据图形配置信息和DataTable生成图形字符串
	 * @param fc
	 * @param dt
	 * @return
	 * @throws Exception
	 */
	public  FChart GetChartStr(FushionChart fc,DataTable dt) throws Exception{
		FChart strs = null;
		if(fc.chartWeiType==2){
			List<Map<Object, Object>> oneDimensionsList = new ArrayList<Map<Object, Object>>();
			Map<Object, Object> map = new HashMap<Object, Object>();
			for(int i=0;i<dt.GetRowsCount();i++){
				map.put("x", dt.GetString(i, "x"));
				map.put("y", dt.GetString(i, "y"));
				oneDimensionsList.add(map);
			}
				fc.setOneDimensionsList(oneDimensionsList);
			}else if(fc.chartWeiType==3){
				for(int i=0;i<dt.GetRowsCount();i++){
					xAxisNameList.add(dt.GetString(i, "x"));
				}
				for (int i = 0; i < groupColumn.length; i++) {
					Map<Object, Object> m = new HashMap<Object, Object>();
					for (int j = 0; j < xAxisNameList.size(); j++) {
						for(int c=0;c<dt.GetRowsCount();c++){
							if(xAxisNameList.get(j).equals(dt.GetString(c, "x"))){
								m.put(xAxisNameList.get(j), dt.GetString(c, groupColumn[i]));
							}
						}
						
					}
					manyDimensionsMap.put(groupName[i], m);
				}
				fc.setManyDimensionsMap(manyDimensionsMap);
				
			}
		switch(fc.getChartType()){
			case 1:{				//柱状图
				if(fc.chartShowType==2){
					if(fc.chartWeiType==3){
						strs=fc.drawColumn2DGroup();
					}else{
						strs=fc.drawColumn2D();
					}
				}else if(fc.chartShowType==3){
					if(fc.chartWeiType==3){
						strs=fc.drawColumn3DGroup();
					}else{
						strs=fc.drawColumn3D();
					}
				}
				break;
			}
			case 2:{				//曲线图
				if(fc.chartShowType==2){
					if(fc.chartWeiType==3){
						strs=fc.drawLine2DGroup();
					}else{
						strs=fc.drawLine2D();
					}
				}else if(fc.chartShowType==3){
					if(fc.chartWeiType==3){
						strs=fc.drawLine3DGroup();
					}else{
						strs=fc.drawLine3D();
					}
				}
				break;
			}
			case 3:{				//饼图
				if(fc.chartShowType==2){
					strs=fc.drawPie2D();
				}else if(fc.chartShowType==3){
					strs=fc.drawPie3D();
				}
				break;
			}
		}
		return strs;
	}

}

3.Servlet代码

package project.report.servlet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import hh.com.carrier.DataTable;
import hh.com.dao.DBUtil;
import hh.com.environment.AbstractWebImpl;
import hh.com.exception.CustomException;
import hh.com.exception.DAOException;
import hh.com.exception.DomainControllerException;
import hh.com.exception.WebImplException;
import hh.com.fushionchart.FushionChart;
import hh.sys.constant.EventId;



public class ReportServlet extends AbstractWebImpl{
	public void doEvent(int eventId) throws WebImplException,
	DomainControllerException {
		
		try{
			switch(eventId){
				case EventId.MM_EXPAND1:{//
					List<Map<Object, Object>> oneDimensionsList = new ArrayList<Map<Object, Object>>();
					List<String> xAxisNameList = new ArrayList<String>();
					Map<Object, Map<Object, Object>> manyDimensionsMap = new HashMap<Object, Map<Object, Object>>();
					
					// 以下代码(三个for循环)是做测试用的
					for (int i = 0; i < 10; i++) {
						int value = (new Random()).nextInt(100);
						Map<Object, Object> map = new HashMap<Object, Object>();
						map.put("x", "你好" + i);
						map.put("y", value);
						oneDimensionsList.add(map);
					}
					for (int i = 1; i <= 12; i++) {
						xAxisNameList.add(i + "");
					}
					for (int i = 0; i < 3; i++) {
						Map<Object, Object> m = new HashMap<Object, Object>();
						for (int j = 1; j <= xAxisNameList.size(); j++) {
							m.put(xAxisNameList.get(j - 1), (new Random())
									.nextInt(100));
						}
						manyDimensionsMap.put("201" + i, m);
					}
					
					FushionChart d = new FushionChart();
					d.setCaption("查询包数统计分析图");
					d.setXAxisName("指标发生时间");
					d.setYAxisName("测试");
					d.setWidth("1000");
					d.setHeight("500"); 
					d.setChartType(1);
					d.setChartShowType(2);
					d.setChartWeiType(3);
				//	d.setXAxisNameList(xAxisNameList);
					System.out.println(manyDimensionsMap.size());
//					d.setManyDimensionsMap(manyDimensionsMap);
					//d.setOneDimensionsList(oneDimensionsList);
					//String str1 = d.drawColumn2D();
					DataTable dt=new DataTable();
					/*dt.AddColumn("x");
					dt.AddColumn("y");
					dt.AddRow(1);
					
					dt.SetCellData("一月",0, "x");
					dt.SetCellData("10",0, "y");
					dt.AddRow(1);
					dt.SetCellData("二月",1, "x");
					dt.SetCellData("20",1, "y");*/
					String[] groupColumn={"cpudeg","ramsize"};
					String[] groupName={"CPU","内存"};
					d.setGroupColumn(groupColumn);
					d.setGroupName(groupName);
					dt=new DBUtil().GetData("select max(cpudeg) cpudeg,max(ramsize) ramsize,createtime x from tsr_csreal group by  date_format(createtime,'%Y-%m-%d')");
					/*String str1= d.GetChartStr(d, dt);
					// 这里如果想要真实数据,可以自己写,只要你写好的数据封装成list或者map的格式就可以。然后把参数传到DrawDesigns这里类里就可以。
					// 我这里没有数据,因为在DrawDesigns类里面我用的是假数据,在verifyParams()这个方法里的最下面就是我写的假数据,被我注释掉了。可以根据自己的需求随便写
					System.out.println("打印出xml数据:" + str1);
					request.setAttribute("draw0", str1);*/
					break;
				}
				
				default:{
					break;
				}
			}
		/*}catch(CustomException ex){			//捕捉自定义异常,抛出错误消息
			request.setAttribute("Res", ex.getMessage());
		}catch (DAOException ex) {			//捕捉DAO层异常,插入数据库错误信息
			ex.printStackTrace(request);
		*/}catch (Exception ex) {				//捕捉service异常,插入数据库错误信息
			ex.printStackTrace();
			throw new WebImplException(request,ex);
		}
	}
}


4.前台jsp页面调用报表插件

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="hh.sys.constant.SysMessage,hh.sys.constant.EventId"%>
<%@ page isELIgnored="false"%>
<%@page import="hh.com.fushionchart.Model.FChart"%>
<html>
<head>
<% 
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
	DataTable dt=(DataTable)request.getAttribute("dt");
	String serverType=(String)request.getParameter("serverType");
	FChart fChart=(FChart)request.getAttribute("fChart");
	int cpudeg=0,discdeg=0,boarddeg=0,cpupct=0;
	if(dt!=null && dt.GetRowsCount()>0){
		cpudeg=dt.GetInteger(0,"cpudeg");
		discdeg=dt.GetInteger(0,"discdeg");
		boarddeg=dt.GetInteger(0,"boarddeg");
		cpupct=dt.GetInteger(0,"cpupct");
	}
%>
<title>用户列表</title>

<script id="othejs" import="1" type="text/javascript" src="../control/H2ResourcesForOthe.js" ></script>
<script id="gridjs" import="1" type="text/javascript" src="../control/H2ResourcesForGrid.js" ></script>
<script id="treejs" import="0" type="text/javascript" src="../control/H2ResourcesForTree.js" ></script>
<script id="datejs" import="1" type="text/javascript" src="../control/H2ResourcesForDate.js" ></script>
<script id="stextjs" import="1" type="text/javascript" src="../control/H2ResourcesForSText.js" ></script>
	 	
<script id="stextjs" import="1" type="text/javascript" src="../control/H2ShowDG.js" ></script>

<script type="text/javascript" src="../FusionCharts/JSClass/FusionCharts.js"></script>
<script type="text/javascript" src="../FusionCharts/JSClass/FusionChartsUtil.js"></script>
<link href="../css/global.css" rel="stylesheet" type="text/css"/>
<style type="text/css">
	.tabtitle{
		background: #f4f4f4;
		height: 23px;
		font-weight: bold;
	}
	.table td {
		border-right: 1px solid #CCC;
		border-bottom: 1px solid #d7d7d7;
	}
	.table .tdone{
		background: #FFF;
		height: 23px;
	}
	.table .tdtwo{
		background: #f4f4f4;
		height: 23px;
	}	
	.table{
		font-size: 13px;
	}
</style>
</head>
<%@ include file="../../../importjsp/I_Message.jsp"%>
<body>

<%@ include file="../../../importjsp/I_ProcessLayout.jsp" %>
<form name="theForm" method="post">
<input type="hidden" id="deptid" name="deptid"  value="<%=request.getParameter("deptid") %>" />
<input name="issearch" type="hidden" value="${param.issearch}"><%--1:查询调用--%>
<table width="98%" height="100%" cellpadding="0" cellspacing="0">

<tr ><td >
	<table class="TableList" width="100%" cellpadding="0" cellspacing="0" >
	<tr>
		<td >
			<div  class="searchwherediv"><!--
				 <span class="title">登录代码:</span>
                 <input type="text" class="searchtext" id="code" name="code" style="width: 200px;"  />
                 --><span class="title">按类型:</span>
                            <select fix="1" class="searchtext" name="ctype" id="ctype" >
                            	<option value="1">温度</option>
                            	<option value="2">CPU百分比</option>
                            	<option value="3">内存大小</option>
                            	<option value="4">带宽</option>
                             </select>
                             
                     <span class="title">图形选择:</span>
                            <select fix="1" class="searchtext" name="charttype" id="charttype" >
                            	
                            	<option value="2">曲线图</option>
                            	<option value="1">柱形图</option>
                             </select>
			</div>	
		</td>
	</tr>
	<tr>
		<td >
			<div  class="searchbuttondiv">
				<input type="button"  name="61005" onClick="onSubmitSearch()" accesskey="Q" title="查询(Alt+Q)" value="查询(Q)" onFocus="this.blur()" class="functionbutton" />
				<input type="button"  name="61006" onClick="onSubmitClear()" accesskey="R" title="重置(Alt+R)" value="重置(R)" onFocus="this.blur()" class="functionbutton" />
				<!--<input type="button"  name="61006" onClick="javascript:OpenImportExcel(ImportExcelCode.USER)" accesskey="I" title="导入用户(Alt+I)" value="导入用户(I)" onFocus="this.blur()" class="functionbutton" />
         	--></div>		
		</td>
	  </tr>
	</table>
</td></tr>

<!---页面按钮赋权开始 disabled -->
<%@ include file="../../../importjsp/I_ListCompetence.jsp" %>
<!---页面按钮赋权结束-->

<!-- H2Grid 表格开始 -->
<tr>
	<td height="100%" valign="top" >
	<div style="width: 100%;height: 100%;">
	<div id="mainDiv" class="mainDiv" style="width: 100%;height: 50%;" >
		<div id="drawDiv" style="width: 75%;height: 100%;float: left;"></div>
		<div style="width: 23%;height: 99%;float: right;text-align: left;border: 1px solid #CCC;">
			<table style="width: 100%;" cellpadding="10">
				<tr>
					<td style="background-color: #f4f4f4;"><h4>电脑状态</h4></td>
				</tr>
				<tr>
					<td>
						<div>CPU温度  <%=cpudeg%>℃</div>
	 					<div id="cpudeg"  style="width:90%; height:20px; border:1px solid #c1cbc2; background:#f5ffec;margin-left: 0px;">
     						<div style="width:10%; height:20px; background:#7fd441;margin-left: 0px;"></div>
 						</div>
					</td>
				</tr>
				<tr>
					<td>
						<div>硬盘温度  <%=discdeg%>℃</div>
	 					<div id="discdeg"  style="width:90%; height:20px; border:1px solid #c1cbc2; background:#f5ffec;margin-left: 0px;">
     						<div style="width:10%; height:20px; background:#7fd441;margin-left: 0px;"></div>
 						</div> 
					</td>
				</tr>
				<tr>
					<td>
						<div>主板温度  <%=boarddeg%>℃</div>
	 					<div id="boarddeg"  style="width:90%; height:20px; border:1px solid #c1cbc2; background:#f5ffec;margin-left: 0px;">
     						<div style="width:10%; height:20px; background:#7fd441;margin-left: 0px;"></div>
 						</div> 
					</td>
				</tr>
				
				<tr>
					<td>
						<div>CPU占用百分比  <%=cpupct%>%</div>
	 					<div id="cpupct"  style="width:90%; height:20px; border:1px solid #c1cbc2; background:#f5ffec;margin-left: 0px;">
     						<div style="width:10%; height:20px; background:#7fd441;margin-left: 0px;"></div>
 						</div> 
					</td>
				</tr>				
			</table>
		</div>
	</div>
	<br/>
	<div id="tableList"  style="width: 100%;height: 45%;border: 1px solid #CCC;" >
			<table width="100%" border="0" cellspacing="0" cellpadding="5" class="table" id='permission'>
				<tr>
					<td align="left" class="tabtitle">CPU温度(℃)</td>
					<td align="left" class="tabtitle">硬盘温度(℃)</td>
					<td align="left" class="tabtitle" >主板温度(℃)</td>
					<td align="left" class="tabtitle" >风扇转速</td>
					<td align="left" class="tabtitle" >CPU占用百分比(%)</td>
					<td align="left" class="tabtitle" >内存占用大小(K)</td>
					<td align="left" class="tabtitle" >带宽(KB)</td>
					<td align="left" class="tabtitle" >时间</td>
				</tr>
				
				
				<%
					if(dt!=null && dt.GetRowsCount()>0){
						for(int i=0;i<dt.GetRowsCount();i++){
							String styleClass="tdtwo";
							if(i%2==0){
								styleClass="tdone";
							}
						%>
						<tr>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"cpudeg") %></td>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"discdeg") %></td>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"boarddeg") %></td>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"fandeg") %></td>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"cpupct") %></td>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"ramsize") %></td>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"bandwidth") %></td>
							<td align="left" class="<%=styleClass %>"><%=dt.GetString(i,"x") %></td>
						</tr>	
						<%}
					}
				 %>
		</table>
		</div>
	</div>
	</td>
</tr>
<!-- H2Grid 表格结束 -->
</table>
</form>
</body>
</html>
<%@ include file="../../../importjsp/I_ResetListValue.jsp" %>
<script type="text/javascript" src="../js/events.js" language="javascript"></script>
<script type="text/javascript" src="../js/utils.js" language="javascript"></script>
<script type="text/javascript" src="../js/check.js" language="javascript"></script>
<script language="javascript" type="text/javascript" src="../control/LoadControl.js"></script>
<script language="javascript" type="text/javascript" src="../js/plugins/custom/customplugin.js"></script>
<script language="javascript" type="text/javascript" >
var grid,id;
grid = new H2Grid({
	pkColumn : 'userid',
	captions : '登陆代码,用户名称,所属部门,手机号码,Email,标识,创建者,创建时间,修改者,修改时间',
	colnames : 'code,name,deptname,mobileno,email,isenabled,creator,createtime,modifier,modifytime',
	widths : '80,80,80,80,80,80,80,150,80,150',
	aligns : 'left,left,left,left,left,left,left,left,left,left',
	page : true
});

//查询
function onSubmitSearch(){
	var url = "../servlet/showpage?eventID=62002&&project_res=sm.real.cserver.report&&serverType=<%=serverType%>";
	SubmitForm(url);
}
//添加
function onSubmitAdd(){
   var deptid=theForm.deptid.value;
   if(deptid==undefined||deptid=="null"){
   	Alert("请先选择组织机构!");
   	return ;
   }
   var url="servlet/showpage?eventID=<%=EventId.MM_EXPAND3%>&&project_res=org.list.table.edit&&deptid="+theForm.deptid.value;
   window.top.openWin("用户——添加",url,650,590);
}

//修改
function onSubmitEdit(){
	id=grid.getSelectRowPKID();
	if(id==""||id==undefined){
		Alert("请选择要编辑的数据!");
		return;
	};
	var url = "servlet/showpage?eventID=<%=EventId.MM_EXPAND2%>&&project_res=org.list.table.edit";
	url += "&&id="+id;
	window.top.openWin('用户——编辑 ',url,650,590);
}
//删除
function onSubmitDelete(){
	id=grid.getSelectRowPKID();
	if(id==""||id==undefined){
		Alert("请选择要删除的数据");
		return;
	};	
	window.top.Confirm("确认删除?","",
		function(){ SubmitForm("../servlet/showpage?eventID=<%=EventId.MM_EXPAND4%>&&project_res=org.list.table&&id="+id+"&&deptid="+theForm.deptid.value);},
		function(){ });
}
function myrefresh()
{
   window.location.reload();
}
setTimeout('myrefresh()',60000); //指定1秒刷新一次
fakeProgress(<%=cpudeg%>, cpudeg,100);
fakeProgress(<%=discdeg%>, discdeg,100);
fakeProgress(<%=boarddeg%>, boarddeg,100);
fakeProgress(<%=cpupct%>, cpupct,100);

//加载报表数据 

ReportData('drawDiv',"<%=fChart.getXmlData() %>",'<%=fChart.getFileName() %>');
</script>

以上就是FushionCharts报表的用例。

不懂的可以博客留言我。

Java封装FushionCharts

标签:fusioncharts   xml   json   java   报表   

原文地址:http://blog.csdn.net/jj88888/article/details/44489215

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!