`
wujunyi911622
  • 浏览: 9009 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

pushlet结合fusionCharts

阅读更多

Fusioncharts
FusionCharts是一个Flash的图表组件,它可以用来制作数据动画图表等

使用它非常简单,我按照在开发这个test的过程记录

首先将FusionCharts.js和Line.swf拷贝到你项目的WebContent(WebRoot)下


pushlet

1:到http://sourceforge.net/projects/pushlets/files/pushlets/上下载pushlet.jar并把它放到lib目录中,引入到工程。并且将pushlet.properties和sources.properties两个文件拷贝到WEB-INF目录中去
目录结构如下:



 2:在你的web.xml中加入

 

 <servlet>
    <servlet-name>pushlet</servlet-name>
    <servlet-class>
            nl.justobjects.pushlet.servlet.Pushlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>pushlet</servlet-name>
    <url-pattern>/pushlet.srv</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

 

3:修改你的sources.properties文件

加入你的pushle类

source9=com.wjy.HelloWorldPushlet

 


4:然后编写index.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>hello chart</title>
<meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <script type="text/javascript" src="ajax-pushlet-client.js"></script>
<script language="JavaScript" src='FusionCharts.js'></script>  

</head>
<body>
<form >

<div id="ok"></div>
<div id="chartdiv" align="center">
<script type="text/javascript">
 PL._init();
 PL.joinListen('/ok/haha');
 function onData(event) {
  var dataXml ="<graph baseFont='SunSim' baseFontSize='12' caption='折线图' subcaption='' xAxisName='时间' yAxisName='数字' hovercapbg='FFECAA' hovercapborder='F47E00' formatNumberScale='0' decimalPrecision='2' showValues='1' numdivlines='10' numVdivlines='0' showNames='1' rotateNames='1' rotateYAxisName='0' showAlternateHGridColor='1'>";
     dataXml += event.get("haha");
     dataXml += "</graph>"; 
     var chart = new FusionCharts('Line.swf', "ChartId", "1024", "600");
     chart.setDataXML(dataXml);
     chart.render('chartdiv');
 }
</script>
</div>
</form> 
</body>
</html>

 

5:后天HelloWorldPushlet 代码

 package com.wjy;

import java.io.Serializable;
import java.util.Calendar;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.core.EventPullSource;

@SuppressWarnings("serial")
public class HelloWorldPushlet extends EventPullSource implements Serializable {
 StringBuffer stringBuffer = new StringBuffer();
 
 JSONArray helloArray = new JSONArray();
    /**
     * 设置休眠时间
     */
    @Override
    protected long getSleepTime() {
        return 5000;
    }     
    /**
     * 创建事件
     *
     * 业务部分写在pullEvent()方法中,这个方法会被定时调用。
     */
    @Override
    protected Event pullEvent() {
     Long time = System.currentTimeMillis();
        Event event = Event.createDataEvent("/ok/haha");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 0);      
        StringBuffer sb = new StringBuffer();
        sb.append(c.get(Calendar.HOUR_OF_DAY));
        sb.append(":");
        sb.append(c.get(Calendar.MINUTE));
        sb.append(":");
        sb.append(c.get(Calendar.SECOND));
        StringBuffer sb1 = new StringBuffer();
        sb1.append((""+time).substring(8));
        if(null != helloArray && helloArray.size() > 11){
         helloArray.remove(0);               
        }
        HelloBean helloBean = new HelloBean();
     helloBean.setKey(sb.toString());
     helloBean.setValue(sb1.toString());
     helloArray.add(helloBean);

        StringBuffer strXml = new StringBuffer();   
        for(Object hello : helloArray){
   JSONObject jsonHelloBean = (JSONObject)hello;
   String key = jsonHelloBean.getString("key");
   String value = jsonHelloBean.getString("value");
   strXml.append("<set name='" + key + "' value='" + value + "' color='AFD8F8' />");
        }  
        String str =  strXml.toString(); 
        event.setField("haha", str);
        return event;
    }  
}
 

以上 每5秒钟刷新一次fusioncharts展现;

 

 

 

 

---------------------------------------------------------------------

以下是 复杂一点的功能;首次是查询,后面是每隔一段时间刷新一次

DataCollectPushletAction 中内嵌DataCollectPushlet ;外面实现业务

内部类实现推送服务数据

 

 

 

 package com.topinfo.action;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.core.EventPullSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.topinfo.entity.DataCollect;
import com.topinfo.entity.DataEquipment;
import com.topinfo.entity.DataMachine;
import com.topinfo.service.DataCollectService;
import com.topinfo.service.DataEquipmentService;
import com.topinfo.service.DataMachineService;

/**
 *
 *@Description: 将实时数据推送到前台,结合前台fusionCharts展现
 *@Since:2013-6-28上午09:14:41
 */
@Controller
@Qualifier
@Scope("prototype")
public class DataCollectPushletAction extends BaseAction {
  

 /**
  *@Fields serialVersionUID : (用一句话描述这个变量表示什么)
  */
 private static final long serialVersionUID = 1L;
  
 private static DataCollectService dataCollectService;
 
 private static List<DataCollect> dataCollectList; 
 
 private static Date                 startDate;
   
    private static Long      equipmentKey;
   
    static SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
   
 @Autowired
 private DataMachineService dataMachineService;
 
 @Autowired
 private DataEquipmentService dataEquipmentService;
 
    private Long      machineKey;
   
    /**
     *
     *@Description: 跳转到页面 根据equipmentKey来查它相关的最近半小时数据

     *@Since: 2013-6-28上午09:16:07
     *@return
     */
    public String ssxxtj(){  
     String dataString = "";
     Calendar c = Calendar.getInstance();
     c.add(Calendar.MINUTE, -30);
     startDate = c.getTime();
     dataCollectList = dataCollectService.getXxtjList(equipmentKey,startDate,null);
     StringBuffer strXml = new StringBuffer();        
        for(DataCollect dc : dataCollectList){
         strXml.append("<set name='" + formatter.format(dc.getCollectTime()) + "' value='" + dc.getDataValue() + "' color='FF1493' />");
        }
        dataString = strXml.toString();
     request.setAttribute("dataString", dataString);
     return "ssxxtj";
    }
 
    /**
     *
     *@Description: 根据equipmentKey来查它相关的最近半小时数据

     *@Since: 2013-6-28上午09:46:21
     */
    public static void pullPerMinute(){
     Calendar c = Calendar.getInstance();
      c.add(Calendar.MINUTE, -30);
      startDate = c.getTime();
      if(null != dataCollectService){
       dataCollectList = dataCollectService.getXxtjList(equipmentKey,startDate,null);
      }
    }
   
    public static class DataCollectPushlet extends EventPullSource{
     /**
      *
      *@Description: 设置休眠时间(设置1分钟)
      *@Author: WuJunyi
      *@Since: 2013-6-27下午03:22:02
      *@return
      */
     @Override
     protected long getSleepTime() {  
      return 15000;
     }
     /**
      *
      *@Description: 创建事件,统计数据等业务写在pullEvent()方法中,这个方法会被定时调用。
      *根据equipmentKey来查它相关的最近半小时数据
      *@Since: 2013-6-27下午03:22:24
      *@return
      */
     @Override
     protected Event pullEvent() {      
            Event event = Event.createDataEvent("/ok/haha");
            StringBuffer strXml = new StringBuffer();
            if(null != dataCollectList){
              for(DataCollect dc : dataCollectList){
         String key = formatter.format(dc.getCollectTime());
         Double value = dc.getDataValue();
         strXml.append("<set name='" + key + "' value='" + value + "' color='AFD8F8' />");
              }
            }
            String str =  strXml.toString(); 
            event.setField("haha", str);
            pullPerMinute();
            return event;
     } 
    }
    /**
     *
     *@Description: 获取所有机器
     *@Since: 2013-6-26上午09:22:43
     *@return
     */
    public List<DataMachine> getMachine(){
     return dataMachineService.findAllDataMachine();
    }
   
    /**
     *
     *@Description: 根据机器id获取该机器的所有设备
     *@Since: 2013-6-26上午09:26:48
     *@return
     */
    public List<DataEquipment> getByMachineId(){
     return dataEquipmentService.getByMachineId(machineKey);
    }
   
 public static DataCollectService getDataCollectService() {
  return dataCollectService;
 }

 @Autowired(required = true)
 public void setDataCollectService(DataCollectService dataCollectService) {
  DataCollectPushletAction.dataCollectService = dataCollectService;
 }

 public static List<DataCollect> getDataCollectList() {
  return dataCollectList;
 }

 public static void setDataCollectList(List<DataCollect> dataCollectList) {
  DataCollectPushletAction.dataCollectList = dataCollectList;
 }

 public static Date getStartDate() {
  return startDate;
 }

 public static void setStartDate(Date startDate) {
  DataCollectPushletAction.startDate = startDate;
 }

 public static Long getEquipmentKey() {
  return equipmentKey;
 }

 public static void setEquipmentKey(Long equipmentKey) {
  DataCollectPushletAction.equipmentKey = equipmentKey;
 }

 public Long getMachineKey() {
  return machineKey;
 }

 public void setMachineKey(Long machineKey) {
  this.machineKey = machineKey;
 }

}

 

 

jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<base href="<%=basePath%>">
<title></title>
<link rel="stylesheet" type="text/css" href="css/common.css" />
<script  type="text/javascript"
 src="javascript/jquery-1.4.2.min.js"></script>
<script src="javascript/tuxun_tips.js" type="text/javascript"></script>
<script type="text/javascript" src="javascript/view/view.js"></script>
<script type="text/javascript" src="javascript/common.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src='javascript/FusionCharts.js'></script> 
<script type="text/javascript" src="javascript/ajax-pushlet-client.js"></script>

</head>
<body>

 <form action="dataCollectPushletAction!ssxxtj.action" name="form1" id="form1"
  method="get">
  <h2 class="content_title  marginTop10 textIndent">采集数据列表</h2>
  <div class="search_div  marginTop10">
   <table class="search_table marginLeft40">
    <tr>
     <td class="search3_title">采集机器:</td>
     <td class="search3_text">
      <span class="select_span">
      <select name="machineKey" id="machine_Key">
              <option value="">-请选择-</option>
              <s:iterator value="getMachine()">
               <option value="${machineId }" <s:if test="machineId == machineKey">selected</s:if> >${name }</option> 
              </s:iterator>
             </select>
     </span>
     </td>

     <td class="search3_title">采集设备:</td>
     <td class="search3_text">
      <span class="select_span">
      <select name="equipmentKey" id="equipment_Key">
              <option value="">-请选择-</option>
              <s:iterator value="getByMachineId()">
               <option value="${equipmentId }" <s:if test="equipmentId == equipmentKey">selected</s:if> >${name }</option> 
              </s:iterator>
             </select>
     </span>
     </td>
     <td class="searc5_btn" colspan="3"><input type="submit" value="查询"
      data-hover="24" class="default_btn marginRight20 floatRight"/>
     </td>
    </tr>
   </table>
  </div>
  <p class="search_bottom ">&nbsp;</p>
  <div id="chartdiv" align="center" class="table_list_div  marginTop10">
  <script type="text/javascript">     
    var flag = true;    
    if(flag){
     var dataXml ="<graph baseFont='SunSim' baseFontSize='12'  subcaption=''  hovercapbg='FFECAA' hovercapborder='F47E00' formatNumberScale='0' decimalPrecision='2' showValues='1' numdivlines='10' numVdivlines='0' showNames='1' rotateNames='1' rotateYAxisName='0' showAlternateHGridColor='1'>";    
     dataXml += "<%=request.getAttribute("dataString") %>";   
        dataXml += "</graph>";
     var chart = new FusionCharts('swf/Line.swf', "ChartId", "1050", "360");
     chart.setDataXML(dataXml);
     chart.render('chartdiv');
    }
    PL._init();
    PL.joinListen('/ok/haha');
    function onData(event) {
     var dataXml ="<graph baseFont='SunSim' baseFontSize='12' subcaption='' hovercapbg='FFECAA' hovercapborder='F47E00' formatNumberScale='0' decimalPrecision='2' showValues='1' numdivlines='10' numVdivlines='0' showNames='1' rotateNames='1' rotateYAxisName='0' showAlternateHGridColor='1'>";
        dataXml += event.get("haha");
        dataXml += "</graph>"; 
        var chart = new FusionCharts('swf/Line.swf', "ChartId", "1024", "600");
        chart.setDataXML(dataXml);
        chart.render('chartdiv');
        flag = false;
    }
  </script>    
  </div>
 </form>
</body>
<script type="text/javascript">
$(document).ready(function(){
 init();
 var message = "<s:property value='message'/>";
 if (message.length != 0){
  tuxunTips.createTips(message,"middle");
 }
});

$(document).ready(function(){
  $("#machine_Key").change(function(){
    if($(this).val() == ""){
     $("#equipment_Key").html("<option value=\"\">- 请选择 -</option>");
    }else{
     $.post("dataCollectAction!getOptionsByMachineId.action",{machineId:$(this).val()},function(result){
      $("#equipment_Key").html("<option value=\"\">- 请选择 -</option>"+result);
     });
    }
  });
});
</script>
</html>

 

 

开发中遇到两个问题:第一,实现业务查询action为了使用pushlet,内部定义了static类实现EventPullSource,业务接口在内部类无法注入,后来采用@Autowired(required = true)
 public void setDataCollectService(DataCollectService dataCollectService) {
  DataCollectPushletAction.dataCollectService = dataCollectService;
 }来注入;希望各位兄弟姐妹能给出别的注入方式。

第二:

 位置不能换,换了只有google浏览器能用,调试很长时间才换了现在这个顺序,这个顺序就ok;

 

 

这次做的小记一个目的是记录一下,代码规范之类的就没有考虑,现在这个功能就是每隔一定的时间刷新一次,能否有什么方法让线条在向左推送而不是刷新整个页面

 

相关下载

 

  • 大小: 40.6 KB
  • 大小: 78.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics