最近项目代码中太多重复的编写Document,不同的接口需要不同的模板,于是重写提取公共部分打成jar包,方便各个系统统一使用~

  提取结构:

  

Http连接方式:

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate; public class HttpConnect { final Logger logger = LoggerFactory.getLogger(this.getClass()); public static final String SECCUESS_CODE = "000000"; private RestTemplate restTemplate ; private int connectTimeout = 1000; private int readTimeout = 15000; private static final String CHARSET_GBK = "GBK"; public String getMessages(Map<String,Object> sendData){
restTemplate = createRestTemplate();
HttpHeaders headers = new HttpHeaders();
MediaType type = new MediaType("text", "xml",
Charset.forName(CHARSET_GBK));
headers.setContentType(type);
String connectIp = (String) sendData.get("RequestIp");
String connectPort = (String) sendData.get("RequestPort");
String content = (String) sendData.get("message");
String url = "http://" + connectIp + ":" + connectPort;
HttpEntity<String> entity = new HttpEntity<String>(content, headers);
String result = restTemplate.postForObject(url, entity, String.class);
logger.info("send data:{},result:{}", content, result); return result;
} public RestTemplate createRestTemplate() {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setConnectTimeout(connectTimeout);
requestFactory.setReadTimeout(readTimeout); RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.getMessageConverters().add(0,
new MyStringHttpMessageConverter());
return restTemplate;
} static class MyStringHttpMessageConverter extends
StringHttpMessageConverter { List<Charset> acceptedCharsets = Arrays.asList(Charset.forName("GBK"),
Charset.forName("GB2312"), Charset.forName("GB18030"),
Charset.forName("UTF-8")); @Override
protected List<Charset> getAcceptedCharsets() {
return acceptedCharsets;
}
}
}

Socket方式:

package SocketClient;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class SocketClient {
 
final Logger logger = LoggerFactory.getLogger(this.getClass());
 
private Socket socket;
 
public SocketClient() {
 
}
 
public SocketClient(String connectIp, String connectPort,
  String connectTime, String readTime) throws SocketTimeoutException,
  ConnectException, UnknownHostException, Exception {
  createSocket(connectIp, connectPort, connectTime, readTime);
}
 
private void createSocket(String hostName, String port, String connectTime,
String readTime) throws SocketTimeoutException, ConnectException,
  UnknownHostException, Exception {
  InetAddress address = InetAddress.getByName(hostName);
  int timeOut = Integer.parseInt(connectTime);
  int readTimeOut = Integer.parseInt(readTime);
  socket = new Socket();
  int connectPort = Integer.valueOf(port);
  InetSocketAddress socketAddr = new InetSocketAddress(address,
  connectPort);
  // 连接后返回结果超时时间
  socket.setSoTimeout(readTimeOut);
  socket.setReuseAddress(true);
  socket.connect(socketAddr, timeOut);
}
 
public void sendData(byte[] data) throws IOException,RuntimeException{
  DataOutputStream dos = null;
 
try {
  dos = new DataOutputStream(socket.getOutputStream());
  dos.writeInt(data.length);
  dos.write(data);
} catch (IOException e) {
  e.printStackTrace();
} catch (RuntimeException e) {
  e.printStackTrace();
} finally {
  if (dos != null) {
    dos.close();
  }
  }
}
 
public byte[] recvData() throws Exception {
  byte[] data = null;
  DataInputStream dis = null;
 
  try {
    dis = new DataInputStream(socket.getInputStream());
    int dataLen = dis.readInt();
    data = new byte[dataLen];
    dis.readFully(data);
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      if (dis != null) {
        dis.close();
      }
    }
    return data;
}
 
public void destory()  {
if (this.socket != null && !this.socket.isClosed()) {
  try {
    this.socket.close();
    this.socket = null;
    } catch (IOException e) {
    logger.error("Socket Destory Error",e);
    }
    }
  }
}

