自定义统计图结合FUSIONCHARTS增强版

第50章 自定义统计图结合FUSIONCHARTS增强版
1. 问题概述
A.之前已发布一个关于自定义统计图结合FUSIONCHARTS的版本,文章名称: <<利用自定义统计图结合FUSIONCHARTS展现效果>>
B.此文章目的在以前的基础上进行修改代码通用性,支持更多的展现类型.如: MSCombi3D, MSColumn3D, StackedColumn3D, 2Column+1Line, StackedBar3D, 1Column+2Line等.
C.在报表里利用自定义统计图结合fusioncharts实现flash的展现效果.此功能已通过java代码做成通用功能. 主要3个java文件:
1.FlashChartServlet初始化Servlet,读取和删除XML文件等,需要在web.xml文件配置一下
2.LoadFlashChart自定义函数主要负责加载flash效果,加载XML文件,自动给执行flashChartServlet返回字符串等
3.FlashChart自定义统计图里画图文件和生成XML文件
2. 操作说明

1.在WEB项目里把fusioncharts下面的*.swf文件全部放在当前Charts文件夹下,把FusionCharts.js放在指定文件夹下

2.在报表A3单元格设置自定义函数:=LoadFlashChart(‘Pie3D’,'loan_bal_rpt2.xml’)
说明:用的是那个flash,执行那个XML文件名

3.在报表A2单元格设置自定义统计图和相关的参数信息,通过标签发布报表时,在jsp里加入<script src=”<%=request.getContextPath() %>/js/FusionCharts.js”></script>


3.展现:
A: StackedColumn3D

B: MSLine

C: MSColumn3D

D: MSCombi3D

E: 2Column+1Line

F: Pie3D

G: StackedBar3D

H: MSArea

I: 1Column+2Line


J:Doughnut 3D Chart

3. 程序说明
1.LoadFlashChart具体代码:

package zHH;

import com.runqian.base4.util.ReportError;

import com.runqian.report4.model.expression.Expression;

import com.runqian.report4.model.expression.Function;

import com.runqian.report4.model.expression.Variant2;

import com.runqian.report4.usermodel.Context;

import java.net.URL;

import java.util.ArrayList;

import javax.servlet.ServletContext;

public class LoadFlashChart extends Function {

public static final String GRAPH_TYPE_COLUMN_2D = “Column2D”;

public static final String GRAPH_TYPE_COLUMN_3D = “Column3D”;

public static final String GRAPH_TYPE_MS_COLUMN_2D = “MSColumn2D”;

public static final String GRAPH_TYPE_MS_COLUMN_3D = “MSColumn3D”;

public static final String GRAPH_TYPE_STACKED_COLUMN_2D = “StackedColumn2D”;

public static final String GRAPH_TYPE_STACKED_COLUMN_3D = “StackedColumn3D”;

public static final String GRAPH_TYPE_BAR_2D = “Bar2D”;

public static final String GRAPH_TYPE_MS_BAR_2D = “MSBar2D”;

public static final String GRAPH_TYPE_MS_BAR_3D = “MSBar3D”;

public static final String GRAPH_TYPE_STACKED_BAR_2D = “StackedBar2D”;

public static final String GRAPH_TYPE_STACKED_BAR_3D = “StackedBar3D”;

public static final String GRAPH_TYPE_PIE_2D = “Pie2D”;

public static final String GRAPH_TYPE_PIE_3D = “Pie3D”;

public static final String GRAPH_TYPE_LINE = “Line”;

public static final String GRAPH_TYPE_MS_LINE = “MSLine”;

public static final String GRAPH_TYPE_AREA = “Area2D”;

public static final String GRAPH_TYPE_MS_AREA = “MSArea”;

public static final String GRAPH_TYPE_STACKED_COLUMN_3D_LINEDY = “StackedColumn3DLineDY”;

public static final String GRAPH_TYPE_MS_COMBI_3D = “MSCombi3D”;

public Object calculate(Context ctx, boolean isInputValue) {

if (this.paramList.size() != 2)

throw new ReportError(该函数需要两个参数!);

Expression param1 = (Expression) this.paramList.get(0);

Expression param2 = (Expression) this.paramList.get(1);

String graphType = (String) Variant2.getValue(param1.calculate(ctx,

isInputValue), false, isInputValue);

String xmlFile = (String) Variant2.getValue(param2.calculate(ctx,

isInputValue), false, isInputValue);

String swfFile = “”;

if (GRAPH_TYPE_COLUMN_2D.equals(graphType))

swfFile = GRAPH_TYPE_COLUMN_2D + “.swf”;

else if (GRAPH_TYPE_COLUMN_3D.equals(graphType))

swfFile = GRAPH_TYPE_COLUMN_3D + “.swf”;

else if (GRAPH_TYPE_MS_COLUMN_2D.equals(graphType))

swfFile = GRAPH_TYPE_MS_COLUMN_2D+“.swf”;

else if (GRAPH_TYPE_MS_COLUMN_3D.equals(graphType))

swfFile = GRAPH_TYPE_MS_COLUMN_3D+“.swf”;

else if (GRAPH_TYPE_STACKED_COLUMN_2D.equals(graphType))

swfFile = GRAPH_TYPE_STACKED_COLUMN_2D+“.swf”;

else if (GRAPH_TYPE_STACKED_COLUMN_3D.equals(graphType))

swfFile = GRAPH_TYPE_STACKED_COLUMN_3D+“.swf”;

else if (GRAPH_TYPE_BAR_2D.equals(graphType))

swfFile = GRAPH_TYPE_BAR_2D+“.swf”;

else if (GRAPH_TYPE_MS_BAR_2D.equals(graphType))

swfFile = GRAPH_TYPE_MS_BAR_2D+“.swf”;

else if (GRAPH_TYPE_MS_BAR_3D.equals(graphType))

swfFile = GRAPH_TYPE_MS_BAR_3D+“.swf”;

else if (GRAPH_TYPE_STACKED_BAR_2D.equals(graphType))

swfFile = GRAPH_TYPE_STACKED_BAR_2D+“.swf”;

else if (GRAPH_TYPE_STACKED_BAR_3D.equals(graphType))

swfFile = GRAPH_TYPE_STACKED_BAR_3D+“.swf”;

else if (GRAPH_TYPE_PIE_2D.equals(graphType))

swfFile = GRAPH_TYPE_PIE_2D+“.swf”;

else if (GRAPH_TYPE_PIE_3D.equals(graphType))

swfFile = GRAPH_TYPE_PIE_3D+“.swf”;

else if (GRAPH_TYPE_LINE.equals(graphType))

swfFile = GRAPH_TYPE_LINE+“.swf”;

else if (GRAPH_TYPE_MS_LINE.equals(graphType))

swfFile = GRAPH_TYPE_MS_LINE+“.swf”;

else if (GRAPH_TYPE_AREA.equals(graphType))

swfFile = GRAPH_TYPE_AREA+“.swf”;

else if (GRAPH_TYPE_MS_AREA.equals(graphType))

swfFile = GRAPH_TYPE_MS_AREA+“.swf”;

else if (GRAPH_TYPE_STACKED_COLUMN_3D_LINEDY.equals(graphType))

swfFile = GRAPH_TYPE_STACKED_COLUMN_3D_LINEDY+“.swf”;

else if (GRAPH_TYPE_MS_COMBI_3D.equals(graphType))

swfFile = GRAPH_TYPE_MS_COMBI_3D+“.swf”;

else {

throw new ReportError(统计图类型参数错误!);

}

String appName = “/”;

try {

ServletContext application = ctx.getApplication();

String path = application.getResource(“/”).getPath();

for (; path.endsWith(“/”); path = path.substring(0,

path.length() – 1));

appName = path.substring(path.lastIndexOf(“/”));

} catch (Exception e) {

appName = “/”;

}

String divId = “div” + String.valueOf(System.currentTimeMillis());

String swfId = “swf” + String.valueOf(System.currentTimeMillis());

StringBuffer htmlCode = new StringBuffer();

htmlCode.append(“<div id=\”" + divId + “\”></div>\n”);

htmlCode.append(“<script language=\”javascript\”>\n”);

htmlCode.append(“\tvar _bodyOnLoadHandler = document.body.onload;\n”);

htmlCode.append(“\tfunction _initFlashChart(){\n”);

htmlCode.append(“\t\tif(_bodyOnLoadHandler) _bodyOnLoadHandler();\n”);

htmlCode.append(“\t\tvar _divId= ‘” + divId + “‘;\n”);

htmlCode.append(“\t\tvar _swfId= ‘” + swfId + “‘;\n”);

htmlCode

.append(“\t\tvar _initWidth = document.getElementById(_divId).parentElement.offsetWidth;\n”);

htmlCode

.append(“\t\tvar _initHeight = document.getElementById(_divId).parentElement.offsetHeight;\n”);

htmlCode.append(“\t\tvar chart = new FusionCharts(‘” + appName

+ “/Charts/” + swfFile + “‘,_swfId,_initWidth,_initHeight)\n”);

htmlCode.append(“\t\tchart.setDataURL(‘” + appName

+ “/flashChartServlet?file=” + xmlFile + “‘);\n”);

htmlCode.append(“\t\tchart.render(_divId);\n”);

htmlCode.append(“\t}\n”);

htmlCode.append(“\tdocument.body.onload = _initFlashChart;\n”);

htmlCode.append(“</script>\n”);

return htmlCode.toString();

}

}

2.FlashChart具体代码:

package zHH;

import com.runqian.base4.util.ReportError;

import com.runqian.report4.model.expression.Expression;

import com.runqian.report4.model.expression.Variant2;

import com.runqian.report4.model.expression.graph.DrawBase;

import com.runqian.report4.model.expression.graph.ExtAlarmLine;

import com.runqian.report4.model.expression.graph.ExtGraphCategory;

import com.runqian.report4.model.expression.graph.ExtGraphProperty;

import com.runqian.report4.model.expression.graph.ExtGraphSery;

import com.runqian.report4.model.expression.graph.GraphParam;

import com.runqian.report4.usermodel.graph.AlarmLine;

import com.runqian.report4.usermodel.graph.GraphFont;

import com.runqian.report4.usermodel.graph.GraphFonts;

import java.awt.Color;

import java.io.File;

import java.io.FileWriter;

import java.io.PrintStream;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.Vector;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.output.XMLOutputter;

public class FlashChart extends DrawBase {

private int graphSort;

private String oneGraph;

private String primaryGraph;

private String secondGraph;

private String xmlFile;

private int labelStep = 1;

private int anchorStep = 1;

private int anchorRadius = 0;

private DecimalFormat df1;

private DecimalFormat df2;

public static final int GRAPH_SORT_SINGLE_SERIES = 1;

public static final int GRAPH_SORT_MULTI_SERIES = 2;

public static final int GRAPH_SORT_DUAL_Y = 3;

private void analyseParameter() {

String param = this.egp.getCustomParam();

if ((param == null) || (“”.equals(param)))

throw new ReportError(参数格式错误!);

String[] ps = param.split(“;”);

if ((ps.length < 2) || (ps.length > 5))

throw new ReportError(参数格式错误!);

String[] pps = ps[0].split(“,”);

this.graphSort = Integer.parseInt(pps[0]);

if ((this.graphSort < 1) || (this.graphSort > 3))

throw new ReportError(统计图类型错误!);

if (this.graphSort == 3) {

if (pps.length != 4)

throw new ReportError(参数格式错误!);

this.oneGraph = pps[1];

this.primaryGraph = pps[2];

this.secondGraph = pps[3];

}

this.xmlFile = ps[1];

if (this.xmlFile.charAt(0) == ‘=’) {

this.xmlFile = this.xmlFile.substring(1);

this.xmlFile = ((String) calcExpression(this.xmlFile));

}

if (ps.length >= 3)

this.labelStep = ((“”.equals(ps[2])) ? 1 : Integer.parseInt(ps[2]));

if (ps.length >= 4)

this.anchorStep = ((“”.equals(ps[3])) ? 1 : Integer.parseInt(ps[3]));

if (ps.length == 5) {

this.anchorRadius = ((“”.equals(ps[4])) ? 0 : Integer

.parseInt(ps[4]));

}

String pattern1 = this.egp.getDisplayDataFormat1();

if ((pattern1 == null) || (“”.equals(pattern1)))

pattern1 = “#”;

this.df1 = new DecimalFormat(pattern1);

String pattern2 = this.egp.getDisplayDataFormat2();

if ((pattern2 == null) || (“”.equals(pattern2)))

pattern2 = pattern1;

this.df2 = new DecimalFormat(pattern2);

}

private void PrintDebugInfo(String info) {

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd kk:mm:ss”);

String timePrefix = “[" + sdf.format(new Date()) + "]“;

Exception e = new Exception();

StackTraceElement ste = e.getStackTrace()[1];

String className = ste.getClassName();

className = className.substring(className.lastIndexOf(“.”) + 1);

String infoPrefix = ” “ + className + ” – “;

System.out.println(timePrefix + infoPrefix + info);

}

private String getColorHex(int color) {

String colorHex = Integer.toHexString(color);

colorHex = colorHex.substring(colorHex.length() – 6, colorHex.length());

return colorHex;

}

private String getColorHex(Color c) {

int color = c.getRGB();

return getColorHex(color);

}

private Element createGraphElement() {

Element chart = new Element(“chart”);

String title = this.egp.getGraphTitle();

if (title != null)

chart.setAttribute(“caption”, title);

String xTitle = this.egp.getXTitle();

if (xTitle != null)

chart.setAttribute(“xAxisName”, xTitle);

String yTitle = this.egp.getYTitle();

if (yTitle != null)

if (this.graphSort != 3) {

chart.setAttribute(“yAxisName”, yTitle);

} else {

String[] titles = yTitle.split(“;”);

if (titles.length >= 1)

chart.setAttribute(“PYAxisName”, titles[0]);

if (titles.length >= 2)

chart.setAttribute(“SYAxisName”, titles[1]);

}

GraphFont xLabelFont = this.egp.getFonts().getXLabelFont();

if (xLabelFont.isVerticalText())

chart.setAttribute(“rotateLabels”, “1″);

GraphFont yTitleFont = this.egp.getFonts().getYTitleFont();

if (!(yTitleFont.isVerticalText()))

chart.setAttribute(“rotateYAxisName”, “0″);

double yMinValue1 = this.egp.getYStartValue1();

double yMaxValue1 = this.egp.getYEndValue1();

double yMinValue2 = this.egp.getYStartValue2();

double yMaxValue2 = this.egp.getYEndValue2();

if (this.graphSort != 3) {

if (yMinValue1 != 0.0D)

chart.setAttribute(“yAxisMinValue”, String.valueOf(yMinValue1));

if (yMaxValue1 != 0.0D)

chart.setAttribute(“yAxisMaxValue”, String.valueOf(yMaxValue1));

} else {

if (yMinValue1 != 0.0D)

chart

.setAttribute(“PYAxisMinValue”, String

.valueOf(yMinValue1));

if (yMaxValue1 != 0.0D)

chart

.setAttribute(“PYAxisMaxValue”, String

.valueOf(yMaxValue1));

if (yMinValue2 != 0.0D)

chart

.setAttribute(“SYAxisMinValue”, String

.valueOf(yMinValue2));

if (yMaxValue2 != 0.0D)

chart

.setAttribute(“SYAxisMaxValue”, String

.valueOf(yMaxValue2));

}

byte legendPosition = this.egp.getLegendLocation();

switch (legendPosition) {

case 4:

chart.setAttribute(“showLegend”, “1″);

chart.setAttribute(“legendPosition”, “BOTTOM”);

break;

case 2:

chart.setAttribute(“showLegend”, “1″);

chart.setAttribute(“legendPosition”, “RIGHT”);

break;

case 3:

default:

chart.setAttribute(“showLegend”, “0″);

}

chart

.setAttribute(“bgColor”, getColorHex(this.egp

.getGraphBackColor()));

chart.setAttribute(“canvasBgColor”, getColorHex(this.egp

.getCanvasColor()));

if (this.egp.isDrawLineDot())

chart.setAttribute(“drawAnchors”, “1″);

else

chart.setAttribute(“drawAnchors”, “0″);

if (this.anchorRadius > 0)

chart.setAttribute(“anchorRadius”, String

.valueOf(this.anchorRadius));

byte lineTick = this.egp.getLineThick();

chart.setAttribute(“lineThickness”, String.valueOf(lineTick));

if (this.egp.isDrawShade())

chart.setAttribute(“showShadow”, “1″);

else

chart.setAttribute(“showShadow”, “0″);

if (this.egp.getDisplayData() == 2)

chart.setAttribute(“showValues”, “1″);

else {

chart.setAttribute(“showValues”, “0″);

}

chart.setAttribute(“formatNumberScale”, “0″);

int maxFraction = this.df1.getMaximumFractionDigits();

if (maxFraction != 0) {

chart.setAttribute(“decimals”, String.valueOf(maxFraction));

chart.setAttribute(“yAxisValueDecimals”, String

.valueOf(maxFraction));

if (maxFraction == this.df1.getMinimumFractionDigits())

chart.setAttribute(“forceDecimals”, “1″);

}

if (this.df1.toPattern().indexOf(“,”) == -1)

chart.setAttribute(“formatNumber”, “0″);

if (this.graphSort == 3) {

chart.setAttribute(“sFormatNumberScale”, “0″);

chart.setAttribute(“endAngX”, “35″);

chart.setAttribute(“endAngY”, “-20″);

chart.setAttribute(“chartOrder”, “Line,Area,Column”);

int maxFraction2 = this.df2.getMaximumFractionDigits();

if (maxFraction2 != 0) {

chart.setAttribute(“sDecimals”, String.valueOf(maxFraction2));

chart.setAttribute(“sYAxisValueDecimals”, String

.valueOf(maxFraction));

}

if (this.df2.toPattern().indexOf(“,”) == -1)

chart.setAttribute(“sFormatNumber”, “0″);

}

return chart;

}

private Element createCategoriesElement() {

Element categories = new Element(“categories”);

GraphFont gf = this.egp.getFonts().getXLabelFont();

categories.setAttribute(“font”, gf.getFamily());

categories.setAttribute(“fontSize”, String.valueOf(gf.getSize()));

categories.setAttribute(“fontColor”, getColorHex(gf.getColor()));

for (int i = 0; i < this.egp.categories.size(); ++i) {

ExtGraphCategory egc = (ExtGraphCategory) this.egp.categories

.get(i);

String label = egc.getNameString();

Element category = new Element(“category”);

category.setAttribute(“label”, label);

if (i % this.labelStep == 0)

category.setAttribute(“showLabel”, “1″);

else

category.setAttribute(“showLabel”, “0″);

categories.addContent(category);

}

return categories;

}

private void addSingleSeryElement(Element root) {

for (int i = 0; i < this.egp.categories.size(); ++i) {

Element set = new Element(“set”);

ExtGraphCategory egc = (ExtGraphCategory) this.egp.categories

.get(i);

set.setAttribute(“label”, egc.getNameString());

// 分出一扇

if (this.egp.getGraphProperty().isPieSpacing() && i == 2)

set.setAttribute(“isSliced”, “1″);

set.setAttribute(“color”, getColorHex(getColor(i)));

if (i % this.labelStep == 0)

set.setAttribute(“showLabel”, “1″);

else

set.setAttribute(“showLabel”, “0″);

ExtGraphSery egs = (ExtGraphSery) egc.getSeries().get(0);

double value = (egs == null) ? 0.0D : egs.getValue();

set.setAttribute(“value”, String.valueOf(value));

root.addContent(set);

}

}

private void addMultiSeryElement(Element root) {

for (int i = 0; i < this.gp.serNum; ++i) {

Element dataset = new Element(“dataset”);

String name = (String) this.gp.serNames.get(i);

dataset.setAttribute(“seriesName”, name);

String colorHex = getColorHex(getColor(i).getRGB());

dataset.setAttribute(“color”, colorHex);

for (int j = 0; j < this.gp.catNum; ++j) {

Element set = new Element(“set”);

ExtGraphCategory egc = (ExtGraphCategory) this.egp

.getCategories().get(j);

ExtGraphSery egs = (ExtGraphSery) egc.getSeries().get(i);

double value = (egs == null) ? 0.0D : egs.getValue();

set.setAttribute(“value”, String.valueOf(value));

if (j % this.anchorStep != 0)

set.setAttribute(“anchorAlpha”, “0″);

dataset.addContent(set);

}

root.addContent(dataset);

}

}

private void addDualYSeryElement(Element root) {

if (this.gp.serNum != 3) {

throw new ReportError(系列数量不正确!);

}

Element oneSery = new Element(“dataset”);

oneSery.setAttribute(“seriesName”, this.gp.serNames.get(0).toString());

if (“S”.equals(this.oneGraph))

oneSery.setAttribute(“parentYAxis”, “S”);

else {

oneSery.setAttribute(“parentYAxis”, “P”);

}

System.out.println(“oneSery:” + this.oneGraph);

// oneSery.setAttribute(“parentYAxis”, “P”);

oneSery.setAttribute(“renderAs”, this.oneGraph);

oneSery.setAttribute(“color”, getColorHex(getColor(0).getRGB()));

Element pSery = new Element(“dataset”);

pSery.setAttribute(“seriesName”, this.gp.serNames.get(1).toString());

if (“S”.equals(this.primaryGraph))

pSery.setAttribute(“parentYAxis”, “S”);

else {

pSery.setAttribute(“parentYAxis”, “P”);

}

System.out.println(“primaryGraph:” + this.primaryGraph);

pSery.setAttribute(“renderAs”, this.primaryGraph);

pSery.setAttribute(“color”, getColorHex(getColor(1).getRGB()));

Element sSery = new Element(“dataset”);

sSery.setAttribute(“seriesName”, this.gp.serNames.get(2).toString());

if (“S”.equals(this.secondGraph))

sSery.setAttribute(“parentYAxis”, “S”);

else {

sSery.setAttribute(“parentYAxis”, “P”);

}

System.out.println(“secondGraph:” + this.secondGraph);

sSery.setAttribute(“renderAs”, this.secondGraph);

sSery.setAttribute(“color”, getColorHex(getColor(2).getRGB()));

for (int i = 0; i < this.gp.catNum; ++i) {

Element oneSet = new Element(“set”);

Element pSet = new Element(“set”);

Element sSet = new Element(“set”);

ExtGraphCategory egc = (ExtGraphCategory) this.egp.getCategories()

.get(i);

ExtGraphSery egs1 = (ExtGraphSery) egc.getSeries().get(0);

ExtGraphSery egs2 = (ExtGraphSery) egc.getSeries().get(1);

ExtGraphSery egs3 = (ExtGraphSery) egc.getSeries().get(2);

double value1 = (egs1 == null) ? 0.0D : egs1.getValue();

oneSet.setAttribute(“value”, String.valueOf(value1));

double value2 = (egs2 == null) ? 0.0D : egs2.getValue();

pSet.setAttribute(“value”, String.valueOf(value2));

double value3 = (egs3 == null) ? 0.0D : egs3.getValue();

sSet.setAttribute(“value”, String.valueOf(value3));

if (i % this.anchorStep != 0)

oneSet.setAttribute(“anchorAlpha”, “0″);

if (i % this.anchorStep != 0)

pSet.setAttribute(“anchorAlpha”, “0″);

if (i % this.anchorStep != 0)

sSet.setAttribute(“anchorAlpha”, “0″);

oneSery.addContent(oneSet);

pSery.addContent(pSet);

sSery.addContent(sSet);

}

root.addContent(oneSery);

root.addContent(pSery);

root.addContent(sSery);

}

private Element createTrendlinesElement() {

Element trendlines = new Element(“trendlines”);

ExtAlarmLine alarmLine = null;

ArrayList alarmLineList = this.egp.getAlarmLines();

if (alarmLineList != null) {

for (int i = 0; i < alarmLineList.size(); i++) {

Element line = new Element(“line”);

alarmLine = (ExtAlarmLine) alarmLineList.get(i);

line.setAttribute(“startValue”, Double.toString(alarmLine

.getAlarmValue()));

line.setAttribute(“color”, getColorHex(alarmLine.getColor()));

line.setAttribute(“displayValue”, alarmLine.getName());

line.setAttribute(“showOnTop”, “1″);

line.setAttribute(“valueOnRight”, “1″);

trendlines.addContent(line);

}

}

return trendlines;

}

private Element createStylesElement() {

Element styles = new Element(“styles”);

Element definition = new Element(“definition”);

Element style = new Element(“style”);

if (this.graphSort == 3)

style.setAttribute(“name”, “bgAnim”);

else

style.setAttribute(“name”, “CanvasAnim”);

style.setAttribute(“type”, “animation”);

style.setAttribute(“param”, “_xScale”);

style.setAttribute(“start”, “0″);

style.setAttribute(“duration”, “1″);

definition.addContent(style);

Element application = new Element(“application”);

Element apply = new Element(“apply”);

if (this.graphSort == 3)

apply.setAttribute(“toObject”, “BACKGROUND”);

else

apply.setAttribute(“toObject”, “Canvas”);

if (this.graphSort == 3)

apply.setAttribute(“styles”, “bgAnim”);

else

apply.setAttribute(“styles”, “CanvasAnim”);

application.addContent(apply);

styles.addContent(definition);

styles.addContent(application);

return styles;

}

private void generateXMLFile(String xmlFile) throws Exception {

File f = new File(xmlFile);

PrintDebugInfo(文件路径: + f.getAbsolutePath());

if (!(f.exists())) {

f.createNewFile();

}

Element root = createGraphElement();

switch (this.graphSort) {

case 1:

addSingleSeryElement(root);

break;

case 2:

root.addContent(createCategoriesElement());

addMultiSeryElement(root);

root.addContent(createTrendlinesElement());

root.addContent(createStylesElement());

break;

case 3:

root.addContent(createCategoriesElement());

addDualYSeryElement(root);

root.addContent(createTrendlinesElement());

root.addContent(createStylesElement());

}

Document doc = new Document(root);

XMLOutputter outputter = new XMLOutputter();

outputter.setEncoding(“GBK”);

FileWriter fw = new FileWriter(f);

outputter.output(doc, fw);

fw.close();

}

private Object calcExpression(String expStr) {

Object result = null;

Expression exp = new Expression(this.ecs, this.ctx, expStr);

result = Variant2

.getValue(exp.calculate(this.ctx, false), false, false);

return result;

}

public void draw(StringBuffer htmlLink) {

analyseParameter();

File fdir = null;

fdir = new File(System.getProperty(“java.io.tmpdir”));

if (!(fdir.exists())) {

fdir.mkdir();

}

String path = System.getProperty(“java.io.tmpdir”) + File.separator

+ this.xmlFile;

try {

PrintDebugInfo(开始生成文件[" + this.xmlFile + "]…”);

generateXMLFile(path);

} catch (Exception e) {

e.printStackTrace();

}

PrintDebugInfo(文件[" + this.xmlFile + "]已生成!);

}

}

3.FlashChartServlet具体代码:

package zHH;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.io.PrintStream;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class FlashChartServlet extends HttpServlet

{

private static final long serialVersionUID = 9158725586773295041L;

private void PrintDebugInfo(String info)

{

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd kk:mm:ss”);

String timePrefix = “[" + sdf.format(new Date()) + "]“;

Exception e = new Exception();

StackTraceElement ste = e.getStackTrace()[1];

String className = ste.getClassName();

className = className.substring(className.lastIndexOf(“.”) + 1);

String infoPrefix = ” “ + className + ” – “;

System.out.println(timePrefix + infoPrefix + info);

}

public void init() throws ServletException {

PrintDebugInfo(初始化Servlet…”);

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {

doGetOrPost(request, response);

}

catch (Exception e) {

e.printStackTrace();

if (e instanceof ServletException) throw ((ServletException)e);

if (e instanceof IOException) throw ((IOException)e);

}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {

doGetOrPost(request, response);

}

catch (Exception e) {

e.printStackTrace();

if (e instanceof ServletException) throw ((ServletException)e);

if (e instanceof IOException) throw ((IOException)e);

}

}

private void doGetOrPost(HttpServletRequest request, HttpServletResponse response) throws Exception {

String file = request.getParameter(“file”);

if ((file == null) || (“”.equals(file))) throw new RuntimeException(没有指定文件名!);

File f = null;

FileReader fr = null;

PrintWriter pw = response.getWriter();

try

{

String path = System.getProperty(“java.io.tmpdir”) + File.separator + file;

f = new File(path);

PrintDebugInfo(文件路径: + f.getAbsolutePath());

if (!(f.exists())) { throw new RuntimeException(找不到目标文件!);

}

PrintDebugInfo(开始读取文件[" + file + "]…”);

fr = new FileReader(f);

for (int c = 0; (c = fr.read()) != -1; )

pw.write(c);

PrintDebugInfo(文件[" + file + "]读取完成!);

}

finally

{

if (pw != null) pw.close();

if (fr != null) fr.close();

if (f.exists()) {

f.delete();

PrintDebugInfo(文件[" + file + "]已删除!);

}

}

}

}

热门文章