作者 朱兆平

合并分支 'origin' 到 'master'

Origin



查看合并请求 !1
target
out
xmlFromImf
.idea
logs
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
... ...
卡口IMF接收客户端
配置文件目录 程序主路径/config
config.properties配置文件 配置IMF 登录账号/密码 接收报文后的存储目录 、发送报文读取目录、读取发送目录报文后的 META节点生成
imf_config.properties 配置文件 配置 IMF服务端IP 端口号 编码类型 是否开启本地日志开关
log4j.properties 配置记录日志格式和信息
\ No newline at end of file
... ...
#登录账号
loginname = KAKO
#登录密码
loginpass = KAKO
#发送报文目录,相对程序目录
readDirectory = /Users/mrz/Downloads/3.CV972/1.CV报文
#接收存储报文目录
bakDirectory = xmlFromImf
#IMF MEAT报头配置
RCVR=
TYPE=KAKO
STYP=CARM
\ No newline at end of file
... ...
#log4j=/home/imf/log_api.xml
isneedlog=Y
#psip=218.28.199.134
psip=10.50.3.74
psport=7484
encoding=UTF-8
... ...
########Log4j configuration#####################################
log4j.rootLogger=INFO, stdout, fileout
log4j.logger.com.fiscal = INFO
#*******************************
log4j.logger.com.system = INFO
#*******************************
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM-dd HH:mm:ss,SSSS}[%p] %m%n
#yyyy-MM-dd HH:mm:ss
log4j.appender.fileout=org.apache.log4j.RollingFileAppender
log4j.appender.fileout.File=logs/imf.log
log4j.appender.fileout.MaxFileSize=50MB
log4j.appender.fileout.MaxBackupIndex=10
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%d{MM-dd HH:mm:ss,SSSS}[%p] %m%n
... ...
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="imf" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.6" level="project" />
<orderEntry type="library" name="Maven: org.dom4j:dom4j:2.1.0" level="project" />
<orderEntry type="library" name="Maven: jaxen:jaxen:1.1.6" level="project" />
<orderEntry type="library" name="Maven: org.jdom:jdom:1.1.3" level="project" />
</component>
</module>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tianbo</groupId>
<artifactId>nmsImfReader</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1.3</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
Manifest-Version: 1.0
Class-Path: commons-io-2.6.jar dom4j-2.1.0.jar jdom-1.1.3.jar jaxen-1.
1.6.jar antlr-2.7.7.jar antlr-3.2.jar antlr-runtime-3.2.jar aopallian
ce-1.0.jar apiConfig.jar asm-3.3.jar bcprov-jdk15-1.45.jar CL3Export.
jar CL3Nonexport.jar com.ibm.mq.axis2.jar com.ibm.mq.commonservices.j
ar com.ibm.mq.defaultconfig.jar com.ibm.mq.fta.jar com.ibm.mq.headers
.jar com.ibm.mq.jar com.ibm.mq.jmqi.jar com.ibm.mq.jms.Nojndi.jar com
.ibm.mq.pcf.jar com.ibm.mq.postcard.jar com.ibm.mq.soap.jar com.ibm.m
q.tools.ras.jar com.ibm.mqetclient.jar com.ibm.mqjms.jar commons-coll
ections-3.2.1.jar commons-lang-2.5.jar commons-logging-1.1.1.jar comm
ons-pool-1.5.5.jar connector.jar cxf-2.3.2.jar cxf-xjc-boolean-2.3.2.
jar cxf-xjc-bug671-2.3.2.jar cxf-xjc-dv-2.3.2.jar cxf-xjc-ts-2.3.2.ja
r dhbcore.jar FastInfoset-1.2.8.jar fscontext.jar geronimo-activation
_1.1_spec-1.1.jar geronimo-annotation_1.0_spec-1.1.1.jar geronimo-jav
amail_1.4_spec-1.7.1.jar geronimo-jaxws_2.2_spec-1.0.jar geronimo-jms
_1.1_spec-1.1.1.jar geronimo-servlet_3.0_spec-1.0.jar geronimo-stax-a
pi_1.0_spec-1.0.1.jar geronimo-ws-metadata_2.0_spec-1.1.3.jar Heartbe
atService.jar IMFClient.1.0.0.jar imfmsg.jar jaxb-api-2.2.1.jar jaxb-
impl-2.2.1.1.jar jettison-1.2.jar jetty-continuation-7.2.2.v20101205.
jar jetty-http-7.2.2.v20101205.jar jetty-io-7.2.2.v20101205.jar jetty
-server-7.2.2.v20101205.jar jetty-util-7.2.2.v20101205.jar jms.jar jn
di.jar jra-1.0-alpha-4.jar js-1.7R2.jar jsr173_1.0_api.jar jsr311-api
-1.1.1.jar jta.jar ldap.jar log4j-1.2.16.jar neethi-2.0.4.jar oro-2.0
.8.jar ProcessService.jar providerutil.jar resolver.jar returnXml.jar
rmm.jar saaj-api-1.3.jar saaj-impl-1.3.2.jar serializer-2.7.1.jar si
gar.jar slf4j-api-1.6.1.jar slf4j-jdk14-1.6.1.jar spring-aop-3.0.5.RE
LEASE.jar spring-asm-3.0.5.RELEASE.jar spring-beans-3.0.5.RELEASE.jar
spring-context-3.0.5.RELEASE.jar spring-core-3.0.5.RELEASE.jar sprin
g-expression-3.0.5.RELEASE.jar spring-jms-3.0.5.RELEASE.jar spring-tx
-3.0.5.RELEASE.jar spring-web-3.0.5.RELEASE.jar stax2-api-3.0.2.jar s
tringtemplate-3.2.jar UploadService.jar velocity-1.6.4.jar woodstox-c
ore-asl-4.0.8.jar wsdl4j-1.6.2.jar wss4j-1.5.11.jar xalan-2.7.1.jar x
bean_xpath.jar xbean.jar xml-resolver-1.2.jar xmlbeans-2.4.0.jar xmlb
eans-qname.jar xmlpublic.jar XmlSchema-1.4.7.jar xmlsec-1.4.4.jar jax
b-xjc-2.2.1.1.jar
Main-Class: com.tianbo.Main
... ...
package com.tianbo;
import com.caac.imf.api.IMFClient;
import com.caac.imf.api.IMFClientFactory;
import com.tianbo.imf.IMF_Reader;
import com.tianbo.imf.IMF_Sender;
import com.tianbo.util.IO.FileTool;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.File;
import java.util.List;
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
public static boolean LOGIN_OK = false;
public static boolean isSuc = true;
public static IMFClient client = null;
public static void sendMsg(String msg){
if (!msg.equals(null) && !msg.isEmpty()){
}
}
private static void start() throws Exception {
PropertyConfigurator.configure("config/log4j.properties");
client = IMFClientFactory.createInstance();
String loginname = FileTool.readProperties("loginname");
String loginpass = FileTool.readProperties("loginpass");
while (true) {
if (client != null) {
IMF_Reader reader = new IMF_Reader(client);
if (!reader.isrunning) {
reader.start();
logger.info("*********KAKO读取线程已开启***********");
} else {
// logger.info("*********KAKO读取线程已开启-不再启动线程*********");
}
IMF_Sender kako_sender = new IMF_Sender(client);
if(!kako_sender.isrunning) {
kako_sender.start();
}
}
if (!LOGIN_OK) {
loginIMF(client, loginname, loginpass, "config/imf_config.properties");
}
try {
Thread.sleep(30000L);
} catch (InterruptedException var7) {
var7.printStackTrace();
}
}
}
private static void loginIMF(IMFClient client, String userName, String password, String confFileName) {
if (client.initial(confFileName)) {
String message = client.login(userName, password);
logger.info("message=" + message);
if (message.indexOf("<CODE>1</CODE>") > 0) {
logger.info("登陆成功");
LOGIN_OK = true;
} else {
int times = 0;
while(times <= 3) {
logger.info("try connection...");
++times;
logger.info("message.=" + message);
if (message.indexOf("<CODE>1</CODE>") > 0) {
logger.info("登陆成功");
LOGIN_OK = true;
break;
}
logger.info("登录失败~~~~");
message = client.login(userName, password);
try {
Thread.sleep(4000L);
} catch (InterruptedException var7) {
var7.printStackTrace();
}
}
if (!LOGIN_OK) {
logger.info("多次尝试登录失败,退出登陆");
client.disconnect();
isSuc =false;
System.exit(-1);
}
}
}
}
public static void main(String[] args) throws Exception{
start();
}
}
... ...
package com.tianbo.imf;
import com.caac.imf.api.IMFClient;
import com.tianbo.util.IO.FileTool;
import com.tianbo.Main;
import org.apache.log4j.Logger;
public class IMF_Reader extends Thread{
protected static final Logger logger = Logger.getLogger(IMF_Reader.class);
private IMFClient client;
public static boolean isrunning;
public IMF_Reader(IMFClient client) {
this.client = client;
}
public void run() {
try{
isrunning =true;
while(true) {
if (Main.LOGIN_OK) {
String message = this.client.getMSG();
if (message != null) {
FileTool.writeFileToBak(message);
// IMF_Message_MainHandle mainHandle = new IMF_Message_MainHandle();
// IMF_META meta = mainHandle.messageHandle(message);
}
//logger.info("当前线程:"+Thread.currentThread().getName());
} else {
//logger.info("***");
}
try {
Thread.sleep(500L);
} catch (InterruptedException var3) {
var3.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
isrunning=false;
logger.info("****************读取线程不在了****************");
}
}
... ...
package com.tianbo.imf;
import com.caac.imf.api.IMFClient;
import com.tianbo.Main;
import com.tianbo.util.Date.DateUtil;
import com.tianbo.util.IO.FileTool;
import com.tianbo.util.XML.MakeImfMeta;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.List;
public class IMF_Sender extends Thread{
protected static final Logger logger = Logger.getLogger(IMF_Sender.class);
public static boolean isrunning;
private IMFClient client;
private String content;
public IMF_Sender(IMFClient client) {
this.client = client;
}
public IMF_Sender(IMFClient client, String content) {
this.client = client;
this.content = content;
}
public void run(){
try {
String sendDir = FileTool.readProperties("readDirectory");
String SNDR = FileTool.readProperties("loginname");
String TYPE = FileTool.readProperties("TYPE");
String STYP = FileTool.readProperties("STYP");
String RCVR = FileTool.readProperties("RCVR");
String DDTM = DateUtil.getDDTM();
String SEQN = DDTM;
if (this.client == null) {
logger.info("IMFClient has been closed");
return;
}
isrunning=true;
if(Main.isSuc){
// logger.info("<<<<<<<<<<<主线程初始化成功>>>>>>>>>>>>");
if(Main.LOGIN_OK){
while (true){
//发送报文
List<File> files = FileTool.readDirectoryFiles(new File(sendDir));
for (File file:files) {
String fileContent = FileTool.readfile(file);
String sendMsg = MakeImfMeta.makeImfDocument(SNDR,RCVR,TYPE,STYP,DDTM,SEQN,fileContent);
String returnMsg = this.client.sendMSG(sendMsg);
//发送成功处理,删除已发送成功的目录下的文件
if(returnMsg.indexOf("<CODE>9</CODE>")>=0){
FileUtils.forceDelete(file);
}
}
try {
Thread.sleep(500L);
} catch (InterruptedException var3) {
var3.printStackTrace();
}
}
}else{
logger.info("<<<<<<<<<<<登陆中>>>>>>>>>>>>");
}
}
}catch (Exception var14) {
var14.printStackTrace();
logger.info(var14.getMessage());
}
isrunning=false;
logger.info("<<<<<<<<<<<发送线程结束>>>>>>>>>>>>");
}
}
... ...
package com.tianbo.util.Date;
import java.text.SimpleDateFormat;
import java.util.Date;
public final class DateUtil {
private static Date currentDate = new Date();
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat timesdf = new SimpleDateFormat("yyyyMMddHHmmss");
public static String getToday(){
return sdf.format(currentDate);
}
public static String getDDTM(){
return timesdf.format(currentDate);
}
}
... ...
package com.tianbo.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import java.util.UUID;
public class Helper {
/**
* Object转BigDecimal类型-MRZ-2018年5月14日09:56:26
*
* @param value 要转的object类型
* @return 转成的BigDecimal类型数据
*/
static public BigDecimal getBigDecimal(Object value) {
BigDecimal ret = null;
if (value != null) {
if (value instanceof BigDecimal) {
ret = (BigDecimal) value;
} else if (value instanceof String) {
ret = new BigDecimal((String) value);
} else if (value instanceof BigInteger) {
ret = new BigDecimal((BigInteger) value);
} else if (value instanceof Number) {
ret = new BigDecimal(((Number) value).doubleValue());
} else {
throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
}
}
return ret;
}
public static String getUUID(){
return UUID.randomUUID().toString().replace("-", "");
}
}
... ...
package com.tianbo.util.IO;
import com.tianbo.util.Date.DateUtil;
import com.tianbo.util.Helper;
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.util.List;
import java.util.Properties;
public final class FileTool {
private final static String errorRootDirectory = "errorLogs";//错误的根目录名
private final static String xmlRootDirectory = "xmlLog"; //记录已收到的报文目录
private final static String Cherector = "UTF-8";
/**
* 写入文件
* @param path 二级目录
* @param content 写入内容
* @param rightOrwrong 是写入错误记录目录还是记录目录
*/
public static void writeFile(String path,String content,boolean rightOrwrong){
StringBuffer stringBuffer = new StringBuffer();
if (rightOrwrong){
stringBuffer.append(xmlRootDirectory).append("/").append(path).append("/").append(DateUtil.getToday()).append("/").append(Helper.getUUID()).append(".log");
}else {
stringBuffer.append(errorRootDirectory).append("/").append(path).append("/").append(DateUtil.getToday()).append("/").append(Helper.getUUID()).append(".log");
}
File file = new File(stringBuffer.toString());
try{
FileUtils.writeStringToFile(file,content,Cherector);
}catch (IOException e){
e.printStackTrace();
}
}
public static String readfile(File file) throws IOException{
String fileToString = FileUtils.readFileToString(file, "UTF-8");
return fileToString;
}
public static List<File> readDirectoryFiles(File dir){
List<File> files = (List<File>)FileUtils.listFiles(dir,new String[]{"xml"},false);
return files;
}
public static void writeWaybill(String path,String content,String waybillNo){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(xmlRootDirectory).append("/").append(path).append("/").append(DateUtil.getToday()).append("/").append(waybillNo).append(".log");
File file = new File(stringBuffer.toString());
try{
FileUtils.writeStringToFile(file,content,Cherector);
}catch (IOException e){
e.printStackTrace();
}
}
public static void writeFileToBak(String content){
String bakDir = readProperties("bakDirectory");
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(bakDir).append("/").append(Helper.getUUID()).append(".txt");
File file = new File(stringBuffer.toString());
try{
FileUtils.writeStringToFile(file,content,Cherector);
}catch (IOException e){
e.printStackTrace();
}
}
public static String readProperties(String key){
Properties properties = new Properties();
String value = "";
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader("config/config.properties"));
properties.load(bufferedReader);
//获取key对应的value值
value= properties.getProperty(key);
}catch (Exception e){
e.printStackTrace();
}
return value;
}
}
... ...
package com.tianbo.util.XML;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
public class MakeImfMeta {
public static String makeImfDocument(String SNDR,String RCVR,String TYPE,String STYP,String DDTM,String SEQN,String Content) throws DocumentException,UnsupportedEncodingException{
Document document = DocumentHelper.createDocument();
Element root = document.addElement( "MSG" );
Element meta = root.addElement("META");
meta.addElement("SNDR").addText(SNDR);
meta.addElement("RCVR").addText(RCVR);
meta.addElement("SEQN").addText(SEQN);
meta.addElement("DDTM").addText(DDTM);
meta.addElement("TYPE").addText(TYPE);
meta.addElement("STYP").addText(STYP);
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(new ByteArrayInputStream(Content.getBytes("UTF-8")));
Element contentRoot = doc.getRootElement();
root.add(contentRoot);
return document.asXML();
}
}
... ...
package com.tianbo.util.XML;
import org.jdom.Element;
public class SubNode {
private Element element;
public SubNode(Element element) {
this.element = element;
}
public Element getElement() {
return this.element;
}
public void setElement(Element element) {
this.element = element;
}
}
... ...
package com.tianbo.util.XML;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
public class XML2ENTITY {
@SuppressWarnings("unchecked")
/**取KEY的VALUE
*
*/
public Map<String, Object> Dom2Map(Document doc){
Map<String, Object> map = new HashMap<String, Object>();
if(doc == null)
return map;
Element root = doc.getRootElement();
for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
Element e = (Element) iterator.next();
List list = e.elements();
if(list.size() > 0){
map.put(e.getName(), Dom2Map(e));
}else
map.put(e.getName(), e.getText());
}
return map;
}
@SuppressWarnings("unchecked")
public Map Dom2Map(Element e){
Map map = new HashMap();
List list = e.elements();
if(list.size() > 0){
for (int i = 0;i < list.size(); i++) {
Element iter = (Element) list.get(i);
List mapList = new ArrayList();
if(iter.elements().size() > 0){
Map m = Dom2Map(iter);
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(m);
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(m);
}
map.put(iter.getName(), mapList);
}else
map.put(iter.getName(), m);
}
else{
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(iter.getText());
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(iter.getText());
}
map.put(iter.getName(), mapList);
}else
map.put(iter.getName(), iter.getText());
}
}
}else
map.put(e.getName(), e.getText());
return map;
}
public List<Map> attrOfElement(Element e){
List attList = new ArrayList();
List<Attribute> listAttr = e.attributes();
for(Attribute attr:listAttr){//遍历当前节点的所有属性
String name=attr.getName();//属性名称
String value=attr.getValue();//属性的值
Map<String, Object> attMap = new HashMap<String, Object>();
attMap.put(name,value);
attList.add(attMap);
}
return attList;
}
@SuppressWarnings("unchecked")
/**遍历所有节点的属性值
*
*/
public Map<String, Object> Dom2Map_propety(Document doc){
Map<String, Object> map = new HashMap<String, Object>();
if(doc == null)
return map;
Element root = doc.getRootElement();
for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
Element e = (Element) iterator.next();
List list = e.elements();
if(list.size() > 0){
map.put(e.getName(), Dom2Map_propety(e));
}else {
map.put(e.getName(), attrOfElement(e));
}
}
return map;
}
@SuppressWarnings("unchecked")
public Map Dom2Map_propety(Element e){
Map map = new HashMap();
List list = e.elements();
if(list.size() > 0){
for (int i = 0;i < list.size(); i++) {
Element iter = (Element) list.get(i);
List mapList = new ArrayList();
if(iter.elements().size() > 0){
Map m = Dom2Map_propety(iter);
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(m);
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(m);
}
map.put(iter.getName(), mapList);
}else
map.put(iter.getName(), m);
}
else{
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(iter.getText());
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(iter.getText());
}
map.put(iter.getName(), mapList);
}else{
map.put(iter.getName(), attrOfElement(iter));
}
}
}
}else {
map.put(e.getName(), attrOfElement(e));
}
return map;
}
/**
* 判断map是否包含key,包含返回KEY值,不包含返回NULL
* @param map
* @param key
* @return
*/
public static Object getMap(Map map, String key){
if(map!=null && map.containsKey(key)){
return map.get(key);
} else {
return null;
}
}
}
... ...
package com.tianbo.util.XML;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
public class XMLParse {
private static final Logger logger = LoggerFactory.getLogger(XMLParse.class);
private static String xmlString;
private static Document document;
private static SAXBuilder builder;
private static Element root;
private static LinkedList<SubNode> listNode;
private static StringReader xmlReader;
private static InputSource xmlSource;
private static List<Map> maps = new ArrayList<Map>();
private static Map<String,Map> allElementValue = new HashMap<String, Map>();
private static int domCount=0;
private String value;
public XMLParse() {
}
public XMLParse(String XmlString) {
builder = new SAXBuilder();
root = null;
listNode = new LinkedList();
value = "";
document =new Document();
xmlString = XmlString;
}
public Map getAllValuesFromXmlString() throws Exception{
try {
xmlReader = new StringReader(xmlString);
xmlSource = new InputSource(xmlReader);
document = builder.build(xmlSource);
root = document.getRootElement();
getElements(root);
}catch (Exception var17) {
var17.printStackTrace();
throw var17;
} finally {
listNode.clear();
document = null;
root = null;
// builder = null;
}
return allElementValue;
}
public void getElements (Element element) throws Exception{
try {
domCount++;
List<Element> Children = element.getChildren();
if (Children.size()>0){
for (Element elements : Children){
if(elements.getChildren().size()>0){
getElements(elements);
}else {//确定是最末节点了 开始取末节点的数据
String childName = elements.getName();
String childValue = elements.getText();
Map<String,String> childMap = new HashMap<String, String>(); //用map存储每个最终节点的值
childMap.put(childName,childValue);
allElementValue.put(domCount+elements.getParentElement().getName()+"-"+childName,childMap);
}
}
}
}catch (Exception e){
e.printStackTrace();
throw e;
}
}
public List<Map> getNodeValuesFromXmlStringForPffm(String xmlNodePath) throws Exception{
String[] nodes = xmlNodePath.split("/");
try {
xmlReader = new StringReader(xmlString);
xmlSource = new InputSource(xmlReader);
document = builder.build(xmlSource);
List<Map> maps = new ArrayList<Map>();
for(int i = 1; i < nodes.length; ++i) {
SubNode snode;
if (i >1) {
snode = (SubNode)listNode.getLast();
List<Element> eList = snode.getElement().getChildren(nodes[i]); //这里得到所有Arrival节点 从ArrivalEvent开始取
if (eList != null && eList.size() > 0) {
SubNode s1 = new SubNode((Element)eList.get(0));
listNode.add(s1);
}
if(eList != null && eList.size() > 1 && i==nodes.length-1){ //只有进入的最尾节点的时候再循环去取同名下的一对多的ELEMENT所有子节点
for (Element element : eList){ //开始取出每个ArrivalEven每个字节点
List<Element> elements=element.getChildren();
Map<String,String> childMap = new HashMap<String, String>(); //用map存储AssociatedTransportCargo节点下每个值
for (Element childElements : elements){
if (childElements.getChildren().size()>1){
for (Element grandChildrenEle : (List<Element>)childElements.getChildren()){ //IncludedMasterConsignment重复节点
String childName = grandChildrenEle.getName();
String childValue = grandChildrenEle.getText();
childMap.put(childName,childValue);
}
}
String childName = childElements.getName();
String childValue = childElements.getText();
childMap.put(childName,childValue);
logger.info(childValue);
}
maps.add(childMap);
}
}
} else if (1 == i) {
root = document.getRootElement();
snode = new SubNode(root);
listNode.add(snode);
}
}
return maps;
} catch (Exception var17) {
var17.printStackTrace();
throw var17;
} finally {
listNode.clear();
document = null;
root = null;
// builder = null;
nodes = null;
}
}
/**
* 取一对多关系的节点下的所有子节点的属性名 和 值,//这个方法作为FWB解析使用
* @return 返回重复节点下的所有节点数据
* @throws Exception
*/
public List<Map> getNodeValuesFromXmlString(String xmlNodePath) throws Exception{
String[] nodes = xmlNodePath.split("/");
try {
xmlReader = new StringReader(xmlString);
xmlSource = new InputSource(xmlReader);
document = builder.build(xmlSource);
List<Map> maps = new ArrayList<Map>();
for(int i = 1; i < nodes.length; ++i) {
SubNode snode;
if (i >1) {
snode = (SubNode)listNode.getLast();
List<Element> eList = snode.getElement().getChildren(nodes[i]); //这里等于3的时候得到associatedPary节点 两个,下面应该循环这两个element,取他下面的所有children
if (eList != null && eList.size() > 0) {
SubNode s1 = new SubNode((Element)eList.get(0));
listNode.add(s1);
}
if(eList != null && eList.size() > 1 && i==nodes.length-1){ //只有进入的最尾节点的时候再循环去取同名下的一对多的ELEMENT所有子节点
for (Element element : eList){ //开始取出每个字节点
List<Element> elements=element.getChildren();
Map<String,String> childMap = new HashMap<String, String>(); //用map存储每个值
for (Element childElements : elements){
if (childElements.getChildren().size()>1){
for (Element grandChildrenEle : (List<Element>)childElements.getChildren()){
String childName = grandChildrenEle.getName();
String childValue = grandChildrenEle.getText();
childMap.put(childName,childValue);
}
}
String childName = childElements.getName();
String childValue = childElements.getText();
childMap.put(childName,childValue);
logger.info(childValue);
}
maps.add(childMap);
}
}
} else if (1 == i) {
root = document.getRootElement();
snode = new SubNode(root);
listNode.add(snode);
}
}
return maps;
} catch (Exception var17) {
var17.printStackTrace();
throw var17;
} finally {
listNode.clear();
document = null;
root = null;
// builder = null;
nodes = null;
}
}
/***
* 获取单一节点的值
* @return 单一节点值
* @throws Exception
*/
public final String getNodeValueFromXmlString(String xmlNodePath) throws Exception {
String[] nodes = xmlNodePath.split("/");
try {
xmlReader = new StringReader(xmlString);
xmlSource = new InputSource(xmlReader);
document = builder.build(xmlSource);
for(int i = 1; i < nodes.length; ++i) {
SubNode snode;
if (i > 1) {
snode = (SubNode)listNode.getLast();
List<Element> eList = snode.getElement().getChildren(nodes[i]);
if (eList != null && eList.size() > 0) {
SubNode s1 = new SubNode((Element)eList.get(0));
listNode.add(s1);
}
} else if (1 == i) {
root = document.getRootElement();
snode = new SubNode(root);
listNode.add(snode);
}
}
SubNode n = (SubNode)listNode.getLast();
value = n.getElement().getText();
n = null;
return value;
} catch (Exception var17) {
var17.printStackTrace();
throw var17;
} finally {
listNode.clear();
document = null;
root = null;
// builder = null;
nodes = null;
}
}
public static final String getNodeAttribute(String xmlFile, String xmlNodePath, String attributeName, String defaultValue) {
String[] nodes = xmlNodePath.split("/");
new Document();
SAXBuilder builder = new SAXBuilder();
Element root = null;
LinkedList<SubNode> listNode = new LinkedList();
String value = "";
Document document;
try {
document = builder.build(xmlFile);
for(int i = 1; i < nodes.length; ++i) {
SubNode snode;
if (i > 1) {
snode = (SubNode)listNode.getLast();
List<Element> eList = snode.getElement().getChildren(nodes[i]);
if (eList != null && eList.size() > 0) {
SubNode s1 = new SubNode((Element)eList.get(0));
listNode.add(s1);
}
} else if (1 == i) {
root = document.getRootElement();
snode = new SubNode(root);
listNode.add(snode);
}
}
SubNode n = (SubNode)listNode.getLast();
value = n.getElement().getAttributeValue(attributeName, defaultValue);
n = null;
} catch (JDOMException var18) {
var18.printStackTrace();
} catch (IOException var19) {
var19.printStackTrace();
} finally {
listNode.clear();
document = null;
root = null;
builder = null;
nodes = null;
}
System.out.println("key=" + xmlNodePath + " node attrivte value=" + value);
return value;
}
}
... ...
package com.tianbo.util.XML;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Node;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class XMLXPath {
public static String getSingleValueByPath(Document document,String path){
Node node = document.selectSingleNode(path);
if (node!=null){
String nodeValue = node.getStringValue();
return nodeValue;
}else {
return null;
}
}
public static List<Node> getPathValues(Document document,String path){
List<Node> nodes= document.selectNodes(path);
return nodes;
}
public static void getPathValues2(Document document,String path){
List list = document.selectNodes(path);
for (Iterator it = list.iterator(); it.hasNext();) {
Attribute attr = (Attribute) it.next();
//TODO
}
}
}
... ...