加载hdfs中的模板文件,并转化为map形式嵌入项目中,存入内存缓存

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class LoadHdfsTemplate {
static final Logger logger = LoggerFactory
.getLogger(LoadHdfsTemplate.class); protected FileSystem fileSystem; public final boolean checkFile(String filePath) {
boolean exists = false;
try {
Path path = new Path(filePath);
exists = fileSystem.exists(path);
} catch (IOException e) {
logger.error("模板文件不存在!", e);
} catch (Exception e) {
logger.error("", e);
}
return exists;
} public Map<String,Object> readHdfsFile(String hdfsPath) throws IOException{
Path path = new Path(hdfsPath);
InputStream in = fileSystem.open(path);
List<String> lines = IOUtils.readLines(in);
if(null == lines || lines.isEmpty()){
return null;
}
Map<String,Object> map = new HashMap<String,Object>();
int rowNum = 0;
for(String line : lines){
rowNum++;
String[] content = line.split(" ");
String code = content[0];
String template = content[1];
if(StringUtils.isEmpty(line) || StringUtils.isEmpty(template)){
logger.error("第{}条模板格式错误!内容为:{}",rowNum,line);
continue;
}
map.put(code, template);
}
return map; }
}

加载本地文件,用于测试

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor; public class LoadTemplate{ final Logger logger = LoggerFactory.getLogger(LoadTemplate.class); private String filePath = "D:/template.txt"; public Map<String,Object> templateMap = new HashMap<String,Object>(); public Map<String, Object> loadTemplate() {
try {
File file = new File(filePath);
Integer lineCount = Files.readLines(file, Charsets.UTF_8,
new LineProcessor<Integer>() {
private int lineCount; public boolean processLine(String line)
throws IOException {
doSync(line);
lineCount++;
logger.debug("{} : {}", lineCount, line);
return true;
} public Integer getResult() {
return lineCount;
}
}); logger.info("读取{}行数据。", lineCount);
} catch (Exception e) {
logger.error("载入模板文件出错!", e);
}
return templateMap;
} private void doSync(String line) {
if(StringUtils.isEmpty(line)){
return;
} String[] content = line.split(" ");
String code = content[0];
String template = content[1];
templateMap.put(code, template);
}
}

解析发送的xml模板: (这里说明下,在系统调用时候,会传入调用的接口对应的模板,与封装的对应模板的值,与模板进行匹配封装)

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.google.common.base.Preconditions;

public class ParseTemplate {

public Map<String,Object> parseData(Map<String,Object> data,String template) throws DocumentException{
Map<String,Object> parseMap = new HashMap<String,Object>();
  Document documnet = DocumentHelper.parseText(template);
  Element root = documnet.getRootElement();
  Element headElement = root.element("Head");
  Preconditions.checkArgument(headElement != null, "XML中无Head元素");
  HeadElements(parseMap,headElement);

  Element bodyElement = root.element("body");
  if(null == bodyElement){
    bodyElement = root.element("Body");
  }else{
    Preconditions.checkArgument(bodyElement != null, "XML中无body元素");
  }
  bodyElements(data,bodyElement);
  parseMap.put("message", "<?xml version='1.0' encoding='gb18030'?>"+root.asXML());
  return parseMap;
}
//
@SuppressWarnings("unchecked")
private void HeadElements(Map<String,Object> parseMap , Element parentElement) {
  List<Element> fieldElements = parentElement.elements();
  for (Element fieldElement : fieldElements) {
    if(fieldElement.getName().equals("RequestType")){
      parentElement.remove(fieldElement);
      parseMap.put("RequestType", fieldElement.getText());
    }
    if(fieldElement.getName().equals("RequestIp")){
      parentElement.remove(fieldElement);
      parseMap.put("RequestIp", fieldElement.getText());
    }
    if(fieldElement.getName().equals("RequestPort")){
      parentElement.remove(fieldElement);
      parseMap.put("RequestPort", fieldElement.getText());
    }
    if(fieldElement.getName().equals("CreateTime")){
      String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
      fieldElement.setText(now);
    }
  }
}

@SuppressWarnings("unchecked")
private void bodyElements(Map<String,Object> data , Element parentElement) {
@SuppressWarnings("rawtypes")
  Iterator iter = parentElement.elementIterator();
  while(iter.hasNext()){
    Element childElement = (Element) iter.next();
    String filedName = childElement.getName();
    if(filedName.equals("field")){ //如果数据为filed,则进行填充处理
      String name = childElement.attributeValue("name");
      String value = (String) data.get(name);
      if(null != value){
        childElement.setText(value);
      }
    }else if(filedName.equals("struct")){
    //如果存在该节点对应的field填充数据,则进行后续处理
    String name = childElement.attributeValue("name");
    if(data.containsKey(name)){
      Map<String,Object> childData = (Map<String, Object>) data.get(name);
      bodyElements(childData, childElement);
    }
  }
}
}

/**
* 解析返回报文
* @param input
* @return
* @throws DocumentException
*/
public Map<String,Object> parseXml(String input) throws DocumentException{
  Map<String, Object> resultMap = new HashMap<String,Object>();
  Map<String,Object> result = new HashMap<String,Object>();
  Document documnet = DocumentHelper.parseText(input);
  Element root = documnet.getRootElement();
  Element headElement = root.element("Head");
  Preconditions.checkArgument(headElement != null, "XML中无Head元素");
  result.putAll(setHeadData(resultMap, headElement));
  Element bodyElement = root.element("Body");
  Preconditions.checkArgument(bodyElement != null, "XML中无Body元素");
  result.putAll(setBodyData(resultMap, bodyElement));
  return result;
}

@SuppressWarnings("unchecked")
public Map<String,Object> setHeadData(Map<String,Object> dataMap,Element parentElement){
  List<Element> fieldElements = parentElement.elements();
  for (Element fieldElement : fieldElements) {
    String name = fieldElement.getName();
    String value = fieldElement.getText();
    dataMap.put(name, value);
  }
  return dataMap;

}

@SuppressWarnings("unchecked")
private Map<String,Object> setBodyData(Map<String, Object> dataMap, Element parentElement) {
  List<Element> fieldElements = parentElement.elements("field");
  if(fieldElements.size() != 0){
    Preconditions.checkArgument(
    (fieldElements != null && !fieldElements.isEmpty()),
    "XML缺少field元素");
    for (Element fieldElement : fieldElements) {
      String name = fieldElement.attributeValue("name");
      String value = StringUtils.trimToNull(fieldElement.getTextTrim());
      dataMap.put(name, value);
    }
  }
  return dataMap;
}
}

方法调用入口: 从xml解析获得的连接方式为socket或http及其Ip和port 进行相应连接,发送并返回请求数据,随之进行解析封装入map,供应用系统提取使用字段值。

import java.io.UnsupportedEncodingException;
import java.util.Map; import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException; import Http.HttpConnect;
import Socket.SocketClient; import temlateRead.ParseTemplate; public class InterFaceCall { public Map<String,Object> getMessage(Map<String,Object> map,String template){
if(null != map && StringUtils.isNotBlank(template) && !map.isEmpty()){
try{
//解析封装模板
ParseTemplate parse = new ParseTemplate();
Map<String,Object> sendData = parse.parseData(map,template);
//连接方式
String connectType = (String) sendData.get("RequestType");
String connectIp = (String) sendData.get("RequestIp");
String connectPort = (String) sendData.get("RequestPort");
if("socket".equals(connectType)){
String content = (String) sendData.get("message");
SocketClient socketClient = new SocketClient(connectIp,connectPort);
socketClient.sendData(content.getBytes());
byte[] res = socketClient.recvData();
String resultData = new String(res,"gb18030");
map = parse.parseXml(resultData);
}else if("http".equals(connectType)){
HttpConnect request = new HttpConnect();
String resultData = request.getMessages(sendData);
map = parse.parseXml(resultData);
}
}catch(DocumentException e){
map.put("errorMessage", e);
e.printStackTrace();
}catch (UnsupportedEncodingException e) {
map.put("errorMessage", e);
e.printStackTrace();
}catch(Exception e){
map.put("errorMessage", e);
e.printStackTrace();
}
}else{
map.put("errorMessage", "传入数据或模板不能为空"); } return map; } }

测试类:

public static void main(String args[]){
String cusUseCashAmount = "";
Map<String,Object> resultData = null;
String template = "";
LoadTemplate aaa = new LoadTemplate();
Map<String,Object> temp = aaa.loadTemplate();;
//从****接口获取用户可用取现金额
String cardNo = "";
template = (String) temp.get("****");
InterFaceCall DataMap = new InterFaceCall();
Map<String,Object> sendData = new HashMap<String,Object>();
String SeqNo = UUID.randomUUID().toString().replace("-", "");
sendData.put("TrxType", "10010");
......
resultData = DataMap.getMessage(sendData, template);
cusUseCashAmount = (String)resultData.get("value1");
}

整理还没有完善,异常处理以及压力测试还没有进行,有空还要重写下。

  

Socket与Http方式解析发送xml消息封装中间件jar包的更多相关文章

  1. 使用XStream解析MXL文件用到的jar包---xpp3_min-1.1.3.4.O.jar和xstream-1.3.1.jar

    使用XStream解析MXL文件用到的jar包---xpp3_min-1.1.3.4.O.jar和xstream-1.3.1.jar

  2. 只要项目是maven构建的,pom.xml中依赖的jar包全都默认去你电脑本地仓库去找

    只要项目是maven构建的,pom.xml中依赖的jar包全都默认去你电脑本地仓库去找

  3. (转)如何在maven的pom.xml中添加本地jar包

    1 maven本地仓库认识 maven本地仓库中的jar目录一般分为三层:图中的1 2 3分别如下所示: 1 groupId 2 artifactId 3 version 4 jar包的依赖 如果要将 ...

  4. (转)如何在maven的pom.xml中添加本地jar包

    转载自: https://www.cnblogs.com/lixuwu/p/5855031.html 1 maven本地仓库认识 maven本地仓库中的jar目录一般分为三层:图中的1 2 3分别如下 ...

  5. 【Java TCP/IP Socket】构建和解析自定义协议消息(含代码)

    在传输消息时,用Java内置的方法和工具确实很用,如:对象序列化,RMI远程调用等.但有时候,针对要传输的特定类型的数据,实现自己的方法可能更简单.容易或有效.下面给出一个实现了自定义构建和解析协议消 ...

  6. Mybatis 的配置xml和properties放在jar包以外的一种方法

    1.问题 开发时候,将xml和properties放resources,直接可以访问到,然而打包后这两个文件也一同被打包到jar包里面,如果发布后想修改就会比较麻烦,所以希望将xml配置文件和prop ...

  7. maven的pom.xml配置文件相关依赖jar包

    <!--声明变量--> <properties> <project.build.sourceEncoding>UTF-8</project.build.sou ...

  8. 如何在maven项目的pom.xml文件中添加jar包

    在使用maven进行项目开发时,我们需要在pom.xml文件中添加自己所需要的jar包.这就要求我们获取jar包的groupId和artifactId. 我们可以在一些maven仓库上搜索我们所需要的 ...

  9. eclipse中基于maven构建的web项目pom.xml中指定的jar包无法发布到tomcat中

    eclipse运行maven web项目报错: 信息: Starting Servlet Engine: Apache Tomcat/7.0.57 一月 07, 2015 11:50:44 下午 or ...

随机推荐

  1. WPF中未将对象引用设置到对象的实例

    前几天,我开始了WPF的基础学习,一上来我就遇到了一个令我头痛的问题,按照书上的例子我写了一段属于自己的代码,一个简单的色调器.满心期待的编译运行,就出现了未将对象引用设置到对象的实例.我在网上查阅了 ...

  2. LPTHW 结束了

    基本上在学习了LPTHW的 类 继承 和 合成以后基本就结束. 后面几章都是根据web.py进行网页编程,以及自动化测试的.目前来看不太感兴趣. 稍后我可能找个实际项目进行锻炼下,比如 Crossin ...

  3. C++ 类继承的对象布局

    C++多重继承下,对象布局与编译器,是否为虚拟继承都有很大关系,下面将逐一分析其中的差别,相同点为都按照类继承的先后顺序布局(类内按照虚表.成员声明先后顺序排列).该类情况为子类按照继承顺序排列,如c ...

  4. 技海拾贝 - Java

    1. Java中的多线程 http://blog.csdn.net/luoweifu/article/details/46673975 Java中继承thread类与实现Runnable接口的区别 h ...

  5. winfrom 限制文本框小数点后两位

    private void numWeight_KeyPress(object sender, KeyPressEventArgs e) { if (char.IsNumber(e.KeyChar) | ...

  6. Flex 关闭浏览器

    在Actionscript 2及以前,要打开任何网址,只需调用全局函数getURL()即可.在Actionscript 3中,已经取消了getURL()这个全局函数,取而代之的是flash.net包中 ...

  7. Pattern Recognition And Machine Learning (模式识别与机器学习) 笔记 (1)

    By Yunduan Cui 这是我自己的PRML学习笔记,目前持续更新中. 第二章 Probability Distributions 概率分布 本章介绍了书中要用到的概率分布模型,是之后章节的基础 ...

  8. 素数方阵的工程ing

    2016 12 12 16 12 开始 2016 12 13 17 30   还没开打 2017 1 3 ..... 一星期前貌似打完了... 如下 #include<iostream> ...

  9. LeetCode-Search in Rotated Sorted Array II

    Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this ...

  10. 视图(View) – ASP.NET MVC 4 系列

           精心编写的整洁代码是开发一个可维护 Web 应用程序的基础.但用户在浏览器中访问时,这些工作他们是看不见的.用户对应用程序的第一印象,以及与应用程序的整个交互过程都是从视图开始的.    ...