读取数据库中的数据,构造成柱状图,并将图片以文件输出流的形式保存到本地电脑中:
package net.test;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.nk.core.entitysupport.POJO;
import net.nk.entity.DataAttr;
import net.nk.entity.DataAttrQueryTemp;
import net.nk.entity.DataStatModel;
import net.nk.entity.SmDepartment;
import net.nk.enums.data.DataAttrSpecialDeal;
import net.nk.oms.common.Parameters;
import net.nk.service.data.iface.ServiceDataAttr;
import net.nk.service.sm.iface.ServiceSmDepartment;
import net.nk.util.cm.CmItemQuery;
import net.nk.util.cm.ICMConnectionPool;
import net.test.core.BusinessTestCase;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
import com.ibm.icu.impl.IntTrie;
import com.ibm.mm.sdk.common.DKConstant;
import com.ibm.mm.sdk.common.DKDDO;
import com.ibm.mm.sdk.server.DKDatastoreICM;
import com.sun.java_cup.internal.internal_error;
/**
* @author xiaoye
* @version create time:Aug 22, 2011 10:55:41 AM
* 类说明
*/
public class TestJfreeChart extends BusinessTestCase {
private static final String CHART_PATH = "E:/test/";
/**
* (方法说明)
* @param (参数说明)
* @return void
* @throws Exception
* @throws Exception
*/
public void test() throws Exception {
DataStatModel model = new DataStatModel();
model.setSmName("dd.png");
model.setSmX("attrGroup_public.attr_data_dept");
model.setSmY("SYSPUBAG.SYSFILESIZE");
model.setSmXName("数据所属科室");
model.setSmYName("文件大小");
model.setSmStatDataTypeID("dt_tool_pro");
ServiceDataAttr serviceDataAttrImpl = (ServiceDataAttr) this.getBean("serviceDataAttrImpl");
ServiceSmDepartment serviceSmDepartmentImpl = (ServiceSmDepartment) this.getBean("serviceSmDepartmentImpl");
beginSet(model,"char",serviceDataAttrImpl,serviceSmDepartmentImpl);
}
//开始
private void beginSet(DataStatModel stateModel,String xType,ServiceDataAttr serviceDataAttrImpl,ServiceSmDepartment serviceSmDepartmentImpl) throws Exception{
String xAttrId = stateModel.getSmX(); //X轴属性
String yAttrId = stateModel.getSmY(); //Y轴属性
String xName = stateModel.getSmXName();//X轴名称
String yName = stateModel.getSmYName();//Y轴名称
String charName = stateModel.getSmName(); //图片标题和图片名称
String itemType = stateModel.getSmStatDataTypeID();
List<String> itemTypeList = Arrays.asList(itemType.split(","));
CmItemQuery itemQuery = new CmItemQuery();
String hql = itemQuery.querypubItemsList(itemTypeList, new ArrayList<DataAttrQueryTemp>());
DKDatastoreICM dsICM = null;//CM连接
try{
//从CM中查找出相应的数据ddo对象
dsICM = ICMConnectionPool.getConnection(ICMConnectionPool.CMUSER, ICMConnectionPool.CMPW);
List<DKDDO> ddos = CmItemQuery.queryResults(hql.toString(),dsICM,true);
DefaultCategoryDataset dataset = getData(ddos,xAttrId,yAttrId,xType,serviceDataAttrImpl,serviceSmDepartmentImpl);
//构造柱状图
createBarSet(dataset,xName,yName,charName);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally {
if (dsICM != null)ICMConnectionPool.returnConnection(dsICM);
}
}
//构造柱状图
private void createBarSet(DefaultCategoryDataset dataset, String xName,
String yName, String charName) {
JFreeChart chart = ChartFactory.createBarChart3D(
charName, // 图表标题
xName, // 目录轴的显示标签
yName, // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
true, // 是否显示图例(对于简单的柱状图必须是false)
true, // 是否生成工具
false // 是否生成URL链接
);
CategoryPlot plot = chart.getCategoryPlot();//获得图表区域对象
//设置图表的纵轴和横轴
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLowerMargin(0.1);//设置距离图片左端距离此时为10%
domainAxis.setUpperMargin(0.1);//设置距离图片右端距离此时为百分之10
//顶部标题
//Font font=new Font("宋体",Font.BOLD,16);
//TextTitle title=new TextTitle("招生信息总览",font);
//chart.setTitle(title);
chart.getTitle().setFont(new Font("宋体",Font.BOLD,16));
//水平底部列表
domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14));
//水平底部标题
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12));
//设定柱子的属性
NumberAxis rangeAxis = (NumberAxis)plot.getRangeAxis();
rangeAxis.setUpperMargin(0.1);//设置最高的一个柱与图片顶端的距离(最高柱的10%)
//垂直标题
rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));
rangeAxis.setAutoTickUnitSelection(true);
//rangeAxis.setTickUnit(new NumberTickUnit(1));
//设置纵横坐标的显示位置
plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);//显示在下端(柱子竖直)或左侧(柱子水平)
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT); //数显示在下端(柱子水平)或左侧(柱子竖直)
//底部柱图说明
chart.getLegend().setItemFont(new Font("宋体",Font.PLAIN,12));
//柱图顶部数值显示
BarRenderer3D renderer = new BarRenderer3D();
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelFont(new Font("黑体",Font.PLAIN,13));
renderer.setBaseItemLabelsVisible(true);
//设置柱图最大宽度
renderer.setMaximumBarWidth(0.1);
//设定柱图数值显示位置
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER));
/*在指定的柱状图上显示数值
renderer.setSeriesItemLabelGenerator(1, new StandardCategoryItemLabelGenerator());
renderer.setSeriesItemLabelFont(1, new Font("黑体",Font.PLAIN,9));
renderer.setSeriesItemLabelsVisible(1, true);*/
plot.setRenderer(renderer);
FileOutputStream fos_jpg = null;
try {
isChartPathExist(CHART_PATH);
String chartName = CHART_PATH + charName;
fos_jpg = new FileOutputStream(chartName);
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 600, 500, true, 10);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 判断文件夹是否存在,如果不存在则新建
* @param chartPath
*/
private void isChartPathExist(String chartPath) {
File file = new File(chartPath);
if (!file.exists()) {
file.mkdirs();
// log.info("CHART_PATH="+CHART_PATH+"create.");
}
}
//构造数据集
private DefaultCategoryDataset getData(List<DKDDO> ddos,String xID,String yID,String xType,ServiceDataAttr serviceDataAttrImpl,ServiceSmDepartment serviceSmDepartmentImpl) throws Exception {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
Map<String, DataAttr> dataAttrMap = new HashMap<String, DataAttr>();
Map<String, Object> dataMap = new HashMap<String, Object>();
String xVal = "";
Object yVal ;
DKDDO ddo ;
short xDataId;
short yDataId;
String xTempId="";
try{
//如果是字符类型
if("char".equals(xType)){
List<POJO> dataAttrList = serviceDataAttrImpl.findAll();
for(POJO pojo:dataAttrList){
DataAttr attr = (DataAttr) pojo;
dataAttrMap.put(attr.getAttrId(), attr);
}
for(int i=0;i<ddos.size();i++){
ddo = ddos.get(i);
xDataId = ddo.dataId(DKConstant.DK_CM_NAMESPACE_ATTR,xID);
if(xID.indexOf(Parameters.AGM_SELECTION_4JAVA) != -1){
xTempId = xID.split(Parameters.GROUP_DECOLATOR)[1];
}else{
xTempId = xID;
}
if(dataAttrMap.containsKey(xTempId)){
DataAttr xAttr = dataAttrMap.get(xTempId);
if(xDataId > 0){
Object val = ddo.getData(xDataId);
if(val != null){
//如果是部门科室特殊属性
if(DataAttrSpecialDeal.department.getCode().equals(xAttr.getSpecial())){
SmDepartment smDepartment = serviceSmDepartmentImpl.findSmDepartmentByPrimaryId(val.toString());
if(smDepartment!=null){
xVal = smDepartment.getDepName();
}else{
xVal = ddo.getData(xDataId).toString();
}
}
}
}
}
//如果Y轴统计的为文件大小,直接读取属性值
if(Parameters.SYSTEM_PUB_AG_FILESIZE.equals(yID)){
yDataId = ddo.dataId(DKConstant.DK_CM_NAMESPACE_ATTR,yID);
if(yDataId > 0){
Object val = ddo.getData(yDataId);
if(val !=null){
yVal = (Double) val/(1024*1024); //化为MB
}else{
yVal = (double)0;
}
if(dataMap.containsKey(xVal)){
dataMap.put(xVal, (Double)yVal+(Double)dataMap.get(xVal));
}else{
dataMap.put(xVal, (Double)yVal);
}
}
}
}
}
if(dataMap.size() < 1){
dataset.setValue((Number)0,"数据","无数据");
}else{
Set<String> keySet = dataMap.keySet();
for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
Object value = dataMap.get(key);
dataset.setValue((Double)value , "数据",key);
}
}
}catch(Exception e){
e.printStackTrace();
throw e;
}
return dataset;
}
}