100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Java应急广播平台接口对接demo(以 应急广播消息格式规范为例)

Java应急广播平台接口对接demo(以 应急广播消息格式规范为例)

时间:2022-07-31 06:54:18

相关推荐

Java应急广播平台接口对接demo(以 应急广播消息格式规范为例)

对接应急广播渠道,自己做的一个测试demo,记录一下,仅供自己日后回顾学习。

此版本为ssh+tomcat7+jdk7,另有springboot版本+jdk8,已上传资源文件gitee。

public JSONObject sendBroadCast(BoardCastConfig config){//获取发布内容String issueText = pubMessage.getPubreason();//广播接口 -集成测试淮北互联网接口地址String boardcastUrl = config.getUrl();//组装xml文件:File dataxml = createXml(pubMessage);//将文件压缩为tar文件String targetTar=dataxml.getAbsolutePath().substring(0, dataxml.getAbsolutePath().lastIndexOf(".")).replace("EBDB", "EBDT")+".tar";System.out.println("targetTar-==="+targetTar);File senddataTar = toCompress(dataxml, dataxml.getAbsolutePath().substring(0, dataxml.getAbsolutePath().lastIndexOf(".")).replace("EBDB", "EBDT")+".tar");System.out.println(senddataTar.getName());try{System.out.println("=================应急广播开始发送文件============");//发送文件://File responseTar = HttpUtils.sendbroadPost(broadcastURL, senddataTar,filepath);File responseTar = HttpUtils.sendbroadPost(boardcastUrl, senddataTar,"D:\\test");System.out.println("=================应急广播解压返回文件==================");//解压返回的数据//File file = uncompress(responseTar, filepath);File file = uncompress(responseTar, "D:\\test");System.out.println("解压后的文件:"+file.getName());System.out.println("=================应急广播开始解析文件========================");//解析数据JSONObject jsonObject = parseFile(file);JSONObject parseFile = jsonObject;System.out.println("=================应急广播解析文件结束========================");System.out.println("=========应急广播返回结果============"+parseFile.get("resultCode"));System.out.println("================应急广播解析完毕=============================");return jsonObject;}catch(Exception e){e.printStackTrace(); JSONObject json = new JSONObject();json.put("result", 2);json.put("msg", e.toString());return json;}}

public class HttpUtils {public static File sendbroadPost(String srcurl,File file,String filepath){try {String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线URL url = new URL(srcurl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);conn.setRequestMethod("POST");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");conn.setRequestProperty("Charsert", "UTF-8");conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);OutputStream out = new DataOutputStream(conn.getOutputStream());byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线StringBuilder sb = new StringBuilder();sb.append("--");sb.append(BOUNDARY);sb.append("\r\n");sb.append("Content-Disposition: form-data;name=\"filed1\";filename=\""+ "EBDT_10223000000000000010101030000000000000414.tar" + "\"\r\n");sb.append("Content-Type:application/x-tar\r\n\r\n");byte[] data = sb.toString().getBytes();out.write(data);DataInputStream in = new DataInputStream(new FileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}out.write(end_data);out.flush();out.close();System.out.println("===================广播文件发送完毕===============");if(conn.getResponseCode() == 200){System.out.println("====================开始接收文件=========================");InputStream inputStream = conn.getInputStream();File resFile = new File(filepath,"test1.tar");FileOutputStream resOut = new FileOutputStream(resFile);int len = 0;byte[] b = new byte[1024];while((len = inputStream.read(b))!= -1){resOut.write(b, 0, len);}resOut.close();inputStream.close();return resFile;}else{System.out.println("响应失败");}} catch (Exception e) {System.out.println("发送POST请求出现异常!" + e);e.printStackTrace();}return null;}}

