通过socket接收报警信息,存入数据库

来源:互联网 发布:sql在表中添加字段 编辑:程序博客网 时间:2024/05/22 00:31
通过ip,端口,连接服务器,得到内容:public class TcpData {public static String IP=null;public static int PORT=0;public static Integer temp=0;public static void getData(){new DataBase().exeSQL2();System.out.println("地址为:"+IP+"----端口号为:"+PORT); String hostname = IP;         int port = PORT;         String content = "{\"type\":\"identify\",\"istation\":\"-1\"}";     String result="";         PrintWriter  out = null;         BufferedReader in = null;         try {             Socket socket = new Socket();             //socket链接指定的主机,超过10秒抛出链接不上异常              socket.connect(new InetSocketAddress(hostname,port), 10000);             // 得到请求的输出流对象               out = new PrintWriter(socket.getOutputStream());             // 发送请求参数             out.print(content);             // flush输出流的缓冲             out.flush();             // 定义 BufferedReader输入流来读取URL的响应             /*in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));             String line;             System.out.println("-------------------");             char[] chars = new char[5];             System.out.println(in.readLine());             System.out.println("-------------------");             while ((line = in.readLine()) != null) {                 result = line;                 System.out.println("获取的结果为:"+result);                   JsonUtils jsonUtils = new JsonUtils();              //                 jsonUtils.parseMap(result);                                                                }*/             Reader reader = new InputStreamReader(socket.getInputStream(),"UTF-8");             char[] chars = new char[1024];             int len;             StringBuilder sb = new StringBuilder();             System.out.println("长度为:"+reader.read(chars));             while ((len=reader.read(chars)) != -1) {               sb.append(new String(chars, 0, len));               System.out.println("获取的结果为:"+sb);               JsonUtils jsonUtils = new JsonUtils();               //此为数据解析方法,单独运行该Java文件测试连通性时,可以注释掉该代码               result = sb.toString();               jsonUtils.parseMap(result);               sb.setLength(0);             }             temp = 1;             System.out.println("终止发送,程序持续访问Socket连接");         }         catch(Exception ex) {             System.out.println("发送 POST 请求出现异常!"+ex);             System.out.println("终止发送,程序持续访问Socket连接");             temp = 1;         }         finally {             try{                 if(out!=null){                     out.close();                 }                 if(in!=null){                     in.close();                 }             }             catch(IOException ex){                 ex.printStackTrace();             }             if (temp==1) {             new TcpData().getData();             }         }}    public static void main(String[] args) {        System.out.println("--");    TcpData.getData();    }}对接收的内容进行解析:json字符串转Map    public static Map<String, Object> parseMap(String jsonStr) throws IOException, ParseException {          Map<String, Object> map = objectMapper.readValue(jsonStr, Map.class);          System.out.println(map);//        Map<String, Object> params = new HashMap<String, Object>();        String evhAlarmBianhao = map.get("alarmid").toString();        String evrAlarmBianhao = map.get("alarmid").toString();        System.out.println("报警的编号:"+map.get("alarmid"));        System.out.println("表明传送的是报警数据:"+map.get("alarmtype"));               //数据解析插入        String data = map.get("data").toString();        System.out.println("报警数据字符串待解析:"+data);                        String evhOcTime = "";        String evhRcTime = "";        String evhDesc = "";        String evrOcTime = "";        String evrDesc = "";        String evrLevel = "";        String evrNowValue = "";        String evrAlarmValue = "";        String evrReturnValue = "";        String evhNowValue = "";        String evhAlarmValue = "";        String evhReturnValue = "";              String [] stringArr = data.split(",");          int i = 0;        for (String string : stringArr) {        i++;        if (i==1) {        evhOcTime = string;        evrOcTime = string;        evhRcTime = string;        System.out.println("告警时间:"+string);}        if (i==2) {        System.out.println("变量名:"+string);}        if (i==3) {        System.out.println("告警类型:"+string);}        if (i==4) {        evhDesc = string;        evrDesc = string;        System.out.println("描述:"+string);}        if (i==5) {        evrLevel = string;        System.out.println("级别:"+string);}        if (i==6) {        evrNowValue = string;        evhNowValue = string;        System.out.println("当前值:"+string);}        if (i==7) {        evrAlarmValue = string;        evhAlarmValue = string;        System.out.println("告警值:"+string);}        if (i==8) {        evrReturnValue = string;        evhReturnValue = string;        System.out.println("恢复值:"+string);}}        String evhStationId = map.get("istation").toString();        String evrStationId = map.get("istation").toString();                System.out.println("站号(项目编号):"+map.get("istation"));                String evhLineId = map.get("lineid").toString();        String evrLineId = map.get("lineid").toString();        System.out.println("回路编号:"+map.get("lineid"));        System.out.println("表明传送的是报警数据"+map.get("type"));                String evhRcType = "1";                Date date = new Date();        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        String evhRcId = sdf.format(date);        String evrTime = sdf.format(date);                String evhBsaCode = map.get("bscode").toString();        String evrBsaCode = map.get("bscode").toString();                System.out.println("采集编号"+map.get("bscode"));                SocketList socketList = new SocketList();        socketList.add(evrStationId,evrLineId,evrBsaCode,evrDesc,evrOcTime,evrLevel,evrAlarmBianhao,evrTime,evrNowValue,evrAlarmValue,evrReturnValue);        //        GjInsertUtil gjInsertUtil = new GjInsertUtil();//        gjInsertUtil.save(evrStationId,evrLineId,evrBsaCode,evrDesc,evrOcTime,evrLevel,evrAlarmBianhao,evrTime,evrNowValue,evrAlarmValue,evrReturnValue);        return map;      } public static JsonNode parse(String jsonStr) throws IOException {          JsonNode node = null;          node = objectMapper.readTree(jsonStr);          System.out.println(node.getTextValue());        return node;      }        public static ObjectMapper getObjectMapper() {          return objectMapper;      }      public static void main(String[] args) throws IOException, ParseException {       String jsonStr = "{\"alarmid\":\"0000100100300036\",\"alarmtype\":1,\"data\":\"2016-10-08 14:10:12,var36,越限告警,10017 越上限 恢复,0,1725.60,,111.6\",\"istation\":1,\"lineid\":1003,\"type\":\"alarmdata\"}";                     JsonUtils.parseMap(jsonStr); }保存数据库public class GjInsertUtil extends DataBase {public Connection conn = null;/** * 入口函数  *  * @param arg *///public boolean save(String value1,String value2,String value3,String value4,String value5,String value6,String value7,String value8,String value9,String value10,String value11,String value12) {//public boolean save(String value1,String value2,String value3,String value4,String value5,String value6,String value7,String value8,String value9,String value10,String value11) {public boolean save(List<EvrBean> list){try {openDB();//String strSQL = "INSERT INTO Evh_Alarm (evh_station_id, evh_line_id,evh_bsa_code,evh_desc,evh_oc_time,evh_rc_time,evh_rc_type,evh_rc_id,evh_alarm_bianhao,evh_now_value,evh_alarm_value,evh_return_value) VALUES ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"', '"+value5+"', '"+value6+"', '"+value7+"', '"+value8+"', '"+value9+"', '"+value10+"', '"+value11+"', '"+value12+"')";//String strSQL = "INSERT INTO Evr_Alarm (evr_station_id, evr_line_id,evr_bsa_code,evr_desc,evr_oc_time,evr_level,evr_alarm_bianhao,evr_time,evr_now_value,evr_alarm_value,evr_return_value) VALUES ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"', '"+value5+"', '"+value6+"', '"+value7+"', '"+value8+"', '"+value9+"', '"+value10+"', '"+value11+"')"; System.out.println("-------------------------------------------");System.out.println(list.size());System.out.println("-------------------------------------------");if (list.size()>0) {String strSQL = "";strSQL += "INSERT INTO Evr_Alarm (evr_station_id, evr_line_id,evr_bsa_code,evr_desc,evr_oc_time,evr_level,evr_alarm_bianhao,evr_time,evr_now_value,evr_alarm_value,evr_return_value) VALUES";for (EvrBean evrAlarm : list) {strSQL += "('"+evrAlarm.getEvrStationId()+"','"+evrAlarm.getEvrLineId()+"','"+evrAlarm.getEvrBsaCode()+"','"+evrAlarm.getEvrDesc()+"','"+evrAlarm.getEvrOcTime()+"','"+evrAlarm.getEvrLevel()+"','"+evrAlarm.getEvrAlarmBianhao()+"','"+evrAlarm.getEvrTime()+"','"+evrAlarm.getEvrNowValue()+"','"+evrAlarm.getEvrAlarmValue()+"','"+evrAlarm.getEvrReturnValue()+"'),";}strSQL = strSQL.substring(0, strSQL.length()-1);System.out.println("----------开始-------------");System.out.println(strSQL);System.out.println("----------结束-------------");return exeSQL(strSQL, "");} else {System.out.println("暂时没有数据!!!!");return false;}} catch (Exception e) {e.printStackTrace();} finally {closeDB();}return false;}public static void main(String[] args) {GjInsertUtil gjInsertUtil = new GjInsertUtil();//gjInsertUtil.save("444","555","1","2","3","4","5","6","7","8","9","10");//gjInsertUtil.save("444","555","1","2","3","4","5","6","7","8","9");}}public class DataBase {  private Bean tempBean=Bean.getInstance();  public Connection con = null;  public ResultSet rs = null;  public Statement st = null;  public String sql = null;  public PreparedStatement ps = null;    public int count = 0;  /*** * 打开数据库   * */  public void openDB() {       con=ConnManager.getConnection(); //连接池    try {      st = con.createStatement();    }    catch (SQLException ex) {    tempBean.systemOutException("[com.phone.db.DataBase]中openDB()出错啦!" + ex.getMessage());    }     }  /**   * 关闭数据库连接   *   */  public void closeDB() {    if (rs != null) {      try {        rs.close();      }      catch (SQLException ex) {      tempBean.systemOutException("[com.phone.db.DataBase]中closeDB()出错啦!" + ex.getMessage());      }      finally {        rs = null;      }    }    if (st != null) {      try {        st.close();      }      catch (SQLException ex) {        System.out.println("[com.phone.db.DataBase]中closeDB()出错啦!" + ex.getMessage());      }      finally {        st = null;      }    }    if (con != null) {      try {        con.close();      }      catch (SQLException ex) {         System.out.println("[com.phone.db.DataBase]中closeDB()出错啦!" + ex.getMessage());      }      finally {        con = null;      }    }    if (ps != null) {      try {        ps.close();      }      catch (SQLException ex) {         System.out.println("[com.phone.db.DataBase]中closeDB()出错啦!" + ex.getMessage());      }      finally {        ps = null;      }    }  }  /**   * 统一执行SQL的添加,删除,修改[不能用于查询]   * */  public boolean exeSQL(String strSQL) {  String sMsg="执行到com.phone.db.DataBase.exeSQL()时出错啦!请查看传来的SQL语句.";  return exeSQL(strSQL,sMsg);  }    /**   *  统一执行SQL的添加,删除,修改[不能用于查询]   * @param strSQL   * @param sMsg   * @return   */  public boolean exeSQL(String strSQL,String sMsg)  {     boolean bool = false;    strSQL=tempBean.removeNull(strSQL);    if (strSQL.equals("") == false)     {      try {        openDB();        if(st.executeUpdate(strSQL) > 0)         {          bool = true;        }      }      catch (SQLException ex) {            tempBean.systemOutException(sMsg);      tempBean.systemOutException("执行SQL出错啦!"+strSQL);          tempBean.systemOutException(ex.getMessage());          try          {          con.rollback();          }catch (SQLException ex2)           {      tempBean.systemOutException(sMsg);          tempBean.systemOutException("rollback时出错了。");          }         }      finally {        closeDB();      }    }else    {    tempBean.systemOutException(sMsg);    tempBean.systemOutException("传来的SQL为空!");    }    return bool;}      /**   *  统一执行SQL的用于查询   * @param strSQL   * @param sMsg   * @return   */  public void exeSQL2()  {   //打开数据库连接  con=ConnManager.getConnection();    String sql = "select * from qt_socket";    try {//    openDB();        ps = (PreparedStatement)con.prepareStatement(sql);        rs = ps.executeQuery();        int col = rs.getMetaData().getColumnCount();//        System.out.println("============================");        while (rs.next()) {        TcpData tcpData = new TcpData();        tcpData.IP = rs.getString(2);        tcpData.PORT = Integer.valueOf(rs.getString(3));//        tcpData.CONTENT = rs.getString(4);        //打印获取的数据库数据            /*for (int i = 1; i <= col; i++) {                System.out.print(rs.getString(i) + "\t");                if ((i == 2) && (rs.getString(i).length() < 8)) {                    System.out.print("\t");                }             }*/        }//            System.out.println("============================");    } catch (SQLException e) {        e.printStackTrace();    }    finally{    //关闭数据库连接    closeDB();    }//    return null;}        /**   * 统一执行SQL的添加,删除,修改[不能用于查询]   * */  public boolean exeDelSQL(String strSQL) {  String sMsg="执行到com.phone.db.DataBase.exeDelSQL()时出错啦!请查看传来的SQL语句.";  return exeDelSQL(strSQL,sMsg);  }    /**   * 统一执行SQL 删除[不能用于查询]   * @param strSQL   * @param sMsg   * @return   */  public boolean exeDelSQL(String strSQL,String sMsg)  {     boolean bool = false;    strSQL=tempBean.removeNull(strSQL);    if (strSQL.equals("") == false)     {      try {        openDB();        if(st.executeUpdate(strSQL) >= 0)         {          bool = true;        }      }      catch (SQLException ex) {            tempBean.systemOutException(sMsg);      tempBean.systemOutException("执行SQL出错啦!"+strSQL);          tempBean.systemOutException(ex.getMessage());          try          {          con.rollback();          }catch (SQLException ex2)           {      tempBean.systemOutException(sMsg);          tempBean.systemOutException("rollback时出错了。");          }         }      finally {        closeDB();      }    }else    {    tempBean.systemOutException(sMsg);    tempBean.systemOutException("exeDelSQL()传来的SQL为空!");    }    return bool;}  public static void main(String[] args) { new DataBase().exeSQL2();}}

0 0