jfreechart生成报表(定时器中)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nevergiveup12345/article/details/50523370

TimingListener中


<span style="font-size:18px;">public class TimingListener implements ServletContextListener {
	private Timer timer = null;
	public void contextInitialized(ServletContextEvent event) {
		timer = new Timer(true);
		try{		
		        //成交量定时查询启动(有发)
			this.dealCount();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent event) {
		timer.cancel();
	}
	//每天00:30执行
	public void dealCount(){
		timer = new Timer(true);
		Calendar theTaskCalendar = Calendar.getInstance();
		theTaskCalendar.set(theTaskCalendar.HOUR_OF_DAY, 0);
		theTaskCalendar.set(theTaskCalendar.MINUTE, 30);
		theTaskCalendar.set(theTaskCalendar.SECOND, 0);
		
		long interval = 1000 * 60 * 60 * 60 * 24;
//		long interval = 1000 * 30;
		System.out.println("=============成交量定时查询启动=============");
        timer.schedule(new DealCountTask(interval),theTaskCalendar.getTime(),
                interval);
	}
}</span>
DealCountTask
<span style="font-size:18px;">public class DealCountTask extends TimerTask{
	  protected Log log;
	  ArrayList list;
	  long intervalTime;
	  private Map map;

	  public Map getMap()
	  {
	    return this.map;
	  }

	  public void setMap(Map map) {
	    this.map = map;
	  }

	  public DealCountTask(long interval) {
	    this.log = LogFactory.getLog(super.getClass());
	    this.intervalTime = interval;
	  }

	  public void run() {
	    try {
		      this.map = new HashMap();
		      this.map.put("switchType", "DS_00008");

			  ITaskService taskService = (ITaskService)SpringBeanProxy.getBean("taskService");
		      this.list = ((ArrayList)taskService.getPlatformList(this.map));
		      this.map.clear();
		      for(int j=0 ;j<list.size() ; j++){
		    	  this.map = (Map)this.list.get(j);
		    	  if (this.map.get("switchValue").equals("1")) {
		    		
		    		HashMap param = new HashMap();
		  			Date date=new Date();
		  			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
		  			String nowDate=format.format(date);
		  			HashMap map1 = new HashMap();
		  			//获取platformId
		  			param.put("platformId", this.map.get("platformId"));
		  			//获取品种
		  			List list = new ArrayList();
		  			list = taskService.getCategory(param);
		  			
		  			Calendar calendar = Calendar.getInstance();
		  			calendar.setTime(date);
		  			//周  昨天 到 今天-8
		  			calendar.add(calendar.DATE, -8);
		  			Date rqs = calendar.getTime();
		  			calendar.add(calendar.DATE, 7);
		  			Date rqe = calendar.getTime();
		  			param.put("rqStart", format.format(rqs));
		  			param.put("rqEnd", format.format(rqe));
		  			//循环品种
		  			for(int i=0;i<list.size();i++){
		  				map1 = (HashMap) list.get(i);
		  				//获取品种名
		  				param.put("catalog_name" + i, map1.get("catalog_name"));
		  				param.put("catalog_name", map1.get("catalog_name"));
		  				map1 = taskService.getcount(param);
		  				param.put("categoryCountWeek" + i, map1.get("categoryCount"));
		  			}
		  			//月 
		  			calendar.add(calendar.MONTH, -1);
		  			rqs = calendar.getTime();
		  			calendar.add(calendar.MONTH, 1);
		  			rqe = calendar.getTime();
		  			param.put("rqStart", format.format(rqs));
		  			param.put("rqEnd", format.format(rqe));
		  			//循环品种
		  			for(int i=0;i<list.size();i++){
		  				map1 = (HashMap) list.get(i);
		  				//获取品种名
		  				param.put("catalog_name" + i, map1.get("catalog_name"));
		  				param.put("catalog_name", map1.get("catalog_name"));
		  				map1 = taskService.getcount(param);
		  				param.put("categoryCountMonth" + i, map1.get("categoryCount"));
		  			}
		  			//年
		  			calendar.add(calendar.YEAR, -1);
		  			rqs = calendar.getTime();
		  			calendar.add(calendar.YEAR, 1);
		  			calendar.add(calendar.DATE, -1);
		  			rqe = calendar.getTime();
		  			param.put("rqStart", format.format(rqs));
		  			param.put("rqEnd", format.format(rqe));
		  			//循环品种
		  			for(int i=0;i<list.size();i++){
		  				map1 = (HashMap) list.get(i);
		  				//获取品种名
		  				param.put("catalog_name" + i, map1.get("catalog_name"));
		  				param.put("catalog_name", map1.get("catalog_name"));
		  				map1 = taskService.getcount(param);
		  				param.put("categoryCountYear" + i, map1.get("categoryCount"));
		  			}
		  			//生成jfreechart图片(饼状图)
		  			String filename2 = ChartUtils.pieChart(param,list,"week");
		  			param.put("filename2", filename2);
		  			
		  			String filename3 = ChartUtils.pieChart(param,list,"month");
		  			param.put("filename3", filename3);
		  			
		  			String filename4 = ChartUtils.pieChart(param,list,"year");
		  			param.put("filename4", filename4);
		  			
		  			param.put("outResult", "1");
		    	  }
		      }
		}
	    catch (Exception e)
	    {
	      e.printStackTrace();
	      System.out.println("成交量定时查询异常:" + e.getMessage());
	    }
	  }
}</span>
TaskService
<span style="font-size:18px;">@Override
	public List getCategory(HashMap param) {
		List list = dao.queryMapList("json.getCategory", param); 
		return list;
	}

	@Override
	public HashMap getcount(HashMap param) {
		HashMap map = (HashMap) dao.queryMap("json.getcount", param);
		return map;
	}</span>
DA O中
<span style="font-size:18px;">public Map queryMap(String id, Object parameterObject) {
		return (Map) getSqlMapClientTemplate().queryForObject(id,
				parameterObject);
	}

	public Object queryObject(String id, Object parameterObject) {
		return getSqlMapClientTemplate().queryForObject(id, parameterObject);
	}</span>
json.xml中
<span style="font-size:18px;"><select id="json.getCategory" parameterClass="map" resultClass="java.util.HashMap">
            SELECT DISTINCT v.catalog_name as catalog_name FROM v_catalog_order v WHERE v.platform_id = #platformId#
        </select>
        <select id="json.getcount" parameterClass="map" resultClass="java.util.HashMap">
        SELECT
                ROUND(IFNULL(sum(v.init_weight),0),2) AS categoryCount
            FROM
                v_catalog_order v
            WHERE
                v.catalog_name = #catalog_name#
            AND date_format(v.create_date, '%Y-%m-%d') &gt;= #rqStart#
            AND date_format(v.create_date, '%Y-%m-%d') &lt;= #rqEnd#
       </select>  </span>
ChartUtils中(jfreechart)

<span style="font-size:18px;">public class ChartUtils {

	/**
	 * 使用Jfreechart生成图片(柱状图)
	 * @return
	 */
	public static String generaterBarChart(HashMap map) {
		//构造数据集合
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		for (int i = 4; i >= 0; i--) {
			dataset.addValue(Double.parseDouble(map.get("dealCount" + i).toString()),"",map.get("date" + i).toString());
//			dataset.addValue(i*1000, "日期", "0"+i);
		}
		JFreeChart chart = ChartFactory.createBarChart3D("",   //图形主标题				                    ); 
		// 设置总的背景颜色
		chart.setBackgroundPaint(ChartColor.WHITE);
		// 获得图表对象
		CategoryPlot p = chart.getCategoryPlot();
		// 设置图的背景颜色
		p.setBackgroundPaint(ChartColor.WHITE);
		//处理主标题乱码
		chart.getTitle().setFont(new Font("宋体",Font.BOLD,18));
		//处理子标题的乱码
		chart.getLegend().setItemFont(new Font("宋体",Font.BOLD,15));
		//处理X轴和Y轴的乱码
		//调用图表区域对象(xxxxPlot)
		CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
		//获取X轴的对象
		CategoryAxis3D categoryAxis3D = (CategoryAxis3D) categoryPlot.getDomainAxis();
		//获取Y轴的对象
		NumberAxis3D numberAxis3D = (NumberAxis3D) categoryPlot.getRangeAxis();
		//处理X轴上的乱码
		categoryAxis3D.setTickLabelFont(new Font("宋体",Font.BOLD,15));
		//处理X轴外的乱码
		categoryAxis3D.setLabelFont(new Font("宋体",Font.BOLD,15));
		//处理Y轴上的乱码
		numberAxis3D.setTickLabelFont(new Font("宋体",Font.BOLD,15));
		//处理Y轴外的乱码
		numberAxis3D.setLabelFont(new Font("宋体",Font.BOLD,15));
		
		//设置y轴上的刻度的默认值为100
//		numberAxis3D.setAutoTickUnitSelection(false);
//		NumberTickUnit unit = new NumberTickUnit(100);
//		numberAxis3D.setTickUnit(unit);
		
		//调用绘图区域对象(xxxxRenderer)
		BarRenderer3D barRenderer3D = (BarRenderer3D) categoryPlot.getRenderer();
		barRenderer3D.setSeriesPaint(0, Color.decode("#FF9E01"));
		//使图形变得苗条
		barRenderer3D.setMaximumBarWidth(0.08);
		//在图形上生成数字
		barRenderer3D.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		barRenderer3D.setBaseItemLabelsVisible(true);
		barRenderer3D.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));
		
		//要求使图形chart生成图片,在项目指定的chart文件夹下
		//获取项目chart文件夹的目录
		String path  = new Property(Constant.propFilePath).getValue("reportUploadPath");//E:/temp/reppic/
		//按照当前日期的年月日时分秒的形式生成图片名称
//		String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")+".png";
		String filename = "dealCount.png";
		//用Jfreechart生成的图片放置到指定的chart的文件夹下
		File file = new File(path+"/"+filename);
		try {
			ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}

	/**
	 * 饼状图
	 * @param map
	 * @param list 
	 * @return
	 */
	public static String pieChart(HashMap map, List list,String flag) {
		DefaultPieDataset dataset = new DefaultPieDataset();
		String filename = "";
		if (flag == "week") {
			//周
			for (int i = 0; i < list.size(); i++) {
				dataset.setValue(map.get("catalog_name"+i).toString(), Double.parseDouble(map.get("categoryCountWeek" + i).toString()));
				filename = "week.png";
			}
		}else if (flag == "month") {
			//月
			for (int i = 0; i < list.size(); i++) {
				dataset.setValue(map.get("catalog_name"+i).toString(), Double.parseDouble(map.get("categoryCountMonth" + i).toString()));
				filename = "month.png";
			}
		}else if (flag == "year") {
			//年
			for (int i = 0; i < list.size(); i++) {
				dataset.setValue(map.get("catalog_name"+i).toString(), Double.parseDouble(map.get("categoryCountYear" + i).toString()));
				filename = "year.png";
			}
		}
		
		JFreeChart chart = ChartFactory.createPieChart3D("", dataset,true, true, false);
		PiePlot3D plot = (PiePlot3D) chart.getPlot();
		// 获得图表对象
		PiePlot pie = (PiePlot) chart.getPlot(); 
		// 设置图的背景颜色
		pie.setBackgroundPaint(Color.white); 
		//没有数据时
		pie.setNoDataMessage("没有数据!"); 
		// 图片中显示百分比:默认方式
		// plot.setLabelGenerator(new
		// StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
		// 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
		plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({2})",
				NumberFormat.getNumberInstance(), new DecimalFormat("0.0%")));
		// 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
		plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(""));
		// 设置背景色为白色
		chart.setBackgroundPaint(Color.white);
		// 指定图片的透明度(0.0-1.0)
		plot.setForegroundAlpha(1.0f);
		// 指定显示的饼图上圆形(false)还椭圆形(true)
		plot.setCircular(true);
		// 设置图标题的字体
		Font font = new Font("黑体", Font.CENTER_BASELINE, 20);
		TextTitle title = new TextTitle("");
		title.setFont(font);
		chart.setTitle(title);
		plot.setLabelFont(new Font("SimSun", 0, 15));//里面的字
		LegendTitle legend = chart.getLegend(0);
		legend.setItemFont(new Font("宋体", Font.BOLD,20));//下面的字

		String path  = new Property(Constant.propFilePath).getValue("reportUploadPath");//E:/temp/reppic/

		File file = new File(path + "/" + filename);

		try {
			ChartUtilities.saveChartAsJPEG(
					file, 
					1, // JPEG图片的质量,0~1之间
					chart, // 统计图标对象
					600, // 宽
	
}</span>


猜你喜欢

转载自blog.csdn.net/nevergiveup12345/article/details/50523370