相信设计到通讯的工程,都会需要用的通讯协议http、soap...,相信也写过很多的接口soap接口、HTTP+XML接口,每次调用我们写的接口的时候传给我们的都是个XML格式的数据信息,我们需要把这些数据解析出来,然后再拼装成一个info发出去,以下写了一个通用的方法,利用JAVA的反射机制来实现:
代码如下:
Java代码
/**
* <p>
* Copyright (C), 1988-2008, Huawei Tech. Co., Ltd.
* </p>
* <p>
* FileName: Transform.java
* </p>
* <p>
* Author:tangtao Version :1.0 Date:2010-8-31
* </p>
* <p>
* Description:
* </p>
* <p>
* Version: 1.0
* </p>
* <p>
* Function List:
* </p>
*/
package com.huawei.nvs.sys.conn.http;
import java.io.ByteArrayInputStream;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.huawei.nvs.sys.conn.http.bean.FieldInfo;
import com.huawei.nvs.sys.conn.http.bean.HttpInfo;
import com.huawei.nvs.sys.conn.http.bean.MessageInfo;
import com.huawei.nvs.sys.conn.http.bean.SendFieldInfo;
import com.huawei.nvs.sys.conn.http.conf.HttpEnv;
import com.huawei.nvs.sys.conn.http.exception.HttpException;
import com.huawei.nvs.sys.conn.http.util.ListMap;
import com.huawei.nvs.sys.conn.http.util.XmlTools;
/**
* <p>
* Title: Transform
* </p>
* <p>
* Description: HTTP消息转换类,把指定的内部实体对象转换成xml,把xml转换成指定的内部实体对象
* </p>
* <p>
* Copyright: Copyright (c) 2010-8-31
* </p>
* <p>
* Company: www.huawei.com
* </p>
*
* @author wanghui
* @version 1.0
*/
public class Transform
{
/**
* 把实体bean转换成xml字符串
*
* @param bean 实体对象
* @throws HttpException HttpException
* @return 转换成功的xml字符串
*/
public static String beanToXml(HttpInfo bean)
throws HttpException
{
if (null == bean)
{
throw new HttpException("Parameter bean is null.");
}
StringBuffer sbf = new StringBuffer("<?xml version='1.0' encoding='UTF-8'?>");
ListMap headFieldMap = new ListMap();
ListMap bodyFieldMap = new ListMap();
Class<?> c = bean.getClass();
try
{
// 获取消息类型和实体对象类路径
Field f = c.getDeclaredField("msgType");
Field v = c.getDeclaredField("version");
// 修改checkstyle 问题by wangzheng at 20101015 begin
// f.setAccessible(true);
AccessibleObject.setAccessible(new Field[] {f}, true);
AccessibleObject.setAccessible(new Field[] {v}, true);
// 修改checkstyle 问题by wangzheng at 20101015 end
String msgType = f.get(bean).toString();
String version = (String)v.get(bean);
//因为这个是发到SMC的消息,不存在多版本,所以这里默认赋值为1.0版本
version = null == version ? "smc" : version;
String path = c.getName();
Field[] fields = c.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
// 找出bean中的消息头和消息体
for (Field field : fields)
{
String fieldName = field.getName();
if (isUseField(msgType, path, fieldName, version))
{
if ("MsgType".equalsIgnoreCase(fieldName) || "Expires".equalsIgnoreCase(fieldName)
|| "callID".equalsIgnoreCase(fieldName))
{
headFieldMap.put(fieldName, field);
}
else
{
bodyFieldMap.put(fieldName, field);
}
}
}
sbf.append("<NVS_SMS_REQ>");
// 拼装消息头xml字符串
String headStr = buildHead(version, msgType, headFieldMap, bean);
// 拼装消息体xml字符串
String bodyStr = buildBody(version, msgType, bodyFieldMap, bean);
// 拼装整个xml消息字符串
sbf.append(headStr).append(bodyStr);
sbf.append("</NVS_SMS_REQ>");
}
catch (Exception e)
{
e.printStackTrace();
throw new HttpException("The xml conversion bean fail.", e);
}
return sbf.toString();
}
/**
* 把实体bean转换成xml字符串
*
* @param msgType 消息类型
* @param bean 实体对象
* @throws HttpException HttpException
* @return 转换成功的xml字符串
*/
public static String beanToXml(String msgType, Object bean)
throws HttpException
{
if (null == bean)
{
throw new HttpException("Parameter bean is null.");
}
StringBuffer sbf = new StringBuffer("");
ListMap headFieldMap = new ListMap();
ListMap bodyFieldMap = new ListMap();
Class<?> c = bean.getClass();
try
{
String path = c.getName();
String version = (String)(c.getDeclaredMethod("getVersion").invoke(bean, new Object[] {}));
Field[] fields = c.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
// 找出bean中的消息头和消息体
for (Field field : fields)
{
String fieldName = field.getName();
if (isUseField(msgType, path, fieldName, version))
{
if ("MsgType".equalsIgnoreCase(fieldName) || "Expires".equalsIgnoreCase(fieldName)
|| "callID".equalsIgnoreCase(fieldName))
{
headFieldMap.put(fieldName, field);
}
else
{
bodyFieldMap.put(fieldName, field);
}
}
}
sbf.append("<Msg_Body>");
// 拼装消息头xml字符串
String headStr = buildHead(version, msgType, headFieldMap, bean);
// 拼装消息体xml字符串
String bodyStr = buildBody(version, msgType, bodyFieldMap, bean);
// 拼装整个xml消息字符串
sbf.append(headStr).append(bodyStr);
sbf.append("</Msg_Body>");
}
catch (Exception e)
{
e.printStackTrace();
throw new HttpException("The bean conversion xml fail.", e);
}
return sbf.toString();
}
/**
* 根据传入的消息头字段拼装成xml格式字符串
*
* @param headListMap 消息头Field
* @param c 实体对象
* @return 拼装后的xml消息头字符串
* @throws IllegalAccessException 反射失败
*/
private static String buildHead(String version, String msgType, ListMap headListMap, Object c)
throws IllegalAccessException
{
// mod by wangzheng at 20100920 begin
// StringBuffer sbf = new StringBuffer("<head>");
StringBuffer sbf = new StringBuffer();
List<?> keyList = headListMap.getKeyList();
for (int i = 0; i < keyList.size(); i++)
{
String key = keyList.get(i).toString();
// 获取属性节点对应的消息节点名称
String msgFieldName = getMsgField(version, msgType, c.getClass().getName(), key);
msgFieldName = null == msgFieldName ? key : msgFieldName;
Field field = (Field)headListMap.get(key);
Object obj = field.get(c);
sbf.append("<").append(msgFieldName).append(">");
sbf.append(changeStrToXml(obj));
sbf.append("</").append(msgFieldName).append(">");
}
// sbf.append("</head>");
// mod by wangzheng at 20100920 begin
return sbf.toString();
}
/**
* 根据传入的消息体字段拼装成xml格式字符串
*
* @param bodyListMap 消息头Field
* @param c 实体对象
* @return 拼装后的xml消息体字符串
* @throws IllegalAccessException
*/
private static String buildBody(String version, String msgType, ListMap bodyListMap, Object c)
throws IllegalAccessException
{
// mod by wangzheng at 20100920 begin
// StringBuffer sbf = new StringBuffer("<body>");
StringBuffer sbf = new StringBuffer();
List<?> keyList = bodyListMap.getKeyList();
for (int i = 0; i < keyList.size(); i++)
{
String key = keyList.get(i).toString();
// 获取属性节点对应的消息节点名称
String msgFieldName = getMsgField(version, msgType, c.getClass().getName(), key);
msgFieldName = null == msgFieldName ? key : msgFieldName;
Field field = (Field)bodyListMap.get(key);
Object obj = field.get(c);
if (obj instanceof List)
{
String buildResult = Transform.buildList(version, msgType, (List<Object>)obj, msgFieldName);
sbf.append(buildResult);
}
else if (obj instanceof String[])
{
String buildResult = buildArray((String[])obj, msgFieldName);
sbf.append(buildResult);
}
else if (obj instanceof HttpInfo)
{
String buildResult = Transform.buildBean(version, msgType, obj);
sbf.append(buildResult);
}
else
{
sbf.append("<").append(msgFieldName).append(">");
sbf.append(changeStrToXml(obj));
sbf.append("</").append(msgFieldName).append(">");
}
}
// sbf.append("</body>");
// mod by wangzheng at 20100920 begin
return sbf.toString();
}
/**
* 根据传入的List消息体字段拼装成xml格式字符串
*
* @param list 消息实体对象列表
* @param listName 列表名称
* @return 拼装后的xml消息体字符串
* @throws IllegalAccessException
*/
private static String buildArray(String[] value, String listName)
throws IllegalAccessException
{
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < value.length; i++)
{
sbf.append("<").append(listName).append(">");
sbf.append(value[i]);
sbf.append("</").append(listName).append(">");
}
return sbf.toString();
}
/**
* 根据传入的List消息体字段拼装成xml格式字符串
*
* @param list 消息实体对象列表
* @param listName 列表名称
* @return 拼装后的xml消息体字符串
* @throws IllegalAccessException
*/
private static String buildList(String version, String msgType, List<Object> list, String listName)
throws IllegalAccessException
{
StringBuffer sbf = new StringBuffer();
sbf.append("<").append(listName).append(">");
for (int i = 0; i < list.size(); i++)
{
sbf.append(buildBean(version, msgType, list.get(i)));
}
sbf.append("</").append(listName).append(">");
return sbf.toString();
}
/**
* 把简单的实体对象中的属性转换成xml格式的字符串
*
* @param bean 简单的实体对象
* @return 转换后的字符串
* @throws IllegalAccessException
*/
private static String buildBean(String version, String msgType, Object bean)
throws IllegalAccessException
{
StringBuffer sbf = new StringBuffer();
Class<?> c = bean.getClass();
String path = c.getName();
//String className = path.substring(path.lastIndexOf(".") + 1, path.length());
//className = className.substring(0, className.indexOf("Info"));
String infoName = getMsgField(version, msgType, path);
infoName = null == infoName ? "" : infoName;
sbf.append("<").append(infoName).append(">");
Field[] fields = c.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (Field f : fields)
{
String fieldName = f.getName();
// 只封装在配置文件中配置过的字段
if (isUseField(msgType, path, fieldName, version))
{
// 获取属性节点对应的消息节点名称
String msgFieldName = getMsgField(version, msgType, path, fieldName);
msgFieldName = null == msgFieldName ? fieldName : msgFieldName;
Object obj = f.get(bean);
if (obj instanceof List)
{
String buildResult = Transform.buildList(version, msgType, (List)obj, msgFieldName);
sbf.append(buildResult);
}
else
{
sbf.append("<").append(msgFieldName).append(">");
Object value = f.get(bean);
sbf.append(changeStrToXml(value));
sbf.append("</").append(msgFieldName).append(">");
}
}
}
sbf.append("</").append(infoName).append(">");
return sbf.toString();
}
private static boolean isUseField(String msgID, String infoName, String fieldName, String version)
{
// 根据消息ID从内存中取出发送消息配置Map
SendFieldInfo sendMsgInfo = HttpEnv.getSendMsgMap().get(version).get(msgID);
if (null != sendMsgInfo)
{
// 根据info的详细类名称取出发送消息字段
Map<String, MessageInfo> messageMap = sendMsgInfo.getMessageMap();
if (null != messageMap)
{
// 根据info路径获取配置的info
MessageInfo msgInfo = messageMap.get(infoName);
if (null != msgInfo)
{
Map<String, FieldInfo> fieldMap = msgInfo.getFieldMap();
// 根据消息字段获取匹配的属性字段
fieldName = fieldName.toLowerCase(Locale.getDefault());
FieldInfo fieldInfo = fieldMap.get(fieldName);
if (null != fieldInfo)
{
return true;
}
}
}
}
else
{
// 如果infoMap为空说明在http_data.xml的发送节点没有配置要发送的info属性,所以默认发送info中全部属性
return true;
}
return false;
}
/**
* 根据消息ID,info类名称,消息字段获取到对应的消息字段名称
*
* @param msgID 消息ID
* @param infoName info类完整名称
* @param fieldName info属性名称
* @return info属性所对应的消息字段
*/
private static String getMsgField(String version, String msgID, String infoName, String fieldName)
{
// 根据消息ID从内存中取出发送消息配置Map
Map<String, SendFieldInfo> sendMsgInfoMap = HttpEnv.getSendMsgMap().get(version);
if (null != sendMsgInfoMap)
{
SendFieldInfo sendMsgInfo = sendMsgInfoMap.get(msgID);
if (null != sendMsgInfo)
{
// 根据info的详细类名称取出发送消息字段
Map<String, MessageInfo> messageMap = sendMsgInfo.getMessageMap();
if (null != messageMap)
{
// 根据info路径获取配置的info
MessageInfo msgInfo = messageMap.get(infoName);
if (null != msgInfo)
{
Map<String, FieldInfo> fieldMap = msgInfo.getFieldMap();
Iterator<Map.Entry<String, FieldInfo>> it = fieldMap.entrySet().iterator();
while (it.hasNext())
{
Map.Entry<String, FieldInfo> entry = it.next();
String key = entry.getKey();
FieldInfo field = entry.getValue();
if (fieldName.equalsIgnoreCase(key))
{
return field.getName();
}
}
}
}
}
}
return null;
}
/**
* 根据消息ID,info类名称,获取到对应的info别名字段名称
*
* @param msgID 消息ID
* @param infoName info类完整名称
* @param fieldName info属性名称
* @return info属性所对应的消息字段
*/
private static String getMsgField(String version, String msgID, String infoName)
{
// 根据消息ID从内存中取出发送消息配置Map
Map<String, SendFieldInfo> sendMsgInfoMap = HttpEnv.getSendMsgMap().get(version);
if (null != sendMsgInfoMap)
{
SendFieldInfo sendMsgInfo = sendMsgInfoMap.get(msgID);
if (null != sendMsgInfo)
{
// 根据info的详细类名称取出发送消息字段
Map<String, MessageInfo> messageMap = sendMsgInfo.getMessageMap();
if (null != messageMap)
{
// 根据info路径获取配置的info
MessageInfo msgInfo = messageMap.get(infoName);
if (null != msgInfo)
{
return msgInfo.getMsgField();
}
}
}
}
return null;
}
/**
* 把字符串中的特殊字符用xml指定的字符代替
*
* @param str 需要转换的字符串
* @return 转换后的字符串
*/
private static String changeStrToXml(Object str)
{
String tempStr = null == str ? "" : str.toString();
// 转换所有&为&
tempStr = tempStr.replaceAll("[&]", "&");
// 转换所有<为<
tempStr = tempStr.replaceAll("[<]", "<");
// 转换所有>为>
tempStr = tempStr.replaceAll("[>]", ">");
// 转换所有‘为'
tempStr = tempStr.replaceAll("[']", "'");
// 转换所有"为"
tempStr = tempStr.replaceAll("[\"]", """);
return tempStr;
}
/**
* 把xml中的的特殊字符用转换回原始数据
*
* @param str 需要转换的字符串
* @return 转换后的字符串
*/
private static String changeXmlToStr(Object xmlStr)
{
String tempStr = null == xmlStr ? "" : xmlStr.toString();
// 转换所有&为&
tempStr = tempStr.replaceAll("&", "&");
// 转换所有<为<
tempStr = tempStr.replaceAll("<", "<");
// 转换所有>为>
tempStr = tempStr.replaceAll(">", ">");
// 转换所有'为‘
tempStr = tempStr.replaceAll("'", "'");
// 转换所有"为"
tempStr = tempStr.replaceAll(""", "\"");
return tempStr;
}
/**
* 把xml格式的字符串信息转换成实体对象
*
* @param xml xml字符串
* @return 消息实体Bean
* @throws HttpException HttpException
*/
public static HttpInfo xmlToBean(String xml)
throws HttpException
{
return xmlToBean("smc", xml);
}
/**
* 把xml格式的字符串信息转换成实体对象
*
* @param version 消息版本
* @param xml xml字符串
* @return 消息实体Bean
* @throws HttpException HttpException
*/
public static HttpInfo xmlToBean(String version, String xml)
throws HttpException
{
if (null == xml || "".equals(xml))
{
throw new HttpException("Parameter xml is null.");
}
HttpInfo info = null;
// 删除xml声明行(第一行)
xml = deleteXmlHead(xml);
Element messageNode = null;
try
{
// 将xml字符串转化为ByteArrayInputStream
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes("UTF-8"));
// 获取head和body节点
messageNode = XmlTools.createRootElement(bis);
// Node headNode = XmlTools.getChildNode(messageNode, "head");
// Node bodyNode = XmlTools.getChildNode(messageNode, "body");
// 获取head节点和body节点的所有子节点
// List<Node> headChildList = XmlTools.getChildNodes(headNode);
List<Node> bodyChildLists = XmlTools.getChildNodes(messageNode);
// 合并headChildList和bodyChildLists
// headChildList.addAll(bodyChildLists);
// mod by wangzheng at 20100905 begin
// 获取消息类型
// Node msgTypeNode = headChildList.get(0);
// 获取消息类型
// Node msgTypeNode = XmlTools.getChildNode(headNode, "msgType");
Node msgTypeNode = XmlTools.getChildNode(messageNode, "MSG_TYPE");
String msgType = XmlTools.getNodeValue(msgTypeNode);
// mod by wangzheng at 20100905 end
// 根据消息类型取出配置的相应info并生成对象
MessageInfo msgInfo = HttpEnv.getMsgMap().get(version).get(msgType);
// 根据配置信息生成Info
info = (HttpInfo)createInfo(msgInfo, bodyChildLists);
}
catch (HttpException e)
{
e.printStackTrace();
throw e;
}
catch (Exception e)
{
e.printStackTrace();
throw new HttpException("The bean conversion xml fail.", e);
}
finally
{
messageNode = null;
}
return info;
}
// add by wangzheng at 20100920 begin
/**
* 把xml格式的字符串信息转换成实体对象--没有head及body
*
* @param xml xml字符串
* @return 消息实体Bean
* @throws HttpException HttpException
*/
public static HttpInfo xmlToBeanNoHead(String xml)
throws HttpException
{
if (null == xml || "".equals(xml))
{
throw new HttpException("Parameter xml is null.");
}
HttpInfo info = null;
// 删除xml声明行(第一行)
xml = deleteXmlHead(xml);
Element messageNode = null;
try
{
// 将xml字符串转化为ByteArrayInputStream
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes("UTF-8"));
// 获取head和body节点
messageNode = XmlTools.createRootElement(bis);
// 获取head节点和body节点的所有子节点
List<Node> headChildList = XmlTools.getChildNodes(messageNode);
// 获取消息类型
Node msgTypeNode = XmlTools.getChildNode(messageNode, "MSG_TYPE");
String msgType = XmlTools.getNodeValue(msgTypeNode);
// 根据消息类型取出配置的相应info并生成对象
MessageInfo msgInfo = HttpEnv.getMsgMap().get("").get(msgType);
// 根据配置信息生成Info
info = (HttpInfo)createInfo(msgInfo, headChildList);
}
catch (HttpException e)
{
e.printStackTrace();
throw e;
}
catch (Exception e)
{
e.printStackTrace();
throw new HttpException("The bean conversion xml fail.", e);
}
finally
{
messageNode = null;
}
return info;
}
/**
* 把xml格式的字符串信息转换成实体对象--没有head及body
*
* @param xml xml字符串
* @param msgType 消息类型
* @param version 消息版本
* @return 消息实体Bean
* @throws HttpException HttpException
*/
public static Object xmlToBeanNoHead(String msgType, String version, String xml)
throws HttpException
{
if (null == xml || "".equals(xml))
{
throw new HttpException("Parameter xml is null.");
}
Object info = null;
// 删除xml声明行(第一行)
xml = deleteXmlHead(xml);
Element messageNode = null;
try
{
// 将xml字符串转化为ByteArrayInputStream
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes("UTF-8"));
// 获取head和body节点
messageNode = XmlTools.createRootElement(bis);
// 获取head节点和body节点的所有子节点
List<Node> headChildList = XmlTools.getChildNodes(messageNode);
// 根据消息类型取出配置的相应info并生成对象
MessageInfo msgInfo = HttpEnv.getMsgMap().get(version).get(msgType);
// 根据配置信息生成Info
info = createInfo(msgInfo, headChildList);
}
catch (HttpException e)
{
e.printStackTrace();
throw e;
}
catch (Exception e)
{
e.printStackTrace();
throw new HttpException("The bean conversion xml fail.", e);
}
finally
{
messageNode = null;
}
return info;
}
// add by wangzheng at 20100920 end
/**
* 根据xml节点创建指定的实体Bean
*
* @param msgInfo 实体bean
* @param nodeList xml节点列表
* @throws HttpException
*/
private static Object createInfo(MessageInfo msgInfo, List<Node> nodeList)
throws HttpException
{
// 获取出messageInfo的属性
String path = msgInfo.getPath();
Map<String, FieldInfo> fieldMap = msgInfo.getFieldMap();
Object obj = null;
try
{
// 根据类路径生成对象
obj = Class.forName(path).newInstance();
for (Node node : nodeList)
{
// 获取消息节点名称及节点值
String nodeName = node.getNodeName().toLowerCase(Locale.getDefault());
Object nodeValue = XmlTools.getValue(node);
// 根据节点名称找到Field
FieldInfo field = fieldMap.get(nodeName);
if (null != field)
{
String type = field.getType();
if ("java.util.List".equalsIgnoreCase(type))
{
List<Object> list = new ArrayList<Object>();
MessageInfo subInfo = field.getChildInfo();
// 获取节点下所有子节点
List<Node> subInfoList = XmlTools.getChildNodes(node);
for (Node subInfoNode : subInfoList)
{
List<Node> subNodeList = XmlTools.getChildNodes(subInfoNode);
Object info = createInfo(subInfo, subNodeList);
list.add(info);
}
// Node subInfoNode = XmlTools.getChildNodes(node).get(0);
nodeValue = list;
}
//mod by wangzheng at 20110329 begin
//若类型为HTTPInfo的子类,则进行取info操作,达不到预期效果,估计需要修改加载内存中结构信息
else if (Class.forName("com.huawei.nvs.sys.conn.http.bean.HttpInfo")
.isAssignableFrom(Class.forName(type)))
{
Object info = null;
//MessageInfo subInfo = field.getChildInfo();
MessageInfo subInfo = msgInfo;
// 获取节点下所有子节点
List<Node> subInfoList = XmlTools.getChildNodes(node);
if (subInfoList.size() > 0)
{
List<Node> subNodeList = XmlTools.getChildNodes(subInfoList.get(0));
if (null == subNodeList || 0 == subNodeList.size())
{
subNodeList = subInfoList;
}
info = createInfo(subInfo, subNodeList);
}
nodeValue = info;
}
// else if ("com.huawei.nvs.sys.conn.http.bean.HttpInfo".equalsIgnoreCase(type))
// {
// Object info = null;
// MessageInfo subInfo = field.getChildInfo();
// // 获取节点下所有子节点
// List<Node> subInfoList = XmlTools.getChildNodes(node);
// if (subInfoList.size() > 0)
// {
// List<Node> subNodeList = XmlTools.getChildNodes(subInfoList.get(0));
// info = createInfo(subInfo, subNodeList);
// }
// nodeValue = info;
// }
//mod by wangzheng at 20110329 end
String name = field.getName();
Object defaultValue = field.getDefaultValue();
String checkRegular = field.getCheckRegular();
// 如果默认值为null那么根据数据类型获取默认值
if (null == defaultValue || "".equals(defaultValue))
{
defaultValue = getDefaultValue(type);
}
// 如果节点值为null的话就给节点赋默认值
nodeValue = null == nodeValue ? defaultValue : nodeValue;
nodeValue = nodeValue instanceof java.util.List ? nodeValue : changeXmlToStr(nodeValue);
// 正则表达式校验
if (null != checkRegular && !"".equals(checkRegular))
{
if (!check(nodeValue, checkRegular))
{
StringBuffer sbf = new StringBuffer("The field value is illegal.");
sbf.append(nodeName).append("=[").append(nodeValue).append("].");
sbf.append("regex=[").append(checkRegular).append("]");
throw new HttpException(sbf.toString());
}
}
// 设置info属性值
setInfoAttValue(obj, name, type, nodeValue);
}
}
}
catch (HttpException e)
{
throw e;
}
catch (Exception e)
{
e.printStackTrace();
throw new HttpException("The bean conversion xml fail.", e);
}
return obj;
}
private static String deleteXmlHead(String msg)
{
int startIndex = msg.indexOf("<Message>");
if (startIndex > -1)
{
msg = msg.substring(startIndex, msg.length());
}
return msg;
}
/**
* 根据传入的正则表达式验证传入的字符串是否合法
*
* @param str 需要校验的字符串
* @param regex 正则表达式
* @return booean true:合法false:不合法
*/
private static boolean check(Object str, String regex)
{
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str.toString());
return matcher.matches();
}
/**
* 设置指定info中的指定属性值
*
* @param obj 实体bean
* @param name 属性名称
* @param type 属性取值类型
* @param value 要设置的属性值
* @throws IllegalAccessException
*/
private static void setInfoAttValue(Object obj, String name, String type, Object value)
throws IllegalAccessException
{
Class<?> cls = obj.getClass();
// 获取info中所有属性
Field[] fields = cls.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
// 找到匹配的属性并赋值
for (Field field : fields)
{
if (field.getName().equalsIgnoreCase(name))
{
if (type.equalsIgnoreCase("java.lang.String") || type.equalsIgnoreCase("String"))
{
field.set(obj, value);
}
else if (type.equalsIgnoreCase("java.util.List"))
{
field.set(obj, value);
}
else if (type.equalsIgnoreCase("java.lang.Integer") || type.equalsIgnoreCase("int"))
{
field.setInt(obj, Integer.parseInt((String)value));
}
else if (type.equalsIgnoreCase("java.lang.Double") || type.equalsIgnoreCase("double"))
{
field.setDouble(obj, Double.parseDouble((String)value));
}
else if (type.equalsIgnoreCase("java.lang.Long") || type.equalsIgnoreCase("long"))
{
field.setLong(obj, Long.parseLong((String)value));
}
else if (type.equalsIgnoreCase("java.lang.Float") || type.equalsIgnoreCase("float"))
{
field.setFloat(obj, Float.parseFloat((String)value));
}
else if (type.equalsIgnoreCase("java.lang.Boolean") || type.equalsIgnoreCase("boolean"))
{
field.setBoolean(obj, Boolean.parseBoolean((String)value));
}
else if (type.equalsIgnoreCase("java.lang.Character") || type.equalsIgnoreCase("char"))
{
char c = null == value ? ' ' : ((String)value).toCharArray()[0];
field.setChar(obj, c);
}
else if (type.equalsIgnoreCase("java.lang.Short") || type.equalsIgnoreCase("Short"))
{
field.setShort(obj, Short.parseShort((String)value));
}
else if (type.equalsIgnoreCase("com.huawei.nvs.sys.conn.http.bean.HttpInfo")
|| type.equalsIgnoreCase("HttpInfo"))
{
field.set(obj, value);
}
break;
}
}
}
private static Object getDefaultValue(String type)
{
Object obj = null;
if (type.equalsIgnoreCase("java.lang.Integer") || type.equalsIgnoreCase("int"))
{
obj = Integer.valueOf(0);
}
else if (type.equalsIgnoreCase("java.lang.Double") || type.equalsIgnoreCase("double"))
{
obj = Double.valueOf(0.0);
}
else if (type.equalsIgnoreCase("java.lang.Long") || type.equalsIgnoreCase("long"))
{
obj = Long.valueOf(0L);
}
else if (type.equalsIgnoreCase("java.lang.Float") || type.equalsIgnoreCase("float"))
{
obj = Float.valueOf(0F);
}
else if (type.equalsIgnoreCase("java.lang.Boolean") || type.equalsIgnoreCase("boolean"))
{
obj = Boolean.valueOf(false);
}
else if (type.equalsIgnoreCase("java.lang.Character") || type.equalsIgnoreCase("char"))
{
obj = null;
}
else if (type.equalsIgnoreCase("java.lang.Short") || type.equalsIgnoreCase("Short"))
{
obj = Short.valueOf("0");
}
else if (type.equalsIgnoreCase("java.lang.String") || type.equalsIgnoreCase("String"))
{
obj = null;
}
return obj;
}
}