websocket推送告警

2 篇文章 0 订阅
1 篇文章 0 订阅

功能:将采集到的告警利用websocket推送到前端

public class AlarmServiceImpl implements AlarmService {

    static{
        startPushThread();
        startCloseThread();
    }
//  
//  public static void pushAllAlarms(){
//      InternalDao internalDao = new InternalDaoImpl();
//      List<JSONObject> alarms = internalDao.find("select * from gjgl");
//      pushAlarms(alarms);
//  }

    private static BlockingQueue<JSONObject> startAlarmQueue=new LinkedBlockingQueue<JSONObject>();
    private static BlockingQueue<JSONObject> endAlarmQueue=new LinkedBlockingQueue<JSONObject>();
    private static Thread pushThread;
    private static Thread closeThread;

    public static void pushAlarms(List<JSONObject> alarms){
        System.out.println("进入告警方法----------------------------------------------------");
        JSONArray dcvnewarray=new JSONArray();

        JSONObject jsonObject = new JSONObject();
        JSONArray jsArr = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject.put("_KEY_", "BMC");
        com.gexin.fastjson.JSONObject devices=new com.gexin.fastjson.JSONObject();

        SimpleDateFormat   f = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
        for (com.gexin.fastjson.JSONObject alarmData : alarms) {
            com.gexin.fastjson.JSONObject result=new com.gexin.fastjson.JSONObject();
            com.gexin.fastjson.JSONObject resultnew=new com.gexin.fastjson.JSONObject();
            String devId = alarmData.getString("DoorID");
            com.gexin.fastjson.JSONObject device = devices.getJSONObject(devId);
            String channelname=alarmData.getString("ChannelName");
            Date startTime=alarmData.getDate("StartTime");
            String timenew=alarmData.getDate("StartTime").getTime()+"";
            if(startTime!=null){
                alarmData.put("startTime", f.format(startTime));
            }
            if(device==null){
                device=new com.gexin.fastjson.JSONObject();
//              device.put(channelname, new JSONArray());
//              result.put("SQL数据库服务", device);
                devices.put(devId, device);
            }
            if(alarmData.getString("ID")!=null){
                result.put("报警级别", "critical");
                result.put("报警时间", alarmData.getString("StartTime"));
                result.put("报警信息", alarmData.getString("Msg"));
                device.put(channelname,result);
//              jsonObject1.put(devId, alarmData);
                //新推送
                resultnew.put("severity", "1");
                resultnew.put("time", timenew);
                resultnew.put("msg", alarmData.getString("Msg"));
                resultnew.put("modifyTime", new Date().getTime());
                resultnew.put("scene", MyProperties.getByKey("scene"));
                resultnew.put("key", "");
                resultnew.put("status", "OPEN");
                resultnew.put("id", devId);
                resultnew.put("title", alarmData.getString("ChannelName"));
                resultnew.put("arg1", "");
                resultnew.put("arg2", "");
                dcvnewarray.add(resultnew);
            }

        }
//      com.gexin.fastjson.JSONObject temp=new com.gexin.fastjson.JSONObject();
//      temp.put("clearAlarms", "true");
//      devices.put("temp", temp);
//      param.put(sceneId, devices);
//      System.out.println(param);
//      dataMap=PostURL.sendPost(momodao.getNodeURL(nodeId)+"/data/putdata", param.toString());
//      System.out.println(dataMap);

        jsonObject.put("_DATA_", devices);
        DCVDao dcvdao=new DCVDaoImpl();
//      String url=dcvdao.getNodeURL(nodeId)+"/services/DataStream";
//      if(url!=null){
//          new UinvClient(url).pushAlarm(jsonObject.toString());
//      }
//      System.out.println(MyProperties.getByKey("DCVURL"));
//      System.out.println(jsonObject.toString());
        System.out.println("推送告警数:"+alarms.size());
        String url=MyProperties.getByKey("DCVURL");
        String urlnew=MyProperties.getByKey("DCVURLNEW");
        if(MyProperties.getByKey("DCVVERSION").equals("3")){
            try {
                String mes=new Uinv30Client(urlnew).pushAlarm(dcvnewarray.toString());
                dcvnewarray.toJSONString();

                System.out.println("3.0版本"+mes);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if(url!=null){
            String result=new UinvClient(url).pushAlarm(jsonObject.toString());
            System.out.println("2.8版本"+result);
        }
//      String result =new UinvClient().pushAlarm(jsonObject.toString());

    }

    public static void closeAlarms(List<JSONObject> alarms){

        JSONArray dcvnewarray=new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONArray jsArr = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject.put("_KEY_", "BMC");
        com.gexin.fastjson.JSONObject devices=new com.gexin.fastjson.JSONObject();

        SimpleDateFormat   f = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
        for (com.gexin.fastjson.JSONObject alarmData : alarms) {
            com.gexin.fastjson.JSONObject result=new com.gexin.fastjson.JSONObject();
            com.gexin.fastjson.JSONObject resultnew=new com.gexin.fastjson.JSONObject();
            String devId = alarmData.getString("DoorID");
            com.gexin.fastjson.JSONObject device = devices.getJSONObject(devId);
            String channelname=alarmData.getString("ChannelName");
            Date startTime=alarmData.getDate("StartTime");
            String timenew=alarmData.getDate("StartTime").getTime()+"";
            if(startTime!=null){
                alarmData.put("startTime", f.format(startTime));
            }
            if(device==null){
                device=new com.gexin.fastjson.JSONObject();
//              device.put(channelname, new JSONArray());
//              result.put("SQL数据库服务", device);
                devices.put(devId, device);
            }
            if(alarmData.getString("ID")!=null){
                result.put("报警级别", "critical");
                result.put("报警时间", alarmData.getString("StartTime"));
                result.put("报警信息", alarmData.getString("Msg"));
                device.put(channelname,result);
//              jsonObject1.put(devId, alarmData);
                //新推送
                resultnew.put("severity", "1");
                resultnew.put("time", timenew);
                resultnew.put("msg", alarmData.getString("Msg"));
                resultnew.put("modifyTime", new Date().getTime());
                resultnew.put("scene", MyProperties.getByKey("scene"));
                resultnew.put("key", "");
                resultnew.put("status", "CLOSE");
                resultnew.put("id", devId);
                resultnew.put("title", alarmData.getString("ChannelName"));
                resultnew.put("arg1", "");
                resultnew.put("arg2", "");
                dcvnewarray.add(resultnew);

            }

        }
//      com.gexin.fastjson.JSONObject temp=new com.gexin.fastjson.JSONObject();
//      temp.put("clearAlarms", "true");
//      devices.put("temp", temp);
//      param.put(sceneId, devices);
//      System.out.println(param);
//      dataMap=PostURL.sendPost(momodao.getNodeURL(nodeId)+"/data/putdata", param.toString());
//      System.out.println(dataMap);

        jsonObject.put("_DATA_", devices);
//      DCVDao dcvdao=new DCVDaoImpl();
//      String url=dcvdao.getNodeURL(nodeId)+"/services/DataStream";
//      if(url!=null){
//          new UinvClient(url).pushAlarm(jsonObject.toString());
//      }
//      System.out.println(MyProperties.getByKey("DCVURL"));
//      System.out.println(jsonObject.toString());
        String url=MyProperties.getByKey("DCVURL");
        String urlnew=MyProperties.getByKey("DCVURLNEW");
        if(MyProperties.getByKey("DCVVERSION").equals("3")){
            try {
                String mes=new Uinv30Client(urlnew).pushAlarm(dcvnewarray.toString());
                System.out.println("3.0版本"+mes);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if(url!=null){
            String result=new UinvClient(url).pushAlarm(jsonObject.toString());
            System.out.println("2.8版本"+result);
        }
    }

    @Override
    public void startAlarm(JSONObject alarm) {
        try {
            startAlarmQueue.put(alarm);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void endAlarm(JSONObject alarm) {
        try {
            endAlarmQueue.put(alarm);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void startPushThread(){
        if(pushThread==null){
            pushThread=new Thread(){
                @Override
                public void run() {
                    while(true){
                        JSONObject alarm;
                        try {
                            alarm = startAlarmQueue.take();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e.getMessage(),e);
                        }
                        List<JSONObject> alarms=new ArrayList<JSONObject>();
                        List<String> ids=new ArrayList<String>();//
                        alarms.add(alarm);
                        while(startAlarmQueue.size()>0){
                            alarm = startAlarmQueue.poll();
                            alarms.add(alarm);
                        }
                        try {
                            int start1=0;
                            while(start1<alarms.size()){
                                int end1=start1+500;
                                if(end1>alarms.size()){
                                    end1=alarms.size();
                                }
                                List<com.gexin.fastjson.JSONObject> subalarm= alarms.subList(start1, end1);
                                pushAlarms(subalarm);
                                Thread.sleep(1000);
//                              list.addAll(websocketDao.findByPrivileges(subIds, privileges));
                                start1=end1;
                            }
//                          pushAlarms(alarms);
                            ids=transform(alarms);
                            Thread.sleep(1000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            pushThread.start();
        }
    }

    public static List<String>  transform(List<JSONObject> alarms){
        SimpleDateFormat   f = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
        List<JSONObject> alarmtrans=new ArrayList<JSONObject>();
        InternalDaoImpl internalDao = new InternalDaoImpl();
        WebsocketDao websocketdao=new WebsocketDaoImpl();
        List<String> ids=new ArrayList<String>();
        for(JSONObject alarm:alarms){
            JSONObject alarmtran=new JSONObject();
            List<com.gexin.fastjson.JSONObject> alarmDatas = internalDao.find("select id,gjdtp from gjdj where gjid=?", alarm.get("AlarmGrade"));
            List<com.gexin.fastjson.JSONObject> alarmDatas1 = internalDao.find("select id,lj from device where devid=?", alarm.get("DoorID"));
            List<com.gexin.fastjson.JSONObject> alarmDatas2 = internalDao.find("select id from channel where chanid=?",alarm.get("ChannelID"));
            if(alarmDatas.size()>0){
                alarmtran.put("gjd", alarmDatas.get(0).get("gjdtp"));
                alarmtran.put("gjdj", alarmDatas.get(0).get("id"));
            }
            if(alarmDatas1.size()>0){
                alarmtran.put("dev", alarmDatas1.get(0).get("id"));
                alarmtran.put("jz", alarmDatas1.get(0).get("lj"));
            }
            if(alarmDatas2.size()>0){
                alarmtran.put("xh", alarmDatas2.get(0).get("id"));      
            }
            else{
                alarmtran.put("xh","");
            }
            alarmtran.put("alarmid", alarm.get("AlarmRecID"));
            alarmtran.put("id", UUID.randomUUID().toString().replace("-", ""));
            ids.add(alarmtran.get("id").toString());
            alarmtran.put("kssj", f.format(alarm.getDate("StartTime")));
            alarmtran.put("cfz", alarm.get("TriggerValue"));
            alarmtran.put("gjxx", alarm.get("Msg"));
            if(alarmtran!=null){
                websocketdao.insert(alarmtran);
                alarmtrans.add(alarmtran);
            }
        }

        try {
            AlarmMonitorWebSocket.sendToAll(alarmtrans,ids);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ids;

    }
    public static void startCloseThread(){
        if(closeThread==null){
            closeThread=new Thread(){
                @Override
                public void run() {
                    while(true){
                        JSONObject alarm;
                        try {
                            alarm = endAlarmQueue.take();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e.getMessage(),e);
                        }
                        List<JSONObject> alarms=new ArrayList<JSONObject>();
                        alarms.add(alarm);
                        while(endAlarmQueue.size()>0){
                            alarm = endAlarmQueue.poll();
                            alarms.add(alarm);
                        }
                        try {
                            int start1=0;
                            while(start1<alarms.size()){
                                int end1=start1+500;
                                if(end1>alarms.size()){
                                    end1=alarms.size();
                                }
                                List<com.gexin.fastjson.JSONObject> subalarm= alarms.subList(start1, end1);
                                closeAlarms(subalarm);
                                Thread.sleep(1000);
//                              list.addAll(websocketDao.findByPrivileges(subIds, privileges));
                                start1=end1;
                            }
//                          closeAlarms(alarms);
                            Thread.sleep(3000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            closeThread.start();
        }
    }



}
package com.yyxt.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONArray;
import com.gexin.fastjson.JSONObject;
import com.yyxt.dao.UserDao;
import com.yyxt.dao.WebsocketDao;
import com.yyxt.dao.impl.UserDaoImpl;
import com.yyxt.dao.impl.WebsocketDaoImpl;
import com.yyxt.service.impl.AlarmServiceImpl;
import com.yyxt.util.YyxtSqlUtil;
@ServerEndpoint(value="/ws/AlarmMonitor")
public class AlarmMonitorWebSocket {
    private Session session;
    private static  String userId;

    List<JSONObject> list=new ArrayList<JSONObject>();
    @OnMessage  
    public void onMessage(String message,Session session)  
            throws IOException, InterruptedException, EncodeException  
       {  
//        System.out.println("***************");  
//        for(int i=0;i<list.size();i++){
            session.getBasicRemote().sendText(list.get(i).getGjxx());
//          
//        }
//        session.getBasicRemote().sendObject(list);
    }  

    @OnOpen  
    public void onOpen(Session session){  
        Map<String, List<String>> params = session.getRequestParameterMap();
        List<String> userId = params.get("userId");
        if(userId!=null&&userId.size()>0){
            this.userId=userId.get(0);
        }
        this.session=session;
        //this.userId=userID;
        System.out.println(" client connected ");  
        WebsocketDao websocketDao=new WebsocketDaoImpl();
        YyxtSqlUtil yyxtSqlUtil = new YyxtSqlUtil();
//        list=websocketDao.findAll();
        UserDao use = new UserDaoImpl();
        String iddep = use.getIddepById(userId.get(0));
        String privileges = yyxtSqlUtil.getWhereSql(userId.get(0), iddep, "gjgl");

            list=websocketDao.findByOnlyPrivileges(privileges);
            sendMessage(list,0);


        SharedGlobalFactory.getAlarmMonitorWebSocketSet().add(this);
    }  

    @OnClose  
    public void onClose(Session session){  
        SharedGlobalFactory.getAlarmMonitorWebSocketSet().remove(this); 
        System.out.println(" connection closed ");  
    } 
    public Session getSession() {
        return session;
    }
    public void setSession(Session session) {
        this.session = session;
    }

    public void sendMessage(List<JSONObject> data ,int sendCount){
        WebSocketResult webSocketResult = new WebSocketResult();
        webSocketResult.setData(data);
        webSocketResult.setAction("new");
        webSocketResult.setObject("gjgl");
        String sendJsonStr = JSON.toJSONString(webSocketResult);
        synchronized (this.session) {
            try {
            //  this.session.getAsyncRemote().sendText(sendJsonStr);// 异步方式
                this.session.getBasicRemote().sendText(sendJsonStr);
            } catch (Exception e) {
                if (sendCount < 5) {
                    sendMessage(data, ++sendCount);
                }
            }
        }
    }

    public static void sendToAll(List<JSONObject> datas,List<String> ids) throws IOException{
        YyxtSqlUtil yyxtSqlUtil = new YyxtSqlUtil();
        WebsocketDao websocketDao=new WebsocketDaoImpl();
//      list=websocketDao.findAll();
        UserDao use = new UserDaoImpl();
        String iddep = use.getIddepById(userId);
        String privileges = yyxtSqlUtil.getWhereSql(userId, iddep, "gjgl");
        List<JSONObject> list=new ArrayList<JSONObject>();
        int start=0;
        while(start<ids.size()){
            int end=start+2000;
            if(end>ids.size()){
                end=ids.size();
            }
            List<String> subIds = ids.subList(start, end);
            list.addAll(websocketDao.findByPrivileges(subIds, privileges));
            start=end;
        }
//      list=websocketDao.findByPrivileges(ids, privileges);
        WebSocketResult webSocketResult = new WebSocketResult();
        webSocketResult.setData(list);
        webSocketResult.setAction("new");
        webSocketResult.setObject("gjgl");
        String sendJsonStr = JSON.toJSONString(webSocketResult);
        CopyOnWriteArraySet<AlarmMonitorWebSocket> clients = SharedGlobalFactory.getAlarmMonitorWebSocketSet();
        for (AlarmMonitorWebSocket client : clients) {

            client.getSession().getBasicRemote().sendText(sendJsonStr);
        }
    }
    public static void sendToAllUpdate(List<JSONObject> datas) throws IOException{
        YyxtSqlUtil yyxtSqlUtil = new YyxtSqlUtil();
        WebsocketDao websocketDao=new WebsocketDaoImpl();
//      list=websocketDao.findAll();
        UserDao use = new UserDaoImpl();
        String iddep = use.getIddepById(userId);
        String privileges = yyxtSqlUtil.getWhereSql(userId, iddep, "gjgl");
        List<JSONObject> list=new ArrayList<JSONObject>();
        List<String> ids=new ArrayList<String>();
        if(datas.size()>0){
            for(int i=0;i<datas.size();i++){
                ids.add(i, datas.get(i).get("alarmid").toString());
            }
        }
        int start=0;
        while(start<ids.size()){
            int end=start+2000;
            if(end>ids.size()){
                end=ids.size();
            }
            List<String> subIds = ids.subList(start, end);
            list.addAll(websocketDao.findByPrivilegesUpdate(subIds, privileges));
            start=end;
        }
//      list=websocketDao.findByPrivileges(ids, privileges);
        WebSocketResult webSocketResult = new WebSocketResult();
        webSocketResult.setData(list);
        webSocketResult.setAction("update");
        webSocketResult.setObject("gjgl");
        String sendJsonStr = JSON.toJSONString(webSocketResult);
        CopyOnWriteArraySet<AlarmMonitorWebSocket> clients = SharedGlobalFactory.getAlarmMonitorWebSocketSet();
        for (AlarmMonitorWebSocket client : clients) {

            client.getSession().getBasicRemote().sendText(sendJsonStr);
        }
    }
    public static void sendToAllRemove(List<JSONObject> datas) throws IOException{
        YyxtSqlUtil yyxtSqlUtil = new YyxtSqlUtil();
        WebsocketDao websocketDao=new WebsocketDaoImpl();
//      list=websocketDao.findAll();
        UserDao use = new UserDaoImpl();
        String iddep = use.getIddepById(userId);
        String privileges = yyxtSqlUtil.getWhereSql(userId, iddep, "gjgl");
        List<JSONObject> list=new ArrayList<JSONObject>();
        List<String> ids=new ArrayList<String>();
        if(datas.size()>0){
            for(int i=0;i<datas.size();i++){
                ids.add(i, datas.get(i).get("alarmid").toString());
            }
        }
        int start=0;
        while(start<ids.size()){
            int end=start+2000;
            if(end>ids.size()){
                end=ids.size();
            }
            List<String> subIds = ids.subList(start, end);
            list.addAll(websocketDao.findByPrivilegesUpdate(subIds, privileges));
            start=end;
        }
//      list=websocketDao.findByPrivileges(ids, privileges);
        WebSocketResult webSocketResult = new WebSocketResult();
        webSocketResult.setData(list);
        webSocketResult.setAction("remove");
        webSocketResult.setObject("gjgl");
        String sendJsonStr = JSON.toJSONString(webSocketResult);
        CopyOnWriteArraySet<AlarmMonitorWebSocket> clients = SharedGlobalFactory.getAlarmMonitorWebSocketSet();
        for (AlarmMonitorWebSocket client : clients) {

            client.getSession().getBasicRemote().sendText(sendJsonStr);
        }
    }
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public static void sendChannelToAll(List<JSONArray> datas) {
        // TODO Auto-generated method stub
//      WebSocketResult webSocketResult = new WebSocketResult();
//      webSocketResult.setData(datas.toString());
//      webSocketResult.setAction("update");
//      webSocketResult.setObject("gjgl");
//      String sendJsonStr = JSON.toJSONString(webSocketResult);
//      CopyOnWriteArraySet<AlarmMonitorWebSocket> clients = SharedGlobalFactory.getAlarmMonitorWebSocketSet();
//      for (AlarmMonitorWebSocket client : clients) {
//          
//          client.getSession().getBasicRemote().sendText(sendJsonStr);
//      }
    }
}


public class SharedGlobalFactory {
    private static CopyOnWriteArraySet<AlarmMonitorWebSocket> alarmMonitorWebSocketSet = new CopyOnWriteArraySet<AlarmMonitorWebSocket>();
    public static CopyOnWriteArraySet<AlarmMonitorWebSocket> getAlarmMonitorWebSocketSet() {
        return alarmMonitorWebSocketSet;
    }

    public static void setAlarmMonitorWebSocketSet(
            CopyOnWriteArraySet<AlarmMonitorWebSocket> alarmMonitorWebSocketSet) {
        SharedGlobalFactory.alarmMonitorWebSocketSet = alarmMonitorWebSocketSet;
    }
}

import com.gexin.fastjson.JSONObject;

public class WebSocketResult {

    private List<JSONObject> data;
    private String action;
    private String object;
    public WebSocketResult() {
        super();
    }

    public WebSocketResult(List<JSONObject> data, String action, String object) {
        super();
        this.data = data;
        this.action = action;
        this.object = object;
    }

    public List<JSONObject> getData() {
        return data;
    }

    public void setData(List<JSONObject> data) {
        this.data = data;
    }

    public String getAction() {
        return action;
    }
    public void setAction(String action) {
        this.action = action;
    }
    public String getObject() {
        return object;
    }
    public void setObject(String object) {
        this.object = object;
    }



}

思路:主要是采集到的告警我们先把它放到队列里,再开启一个线程不断的从队列里去取,取出来后transform转成自己想要的格式,再推送到前端

格式:ws://127.0.0.1:8081/yyxt/ws/AlarmMonitor
其中:127.0.0.1:8081/yyxt 是项目路径

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值