public File createXml(PubMessage pubMessage) {try{//1.创建document对象Document document = DocumentHelper.createDocument();//2.创建根节点Element root = document.addElement("EBD");root.addAttribute("xmlns:xs", "/2001/XMLSchema");Element EBDVersion = root.addElement("EBDVersion");EBDVersion.addText("1.0");Element EBDID = root.addElement("EBDID");EBDID.addText("10234000000000000010101010000000040694582");//43位id-------------Element EBDType = root.addElement("EBDType");EBDType.addText("EBM");//src标签Element SRC = root.addElement("SRC");Element EBRID = SRC.addElement("EBRID");EBRID.addText("23400000000000001010101");//EBRID--------------Element URL = SRC.addElement("URL");URL.addText("http://上级平台ip:8080/bjyujing");//dest标签Element DEST = root.addElement("DEST");Element EBRID_dest = DEST.addElement("EBRID");EBRID_dest.addText("33406000000000103010101");//数据包生成时间SimpleDateFormat sdfpub = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String EBDTimeStr = sdfpub.format(new Date());Element EBDTime = root.addElement("EBDTime");EBDTime.addText(EBDTimeStr);//组装EBMElement EBM = root.addElement("EBM");Element EBMVersion = EBM.addElement("EBMVersion");EBMVersion.addText("1");Element EBMID = EBM.addElement("EBMID");EBMID.addText("2340000000000000101010105266767");//EBMID-----------------------//组装EBM的MsgBasicInfoElement MsgBasicInfo = EBM.addElement("MsgBasicInfo");Element MsgType = MsgBasicInfo.addElement("MsgType");//消息的类型,1:实际播发2:取消播发3:平台演练播发4:前端演练播发5:终端演练播发MsgType.addText("1");Element SenderName = MsgBasicInfo.addElement("SenderName");//SenderName.addText(pubMessage.getOrgName());//应急信息发布机构的全称SenderName.addText("安徽省调度控制平台");Element SenderCode = MsgBasicInfo.addElement("SenderCode");//SenderCode.addText(pubMessage.getOrgcode());//应急信息发布机构的编码SenderCode.addText("23400000000000001010101");Element SendTime = MsgBasicInfo.addElement("SendTime");SendTime.addText(sdfpub.format(new Date()));Element EventType = MsgBasicInfo.addElement("EventType");//当前type所需为预警类型:当前预警生成没有预警类型,暂写死为空串EventType.addText(pubMessage.getType());Element Severity = MsgBasicInfo.addElement("Severity");String level = "01".equals(pubMessage.getYjlevel()) ? "1" : "02".equals(pubMessage.getYjlevel()) ? "2": "03".equals(pubMessage.getYjlevel()) ? "3" : "04".equals(pubMessage.getYjlevel()) ? "4" : "0";Severity.addText(level);//预警级别Element StartTime = MsgBasicInfo.addElement("StartTime");StartTime.addText(sdfpub.format(new Date()));Element EndTime = MsgBasicInfo.addElement("EndTime");EndTime.addText(sdfpub.format(new Date()));//组装msgContentElement MsgContent = EBM.addElement("MsgContent");Element LanguageCode = MsgContent.addElement("LanguageCode");LanguageCode.addText("zho");Element MsgTitle = MsgContent.addElement("MsgTitle");//MsgTitle.addText(pubMessage.getTitle());MsgTitle.addText("淮北市应急广播");Element MsgDesc = MsgContent.addElement("MsgDesc");//MsgDesc.addText(pubMessageServiceImpl.getIssueText(pubMessage.getId(), cannelId));MsgDesc.addText("【测试应急广播】当前为应急广播渠道测试,请忽略,如有打扰请谅解");String pubdistrict = "";StringBuffer sb = new StringBuffer();//发布区域 多个用逗号隔开-//List<String> list = Arrays.asList(pubMessage.getPubdistrict().split(","));//if (list != null && list.size()>0) {//for (int i = 0;i<list.size();i++) {//if(i != list.size()-1){//pubdistrict+=list.get(i)+",";//}else{//pubdistrict += list.get(i);//}//}//}Element AreaCode = MsgContent.addElement("AreaCode");//AreaCode.addText(pubdistrict);AreaCode.addText("340602401000");Element ProgramNum = MsgContent.addElement("ProgramNum");ProgramNum.addText("0");// 5、设置生成xml的格式OutputFormat format = OutputFormat.createPrettyPrint();// 设置编码格式format.setEncoding("UTF-8");// 6、生成xml文件File file = new File("D:/test"+"/EBDB_10223000000000000010101030000000000000414.xml");XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);// 设置是否转义,默认使用转义字符writer.setEscapeText(false);writer.write(document);writer.close();System.out.println("生成应急广播请求文件成功");return file;}catch(Exception e){// TODO Auto-generated catch blocke.printStackTrace();}return null;}

//把文件打包成tar包public File toCompress(File sourceFile,String tarFilrPath) { FileOutputStream dest; TarOutputStream tarOut; try { //设置tar包位置File file = new File(tarFilrPath);dest = new FileOutputStream(file); tarOut = new TarOutputStream(new BufferedOutputStream(dest));//设置待打包源文件的位置tarOut.putNextEntry(new TarEntry(sourceFile, sourceFile.getName())); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); int count; byte data[] = new byte[2048]; while ((count = bis.read(data)) != -1) { tarOut.write(data, 0, count); } tarOut.flush(); bis.close(); tarOut.close(); return file;} catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null;}

public File uncompress(File sourceFile,String FilePath) { InputStream inputstream = null; OutputStream outputstream = null; TarInputStream zis = null; File tempFile = null; try { //读取压缩包的内容inputstream = new FileInputStream(sourceFile); zis = new TarInputStream(inputstream); //tarEntry:每一个文件对应一个tarEntryTarEntry tarEntry = null; while ((tarEntry = zis.getNextEntry()) != null) { String path = FilePath+"//"+ tarEntry.getName();tempFile = new File(path); if(!tempFile.exists()){tempFile.createNewFile();}outputstream = new FileOutputStream(tempFile); //定义一个缓冲池,缓冲池的大小,决定着每次读取的数据量大小,可以根据实际要处理的数据量大小和服务器的自身的配置,对其进行修改byte[] buffer = new byte[1024];int len = 0;while((len = zis.read(buffer))!=-1){outputstream.write(buffer, 0, len);}}return tempFile;} catch (Exception e) { e.printStackTrace(); System.out.println("=============解压应该广播返回文件异常==============");} finally { try { outputstream.flush(); inputstream.close(); zis.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } } return null;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。