版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010741376/article/details/54406399
webservice接口发布:代码如下:
发布接口:
package com.iris.innocity2.nsoweb.service.ws.syncUser;
import javax.jws.WebService;
@WebService(serviceName="syncUserWsService",targetNamespace="http://ws.server.iris.com")
public interface SyncUserWsService {
public String syncUser(String sysCode,String paramXml) throws Exception;
}
接口实现类:
package com.iris.innocity2.nsoweb.service.ws.syncUser;
import java.util.LinkedHashMap;
import javax.jws.WebService;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.iris.innocity2.nsoweb.constants.IncWsConstants;
import com.iris.innocity2.nsoweb.model.register.PsnRegister;
import com.iris.innocity2.nsoweb.model.register.PsnRegisterForm;
import com.iris.innocity2.nsoweb.service.person.PersonService;
import com.iris.innocity2.nsoweb.service.register.PsnRegisterService;
import com.iris.innocity2.nsoweb.service.system.AuthLoginService;
import com.iris.innocity2.nsoweb.ws.utils.WsXmlDocument;
@WebService(serviceName="syncUserWsService",portName="syncUserWsServicePort",targetNamespace="http://ws.server.iris.com",endpointInterface="com.iris.innocity2.nsoweb.service.ws.syncUser.SyncUserWsService")
public class SyncUserWsServiceImpl implements SyncUserWsService {
protected final Logger logger=LoggerFactory.getLogger(getClass());
@Autowired
private PersonService personService;
@Autowired
private AuthLoginService authLoginService;
@Autowired
private PsnRegisterService psnRegisterService;
@SuppressWarnings("unused")
@Override
public String syncUser(String sysCode, String paramXml) throws Exception {
String resultXml = null;
String msg=null;
LinkedHashMap<String, String> dataMap=new LinkedHashMap<String, String>();
String incPsnId=null;
//参数效验
if (isMatchSysCode(sysCode)==false){
msg="sysCode非法";
}else if(StringUtils.isBlank(paramXml)){
msg="paramXml不能为空";
}else{
PsnRegister psnRegister=updateJxttUserInfo(paramXml);
if(psnRegister.getPsnId()>0){
incPsnId=psnRegister.getPsnId().toString();
}
}
//根据msg返回结果xml信息
WsXmlDocument wsXmlDocument = new WsXmlDocument("<?xml version=\"1.0\" encoding=\"UTF-8\"?><data></data>");
if(msg!=null)
{
dataMap.put("msg",msg);
dataMap.put("result", "error");
}else{
dataMap.put("result", "success");
dataMap.put("incPsnId",incPsnId);
}
logger.info("syncUser请求参数:"+dataMap.toString());
return wsXmlDocument.createPrimaryNode(dataMap);
}
/**
* 检查系统标示是否符合约定.
*
* @param sysCode
* @return
*/
private boolean isMatchSysCode(String sysCode) {
return (StringUtils.isNotBlank(sysCode) && StringUtils.equalsIgnoreCase(IncWsConstants.JXTT_SYS_CODE,sysCode));
}
public PsnRegister updateJxttUserInfo(String paramXml) throws Exception{
WsXmlDocument wsXmlDocument = new WsXmlDocument(paramXml);
Element rootEle = (Element) wsXmlDocument.getRootNode("/params");
PsnRegisterForm psnRegisterForm=new PsnRegisterForm();
PsnRegister psnRegister=new PsnRegister();
if (rootEle != null) {
//提取参数
if(rootEle.elementTextTrim("psnId")!=null){
psnRegisterForm.setScmPsnId(rootEle.elementTextTrim("psnId"));
}
if(rootEle.elementTextTrim("firstName")!=null){
psnRegisterForm.setFirstName(rootEle.elementTextTrim("firstName"));
}
if(rootEle.elementTextTrim("lastName")!=null){
psnRegisterForm.setLastName(rootEle.elementTextTrim("lastName"));
}
if(rootEle.elementTextTrim("name")!=null){
psnRegisterForm.setName(rootEle.elementTextTrim("name"));
}
if(rootEle.elementTextTrim("ename")!=null){
psnRegisterForm.setEname(rootEle.elementTextTrim("ename"));
}
if(rootEle.elementTextTrim("email")!=null){
psnRegisterForm.setEmail(rootEle.elementTextTrim("email"));
}
if(rootEle.elementTextTrim("position")!=null){
psnRegisterForm.setPosition(rootEle.elementTextTrim("position"));
}
if(rootEle.elementTextTrim("insName")!=null){
psnRegisterForm.setInsName(rootEle.elementTextTrim("insName"));
}
if(rootEle.elementTextTrim("avatars")!=null){
psnRegisterForm.setAvatars(rootEle.elementTextTrim("avatars"));
}
psnRegisterForm.setIsApply(0);
psnRegisterForm.setType("scm");
psnRegister=psnRegisterService.create(psnRegisterForm);
logger.info("*************updateJxttUserInfo成功");
}
return psnRegister;
}
}
配置文件:applicationContext-jaxws.xml:
<bean id="syncUserWsService" class="com.iris.innocity2.nsoweb.service.ws.syncUser.SyncUserWsServiceImpl" />
解析dom工具类:
package com.iris.innocity2.nsoweb.ws.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
/**
* <data> <interface> <method> <arg0></arg0>
* <arg1></arg1> ...... </method> </interface> </data>
*
*
*/
public class WsXmlDocument {
public static final String XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
public static final String WS_RESULT_PATH = "/result";
public static final String WS_DATA_PATH = "/data";
public static final String WS_PARAM_PATH = "/params";
public static final String WS_INTERFACE_PATH = "/interface";
public static final String WS_INTERFACE_METHOD_PATH = "/interface/method";
public static final String WS_ERROR_MSG_NODE = "/error_msg";
public static final String WS_RESULT_TOTAL_COUNT = "total_count";
/**
*
*/
private Document xmlDocument = null;
/**
* 1、构造返回类型doc;2、构造参数doc.
*
* @param type
* @throws DocumentException
*/
public WsXmlDocument(int type) throws DocumentException {
StringBuilder xml = new StringBuilder();
xml.append(WsXmlDocument.XML_DECL);
// 根据类型定义根节点.
if (type == 2) {
xml.append("<data><interface><method></method></interface></data>");
} else if (type == 3) {
xml.append("<data></data>");
} else {
xml.append("<result></result>");
}
xmlDocument = DocumentHelper.parseText(xml.toString());
}
public WsXmlDocument(String xmlData) throws DocumentException {
xmlDocument = DocumentHelper.parseText(xmlData);
}
public WsXmlDocument(Document doc) throws DocumentException {
xmlDocument = doc;
}
/**
* 增加无参构造器(不初始化根节点).
*
* @throws DocumentException
*/
public WsXmlDocument() throws DocumentException {
StringBuilder xml = new StringBuilder();
xml.append(WsXmlDocument.XML_DECL);
xmlDocument = DocumentHelper.parseText(xml.toString());
}
/**
* 获取接口节点.
*
* @return Node
*/
public Node getWsInterface() {
return this.getNode(WsXmlDocument.WS_INTERFACE_PATH);
}
/**
* 获取接口方法节点.
*
* @return Node
*/
public Node getWsInterfaceMethod() {
return this.getNode(WsXmlDocument.WS_INTERFACE_METHOD_PATH);
}
@SuppressWarnings("unchecked")
public List<Element> getMethodElementChildren() {
Element methodElement = (Element) this.getWsInterfaceMethod();
if (methodElement == null) {
throw new java.lang.NullPointerException("/data/interface/method is null.");
}
return methodElement.elements();
}
@SuppressWarnings("unchecked")
public List<String> getMethodParams() throws Exception {
List<String> valList = new ArrayList<String>();
Element methodElement = (Element) this.getWsInterfaceMethod();
List<Element> list = methodElement.elements();
if (CollectionUtils.isNotEmpty(list)) {
for (Element element : list) {
valList.add(element.getStringValue());
}
}
return valList;
}
/**
* 获取根节点.
*
* @return Node
*/
public Node getRootNode(String rootPath) {
return this.xmlDocument.selectSingleNode(rootPath);
}
/**
* @param xpath
* Xml元素路径
* @return List
*/
@SuppressWarnings("rawtypes")
public List getNodes(String rootPath, String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
if (!xpath.startsWith(rootPath))
xpath = rootPath + xpath;
return this.xmlDocument.selectNodes(xpath);
}
@SuppressWarnings("unchecked")
public List<Node> getResultNodes(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
return this.xmlDocument.selectNodes(WsXmlDocument.WS_RESULT_PATH + xpath);
}
/**
* @param fullPath
* xml元素路径
* @return String
* @throws InvalidXpathException
* InvalidXpathException
*/
public String getXmlNodeAttribute(String fullPath) throws InvalidXpathException {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
int pos = fullPath.indexOf("@");
if (pos == -1) {
throw new InvalidXpathException(fullPath);
}
String attrName = fullPath.substring(pos + 1);
String xpath = fullPath.substring(0, pos - 1);
Node node = this.getNode(xpath);
if (node != null) {
String val = node.valueOf("@" + attrName);
val = org.apache.commons.lang.StringUtils.stripToEmpty(val);
return val;
}
return "";
}
/**
* @param nodepath
* xml元素路径
* @param attrName
* xml属性名
* @param newValue
* xml属性新值
*/
public void setXmlNodeAttribute(String nodepath, String attrName, String newValue) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
if (attrName.startsWith("@")) {
attrName = attrName.substring(1);
}
Element ele = (Element) this.getNode(nodepath);
if (ele == null) {
return;
}
if (ele != null) {
ele.addAttribute(attrName, newValue);
}
}
/**
* @param xpath
* xml元素路径
* @return Node
*/
public Node getNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
if (!xpath.startsWith(WsXmlDocument.WS_DATA_PATH))
xpath = WsXmlDocument.WS_DATA_PATH + xpath;
return this.xmlDocument.selectSingleNode(xpath);
}
public Node getResultNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
return this.xmlDocument.selectSingleNode(xpath);
}
public void createMethodParamNode(Map<String, Object> map) {
if (MapUtils.isNotEmpty(map)) {
Element methodElement = (Element) this.getWsInterfaceMethod();
for (Map.Entry<String, Object> entry : map.entrySet()) {
methodElement.addElement(entry.getKey()).setText(ObjectUtils.toString(entry.getValue(), ""));
}
}
}
/**
*
* @param parentNode
* @param map
*/
public void createNode(Node parentNode, Map<String, String> map) {
if (parentNode != null && MapUtils.isNotEmpty(map)) {
Element parentElement = (Element) parentNode;
String value = "";
for (Map.Entry<String, String> entry : map.entrySet()) {
value = entry.getValue() == null ? "" : entry.getValue();
this.createElement(parentElement, entry.getKey()).setText(value);
}
}
}
/**
* 创建返回节点.
*
* @param resultType
* 1、成功; 2、缺少必要参数;3、未关联人员;4、远程调用同步出错
* @param errorMsg
* @return
*/
public String createResultData(int resultType, Map<String, String> map) {
Node node = this.xmlDocument.selectSingleNode(WsXmlDocument.WS_RESULT_PATH);
Element element = (Element) node;
element.addAttribute("value", resultType + "");
if (resultType == 1) {
element = element.addElement("data");
}
this.createNode(element, map);
return this.xmlDocument.asXML();
}
/**
* 创建根节点下的一级节点(有序排列).
*
* @param nodeName
* @param map
* @return
*/
@SuppressWarnings("rawtypes")
public String createPrimaryNode(LinkedHashMap<String, String> map) {
Element rootEle = xmlDocument.getRootElement();
if (map != null && map.size() > 0) {
Set<String> set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
String value = map.get(key);
rootEle.addElement(key);
rootEle.element(key).setText(value);
}
}
return this.xmlDocument.asXML();
}
/**
* 创建根节点的二级子节点,parentNodeName必须是根节点的一级子节点(即在一级子节点下增加多个相同名称的二级子节点).
*
* @param parentNodeName
* 一级子节点名称(已存在).
* @param subNodeName
* 二级子节点名称(需增加).
* @param dataList
* 子节点值列表.
*/
public void createSubNodeWithPath(String parentNodePath,
String subNodeName, List<?> dataList) {
if (StringUtils.isNotBlank(parentNodePath)
&& StringUtils.isNotBlank(subNodeName)
&& CollectionUtils.isNotEmpty(dataList)) {
Node node = this.getNode(parentNodePath);
Element currEle = (Element) node;
if (currEle != null) {
for (int i = 0; i < dataList.size(); i++) {
String value = ObjectUtils.toString(dataList.get(i));
currEle.addElement(subNodeName).setText(value);
}
}
}
}
/**
* 创建根节点的二级子节点,包含多个子节点属性(即在一级子节点下增加多个相同名称的二级子节点).
*
* @param parentNodeName
* 一级子节点名称(已存在).
* @param subNodeName
* 二级子节点名称(需增加).
* @param dataList
* 子节点值列表.
*/
@SuppressWarnings("rawtypes")
public void createSubNodeWithPath(String parentNodePath,
LinkedHashMap<String, String> map) {
if (StringUtils.isNotBlank(parentNodePath) && map != null
&& map.size() > 0) {
Node node = this.getNode(parentNodePath);
Element currEle = (Element) node;
Set<String> set = map.keySet();
if (currEle != null) {
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
String value = (StringUtils.isNotBlank(map.get(key)) ? map
.get(key) : "");
currEle.addElement(key).setText(value);
}
}
}
}
/**
* 创建根节点的二级子节点,包含多个子节点属性(即在一级子节点下增加多个相同名称的二级子节点).
*
* @param parentNodeName
* 一级子节点名称(已存在).
* @param subNodeName
* 二级子节点名称(需增加).
* @param dataList
* 子节点值列表.
*/
@SuppressWarnings("rawtypes")
public void createSubNodeAttribute(String parentNodePath,
String subNodeName, LinkedHashMap<String, String> map) {
if (StringUtils.isNotBlank(parentNodePath)
&& StringUtils.isNotBlank(subNodeName) && map != null
&& map.size() > 0) {
Node node = this.getNode(parentNodePath);
Element parentElement = (Element) node;
Set<String> set = map.keySet();
if (parentElement != null) {
Element currEle = parentElement.addElement(subNodeName);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
String value = map.get(key);
currEle.addAttribute(key, value);
}
}
}
}
public String getMethodParamVal(String xpath) {
Node node = this.getNode(WsXmlDocument.WS_DATA_PATH + WsXmlDocument.WS_INTERFACE_METHOD_PATH + xpath);
if (node != null) {
return node.getStringValue();
}
return null;
}
public String getResultParamVal(String xpath) {
Node node = this.getResultNode(WsXmlDocument.WS_RESULT_PATH + WsXmlDocument.WS_DATA_PATH + xpath);
if (node != null) {
return node.getStringValue();
}
return null;
}
/**
* @param xpath
* xml元素路径
* @param attrName
* xml属性名
* @return String
*/
public String getXmlNodeAttribute(String xpath, String attrName) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
if (node != null) {
return getXmlNodeAttributeValue(node, attrName);
}
return "";
}
/**
* @param node
* xml节点
* @param attrName
* xml属性名
* @return String
*/
public String getXmlNodeAttributeValue(Node node, String attrName) {
if (node == null) {
return "";
}
String val = node.valueOf("@" + attrName);
if (val == null) {
val = "";
}
return val.trim();
}
/**
* @param xpath
* xml元素路径
* @return boolean
*/
public boolean existsNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
return node != null;
}
/**
* @param xpath
* xml元素路径
* @param attrName
* xml属性
* @return boolean
*/
public boolean existsNodeAttribute(String xpath, String attrName) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
if (node == null) {
return false;
}
Element ele = (Element) node;
Attribute attr = ele.attribute(attrName);
return attr != null;
}
/**
* @param xpath
* xml元素路径
*/
public void removeNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
if (node != null) {
boolean result = this.xmlDocument.remove(node);
if (!result) {
node.detach();
}
}
}
public String getXmlString() {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
String xml = this.xmlDocument.asXML();
return xml;
}
public Document getXmlDocument() {
return xmlDocument;
}
/**
* @param elePath
* xml元素路径 (e.g. /publication, /pub_members/pub_member[01],
* /pub_members, )
* @return Element
*/
public Element createElement(Element rootNode, String elePath) {
if (XmlUtils.isEmpty(elePath)) {
throw new java.lang.NullPointerException("can't create Element with NULL (elePath).");
}
elePath = elePath.toLowerCase();
String[] paths = XmlUtils.splitXPath(elePath); // 分割元素和元素的属性
String[] segs = paths[0].split("/"); // will return ['/','persons']
// or
// ['/','persons','person[1]','psn_id']
Element parentEle = (Element) rootNode.selectSingleNode(segs[1]);
if (parentEle == null) {
parentEle = rootNode.addElement(segs[1]);
}
// 只支持2级节点
if (segs.length > 2) {
String name = segs[2];
int pos = name.indexOf("[");
Integer seqNo = null;
if (pos > 0) {// 获取序号
String tmp = name.substring(pos + 1, name.length() - 1);
seqNo = Integer.parseInt(tmp);
}
// 删除序号
name = name.replaceAll("\\[.*\\]", "");
String selectedPath = segs[2];
Element ele = null;
if (seqNo != null) {
Element childEle = null;
// 页面提交的数据顺序是不确定的,因此如果前面序号的节点后到,则提前创建,防止页面获取XML数据乱序
for (int i = 1; i <= seqNo; i++) {
selectedPath = name + "[@seq_no=" + String.valueOf(i) + "]";
ele = (Element) parentEle.selectSingleNode(selectedPath); // segs[2]如:pub_member[01]
if (ele == null) {
ele = parentEle.addElement(name);
ele.addAttribute("seq_no", String.valueOf(i));
}
if (segs.length > 3) {
childEle = (Element) ele.selectSingleNode(segs[3]);
if (childEle == null) {
childEle = ele.addElement(segs[3]);
}
ele = childEle;
}
}
} else {
ele = (Element) parentEle.selectSingleNode(selectedPath);
if (ele == null) {
ele = parentEle.addElement(name);
}
}
return ele;
}
return parentEle;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static final void main(String[] args) {
LinkedHashMap<String, String> orderMap = new LinkedHashMap<String, String>();
orderMap.put("system_code", "sfms");
orderMap.put("result_type", "1");
orderMap.put("order_codes", "");
orderMap.put("err_msg", "");
List dataList = new ArrayList();
dataList.add("1");
dataList.add("2");
dataList.add("3");
dataList.add("4");
try {
WsXmlDocument doc = new WsXmlDocument(3);
System.out.println(doc.createPrimaryNode(orderMap));
System.out.println(doc.getXmlString());
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端调用
定义调用接口:
package com.iris.nsonline.nsoweb.service.ws.innocity;
import javax.jws.WebService;
/**
* 类说明:同步用户信息
*/
@WebService(serviceName = "syncUserWsService", targetNamespace = "http://ws.server.iris.com", endpointInterface = "com.iris.nsonline.nsoweb.service.ws.innocity.SyncUserWsService")
public interface SyncUserWsService {
public String syncUser(String sysCode,String paramXml) throws Exception;
}
Action进行调用:
package com.iris.nsonline.nsoweb.web.struts2.login;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.iris.nsonline.nsoweb.model.person.Person;
import com.iris.nsonline.nsoweb.model.person.PsnForm;
import com.iris.nsonline.nsoweb.security.utils.SecurityUtils;
import com.iris.nsonline.nsoweb.service.person.PersonService;
import com.iris.nsonline.nsoweb.service.person.ScmRelationAccountService;
import com.iris.nsonline.nsoweb.service.ws.innocity.SyncUserWsService;
import com.iris.nsonline.nsoweb.ws.utils.WsXmlDocument;
import com.iris.struts2.utils.Struts2Utils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
public class RelateAccountAction extends ActionSupport implements Preparable, ModelDriven<PsnForm>{
/**
*
*/
private static final long serialVersionUID = 7506884913405793653L;
protected final Logger logger = LoggerFactory.getLogger(getClass());
private PsnForm form;
@Autowired
private ScmRelationAccountService scmRelationAccountService;
@Value("${scm_relation_login_token}")
private String relationToken;
@Autowired
private SyncUserWsService syncUserWsService;
@Autowired
private PersonService personService;
@Action("/relation/scm/enterAjaxSaveAccountRelation")
public String enterAjaxSaveAccountRelation(){
Map<String, String> map = new HashMap<String, String>(2);
try {
Map<String, String> data = new HashMap<String, String>();
Long userId = SecurityUtils.getCurrentUserId();
if (userId!= null &&userId != 0L) {
form.setPsnId(userId);
form.setToken(this.relationToken);
// 去OpenUserUnionDemo查找记录,看是否有关联关系
Long openId = scmRelationAccountService.getOpenUserUnionByIdAndToken(userId,this.relationToken);
if (openId != null) {
if(syncUser(userId)){
map.put("result", "redirect");
}
Struts2Utils.renderJson(map, "encoding:UTF-8");
} else {
// 如果没关联,构建url跳到账号关联页面
String url = scmRelationAccountService.buildConnectionURL(form, form.getToken());
if (StringUtils.isNotBlank(url)) {
map.put("result", "success");
map.put("targetUrl", url);
Struts2Utils.renderJson(map, "encoding:UTF-8");
} else {
// url为空,说明生成URL失败,提示失败信息
data.put("result", "error");
data.put("errorMsg", "获取生成的URL为空");
Struts2Utils.renderJson(data, "encoding:UTF-8");
}
}
} else {
data.put("result", "error");
data.put("errorMsg", "人员ID为空");
Struts2Utils.renderJson(data, "encoding:UTF-8");
}
} catch (Exception e) {
logger.error("互联互通------跳转到账号关联页面失败", e);
}
return null;
}
@Action("/relation/scm/ajaxSaveAccountRelation")
public String ajaxSaveAccountRelation(){
try {
// 第三方系统获取当前登录的psnId
Map<String, String> map = new HashMap<String, String>(2);
Long userId = SecurityUtils.getCurrentUserId();
try {
if(userId>0){
form.setPsnId(userId);
form.setToken(this.relationToken);
if (form.getOpenId() != null && !form.getOpenId().equals(0L)&&scmRelationAccountService.checkSignatureRelation(form)) {
scmRelationAccountService.saveAccountRelation(form);
Struts2Utils.getSession().setAttribute("openId", form.getOpenId());//将openId存入session中
if(syncUser( userId)){
map.put("result", "success");
}
}
Struts2Utils.renderJson(map, "encoding:UTF-8");
}
} catch (Exception e) {
logger.error("模拟第三方系统保存关联关系出错", e);
map.put("result", "error");
Struts2Utils.renderJson(map, "encoding:UTF-8");
}
} catch (Exception e) {
logger.error("模拟第三方系统保存关联关系出错", e);
}
return null;
}
@Override
public PsnForm getModel() {
return form;
}
@Override
public void prepare() throws Exception {
if (form == null) {
form = new PsnForm();
}
}
public Boolean syncUser(Long userId) throws Exception{
Person person=personService.getPersonByPsnId(userId);
WsXmlDocument wsXmlDocument = new WsXmlDocument("<?xml version=\"1.0\" encoding=\"UTF-8\"?><params></params>");
LinkedHashMap<String, String> dataMap=new LinkedHashMap<String, String>();
dataMap.put("psnId", person.getPsnId().toString());
if(StringUtils.isNotEmpty(person.getFirstName())){
dataMap.put("firstName", person.getFirstName());
}
if(StringUtils.isNotEmpty(person.getLastName())){
dataMap.put("lastName", person.getLastName());
}
if(StringUtils.isNotEmpty(person.getName())){
dataMap.put("name", person.getName());
}
if(StringUtils.isNotEmpty(person.getEname())){
dataMap.put("ename", person.getEname());
}
if(StringUtils.isNotEmpty(person.getEmail())){
dataMap.put("email", person.getEmail());
}
if(StringUtils.isNotEmpty(person.getPosition())){
dataMap.put("position", person.getPosition());
}
if(StringUtils.isNotEmpty(person.getInsName())){
dataMap.put("insName", person.getInsName());
}
if(StringUtils.isNotEmpty(person.getAvatars())){
dataMap.put("avatars", person.getAvatars());
}
String xmlResult=syncUserWsService.syncUser("jxtt", wsXmlDocument.createPrimaryNode(dataMap));
//读取解析paramXml
wsXmlDocument = new WsXmlDocument(xmlResult);
//Element rootEle=(Element)xmlDocument.selectSingleNode(WsXmlDocument.WS_PARAM_PATH);
Element rootEle = (Element) wsXmlDocument.getRootNode("/data");
if (rootEle != null) {
//提取参数
String result=rootEle.elementTextTrim("result");
String incPsnId=rootEle.elementTextTrim("insPsnId");
//只有incPsnId或者scmPsnId有一个不为空
if (StringUtils.isNotBlank(result)) {
if(result.equals("success")){
person.setIncPsnId(Long.valueOf(incPsnId));
personService.save(person);
return true;
}
}
}
return false;
}
}
配置文件
applicationContext-jaxws.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<description>Spring公共配置文件</description>
<bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter">
<property name="baseAddress" value="${webserviceurl}/" />
</bean>
<bean id="syncUserWsService" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
<property name="serviceInterface" value="com.iris.nsonline.nsoweb.service.ws.innocity.SyncUserWsService" />
<property name="wsdlDocumentUrl" value="${inc.client.incSysUser.wsdlurl}" />
<property name="namespaceUri" value="http://ws.server.iris.com" />
<property name="serviceName" value="syncUserWsService" />
<property name="portName" value="syncUserWsServicePort" />
<property name="lookupServiceOnStartup" value="false"></property>
</bean>
</beans>
properties文件:
inc.client.incSysUser.wsdlurl=http\://test2.innocity.com\:39699/syncUserWsServiceImpl?wsdl
发布接口:
package com.iris.innocity2.nsoweb.service.ws.syncUser;
import javax.jws.WebService;
@WebService(serviceName="syncUserWsService",targetNamespace="http://ws.server.iris.com")
public interface SyncUserWsService {
public String syncUser(String sysCode,String paramXml) throws Exception;
}
接口实现类:
package com.iris.innocity2.nsoweb.service.ws.syncUser;
import java.util.LinkedHashMap;
import javax.jws.WebService;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.iris.innocity2.nsoweb.constants.IncWsConstants;
import com.iris.innocity2.nsoweb.model.register.PsnRegister;
import com.iris.innocity2.nsoweb.model.register.PsnRegisterForm;
import com.iris.innocity2.nsoweb.service.person.PersonService;
import com.iris.innocity2.nsoweb.service.register.PsnRegisterService;
import com.iris.innocity2.nsoweb.service.system.AuthLoginService;
import com.iris.innocity2.nsoweb.ws.utils.WsXmlDocument;
@WebService(serviceName="syncUserWsService",portName="syncUserWsServicePort",targetNamespace="http://ws.server.iris.com",endpointInterface="com.iris.innocity2.nsoweb.service.ws.syncUser.SyncUserWsService")
public class SyncUserWsServiceImpl implements SyncUserWsService {
protected final Logger logger=LoggerFactory.getLogger(getClass());
@Autowired
private PersonService personService;
@Autowired
private AuthLoginService authLoginService;
@Autowired
private PsnRegisterService psnRegisterService;
@SuppressWarnings("unused")
@Override
public String syncUser(String sysCode, String paramXml) throws Exception {
String resultXml = null;
String msg=null;
LinkedHashMap<String, String> dataMap=new LinkedHashMap<String, String>();
String incPsnId=null;
//参数效验
if (isMatchSysCode(sysCode)==false){
msg="sysCode非法";
}else if(StringUtils.isBlank(paramXml)){
msg="paramXml不能为空";
}else{
PsnRegister psnRegister=updateJxttUserInfo(paramXml);
if(psnRegister.getPsnId()>0){
incPsnId=psnRegister.getPsnId().toString();
}
}
//根据msg返回结果xml信息
WsXmlDocument wsXmlDocument = new WsXmlDocument("<?xml version=\"1.0\" encoding=\"UTF-8\"?><data></data>");
if(msg!=null)
{
dataMap.put("msg",msg);
dataMap.put("result", "error");
}else{
dataMap.put("result", "success");
dataMap.put("incPsnId",incPsnId);
}
logger.info("syncUser请求参数:"+dataMap.toString());
return wsXmlDocument.createPrimaryNode(dataMap);
}
/**
* 检查系统标示是否符合约定.
*
* @param sysCode
* @return
*/
private boolean isMatchSysCode(String sysCode) {
return (StringUtils.isNotBlank(sysCode) && StringUtils.equalsIgnoreCase(IncWsConstants.JXTT_SYS_CODE,sysCode));
}
public PsnRegister updateJxttUserInfo(String paramXml) throws Exception{
WsXmlDocument wsXmlDocument = new WsXmlDocument(paramXml);
Element rootEle = (Element) wsXmlDocument.getRootNode("/params");
PsnRegisterForm psnRegisterForm=new PsnRegisterForm();
PsnRegister psnRegister=new PsnRegister();
if (rootEle != null) {
//提取参数
if(rootEle.elementTextTrim("psnId")!=null){
psnRegisterForm.setScmPsnId(rootEle.elementTextTrim("psnId"));
}
if(rootEle.elementTextTrim("firstName")!=null){
psnRegisterForm.setFirstName(rootEle.elementTextTrim("firstName"));
}
if(rootEle.elementTextTrim("lastName")!=null){
psnRegisterForm.setLastName(rootEle.elementTextTrim("lastName"));
}
if(rootEle.elementTextTrim("name")!=null){
psnRegisterForm.setName(rootEle.elementTextTrim("name"));
}
if(rootEle.elementTextTrim("ename")!=null){
psnRegisterForm.setEname(rootEle.elementTextTrim("ename"));
}
if(rootEle.elementTextTrim("email")!=null){
psnRegisterForm.setEmail(rootEle.elementTextTrim("email"));
}
if(rootEle.elementTextTrim("position")!=null){
psnRegisterForm.setPosition(rootEle.elementTextTrim("position"));
}
if(rootEle.elementTextTrim("insName")!=null){
psnRegisterForm.setInsName(rootEle.elementTextTrim("insName"));
}
if(rootEle.elementTextTrim("avatars")!=null){
psnRegisterForm.setAvatars(rootEle.elementTextTrim("avatars"));
}
psnRegisterForm.setIsApply(0);
psnRegisterForm.setType("scm");
psnRegister=psnRegisterService.create(psnRegisterForm);
logger.info("*************updateJxttUserInfo成功");
}
return psnRegister;
}
}
配置文件:applicationContext-jaxws.xml:
<bean id="syncUserWsService" class="com.iris.innocity2.nsoweb.service.ws.syncUser.SyncUserWsServiceImpl" />
解析dom工具类:
package com.iris.innocity2.nsoweb.ws.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
/**
* <data> <interface> <method> <arg0></arg0>
* <arg1></arg1> ...... </method> </interface> </data>
*
*
*/
public class WsXmlDocument {
public static final String XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
public static final String WS_RESULT_PATH = "/result";
public static final String WS_DATA_PATH = "/data";
public static final String WS_PARAM_PATH = "/params";
public static final String WS_INTERFACE_PATH = "/interface";
public static final String WS_INTERFACE_METHOD_PATH = "/interface/method";
public static final String WS_ERROR_MSG_NODE = "/error_msg";
public static final String WS_RESULT_TOTAL_COUNT = "total_count";
/**
*
*/
private Document xmlDocument = null;
/**
* 1、构造返回类型doc;2、构造参数doc.
*
* @param type
* @throws DocumentException
*/
public WsXmlDocument(int type) throws DocumentException {
StringBuilder xml = new StringBuilder();
xml.append(WsXmlDocument.XML_DECL);
// 根据类型定义根节点.
if (type == 2) {
xml.append("<data><interface><method></method></interface></data>");
} else if (type == 3) {
xml.append("<data></data>");
} else {
xml.append("<result></result>");
}
xmlDocument = DocumentHelper.parseText(xml.toString());
}
public WsXmlDocument(String xmlData) throws DocumentException {
xmlDocument = DocumentHelper.parseText(xmlData);
}
public WsXmlDocument(Document doc) throws DocumentException {
xmlDocument = doc;
}
/**
* 增加无参构造器(不初始化根节点).
*
* @throws DocumentException
*/
public WsXmlDocument() throws DocumentException {
StringBuilder xml = new StringBuilder();
xml.append(WsXmlDocument.XML_DECL);
xmlDocument = DocumentHelper.parseText(xml.toString());
}
/**
* 获取接口节点.
*
* @return Node
*/
public Node getWsInterface() {
return this.getNode(WsXmlDocument.WS_INTERFACE_PATH);
}
/**
* 获取接口方法节点.
*
* @return Node
*/
public Node getWsInterfaceMethod() {
return this.getNode(WsXmlDocument.WS_INTERFACE_METHOD_PATH);
}
@SuppressWarnings("unchecked")
public List<Element> getMethodElementChildren() {
Element methodElement = (Element) this.getWsInterfaceMethod();
if (methodElement == null) {
throw new java.lang.NullPointerException("/data/interface/method is null.");
}
return methodElement.elements();
}
@SuppressWarnings("unchecked")
public List<String> getMethodParams() throws Exception {
List<String> valList = new ArrayList<String>();
Element methodElement = (Element) this.getWsInterfaceMethod();
List<Element> list = methodElement.elements();
if (CollectionUtils.isNotEmpty(list)) {
for (Element element : list) {
valList.add(element.getStringValue());
}
}
return valList;
}
/**
* 获取根节点.
*
* @return Node
*/
public Node getRootNode(String rootPath) {
return this.xmlDocument.selectSingleNode(rootPath);
}
/**
* @param xpath
* Xml元素路径
* @return List
*/
@SuppressWarnings("rawtypes")
public List getNodes(String rootPath, String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
if (!xpath.startsWith(rootPath))
xpath = rootPath + xpath;
return this.xmlDocument.selectNodes(xpath);
}
@SuppressWarnings("unchecked")
public List<Node> getResultNodes(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
return this.xmlDocument.selectNodes(WsXmlDocument.WS_RESULT_PATH + xpath);
}
/**
* @param fullPath
* xml元素路径
* @return String
* @throws InvalidXpathException
* InvalidXpathException
*/
public String getXmlNodeAttribute(String fullPath) throws InvalidXpathException {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
int pos = fullPath.indexOf("@");
if (pos == -1) {
throw new InvalidXpathException(fullPath);
}
String attrName = fullPath.substring(pos + 1);
String xpath = fullPath.substring(0, pos - 1);
Node node = this.getNode(xpath);
if (node != null) {
String val = node.valueOf("@" + attrName);
val = org.apache.commons.lang.StringUtils.stripToEmpty(val);
return val;
}
return "";
}
/**
* @param nodepath
* xml元素路径
* @param attrName
* xml属性名
* @param newValue
* xml属性新值
*/
public void setXmlNodeAttribute(String nodepath, String attrName, String newValue) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
if (attrName.startsWith("@")) {
attrName = attrName.substring(1);
}
Element ele = (Element) this.getNode(nodepath);
if (ele == null) {
return;
}
if (ele != null) {
ele.addAttribute(attrName, newValue);
}
}
/**
* @param xpath
* xml元素路径
* @return Node
*/
public Node getNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
if (!xpath.startsWith(WsXmlDocument.WS_DATA_PATH))
xpath = WsXmlDocument.WS_DATA_PATH + xpath;
return this.xmlDocument.selectSingleNode(xpath);
}
public Node getResultNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
return this.xmlDocument.selectSingleNode(xpath);
}
public void createMethodParamNode(Map<String, Object> map) {
if (MapUtils.isNotEmpty(map)) {
Element methodElement = (Element) this.getWsInterfaceMethod();
for (Map.Entry<String, Object> entry : map.entrySet()) {
methodElement.addElement(entry.getKey()).setText(ObjectUtils.toString(entry.getValue(), ""));
}
}
}
/**
*
* @param parentNode
* @param map
*/
public void createNode(Node parentNode, Map<String, String> map) {
if (parentNode != null && MapUtils.isNotEmpty(map)) {
Element parentElement = (Element) parentNode;
String value = "";
for (Map.Entry<String, String> entry : map.entrySet()) {
value = entry.getValue() == null ? "" : entry.getValue();
this.createElement(parentElement, entry.getKey()).setText(value);
}
}
}
/**
* 创建返回节点.
*
* @param resultType
* 1、成功; 2、缺少必要参数;3、未关联人员;4、远程调用同步出错
* @param errorMsg
* @return
*/
public String createResultData(int resultType, Map<String, String> map) {
Node node = this.xmlDocument.selectSingleNode(WsXmlDocument.WS_RESULT_PATH);
Element element = (Element) node;
element.addAttribute("value", resultType + "");
if (resultType == 1) {
element = element.addElement("data");
}
this.createNode(element, map);
return this.xmlDocument.asXML();
}
/**
* 创建根节点下的一级节点(有序排列).
*
* @param nodeName
* @param map
* @return
*/
@SuppressWarnings("rawtypes")
public String createPrimaryNode(LinkedHashMap<String, String> map) {
Element rootEle = xmlDocument.getRootElement();
if (map != null && map.size() > 0) {
Set<String> set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
String value = map.get(key);
rootEle.addElement(key);
rootEle.element(key).setText(value);
}
}
return this.xmlDocument.asXML();
}
/**
* 创建根节点的二级子节点,parentNodeName必须是根节点的一级子节点(即在一级子节点下增加多个相同名称的二级子节点).
*
* @param parentNodeName
* 一级子节点名称(已存在).
* @param subNodeName
* 二级子节点名称(需增加).
* @param dataList
* 子节点值列表.
*/
public void createSubNodeWithPath(String parentNodePath,
String subNodeName, List<?> dataList) {
if (StringUtils.isNotBlank(parentNodePath)
&& StringUtils.isNotBlank(subNodeName)
&& CollectionUtils.isNotEmpty(dataList)) {
Node node = this.getNode(parentNodePath);
Element currEle = (Element) node;
if (currEle != null) {
for (int i = 0; i < dataList.size(); i++) {
String value = ObjectUtils.toString(dataList.get(i));
currEle.addElement(subNodeName).setText(value);
}
}
}
}
/**
* 创建根节点的二级子节点,包含多个子节点属性(即在一级子节点下增加多个相同名称的二级子节点).
*
* @param parentNodeName
* 一级子节点名称(已存在).
* @param subNodeName
* 二级子节点名称(需增加).
* @param dataList
* 子节点值列表.
*/
@SuppressWarnings("rawtypes")
public void createSubNodeWithPath(String parentNodePath,
LinkedHashMap<String, String> map) {
if (StringUtils.isNotBlank(parentNodePath) && map != null
&& map.size() > 0) {
Node node = this.getNode(parentNodePath);
Element currEle = (Element) node;
Set<String> set = map.keySet();
if (currEle != null) {
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
String value = (StringUtils.isNotBlank(map.get(key)) ? map
.get(key) : "");
currEle.addElement(key).setText(value);
}
}
}
}
/**
* 创建根节点的二级子节点,包含多个子节点属性(即在一级子节点下增加多个相同名称的二级子节点).
*
* @param parentNodeName
* 一级子节点名称(已存在).
* @param subNodeName
* 二级子节点名称(需增加).
* @param dataList
* 子节点值列表.
*/
@SuppressWarnings("rawtypes")
public void createSubNodeAttribute(String parentNodePath,
String subNodeName, LinkedHashMap<String, String> map) {
if (StringUtils.isNotBlank(parentNodePath)
&& StringUtils.isNotBlank(subNodeName) && map != null
&& map.size() > 0) {
Node node = this.getNode(parentNodePath);
Element parentElement = (Element) node;
Set<String> set = map.keySet();
if (parentElement != null) {
Element currEle = parentElement.addElement(subNodeName);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
String value = map.get(key);
currEle.addAttribute(key, value);
}
}
}
}
public String getMethodParamVal(String xpath) {
Node node = this.getNode(WsXmlDocument.WS_DATA_PATH + WsXmlDocument.WS_INTERFACE_METHOD_PATH + xpath);
if (node != null) {
return node.getStringValue();
}
return null;
}
public String getResultParamVal(String xpath) {
Node node = this.getResultNode(WsXmlDocument.WS_RESULT_PATH + WsXmlDocument.WS_DATA_PATH + xpath);
if (node != null) {
return node.getStringValue();
}
return null;
}
/**
* @param xpath
* xml元素路径
* @param attrName
* xml属性名
* @return String
*/
public String getXmlNodeAttribute(String xpath, String attrName) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
if (node != null) {
return getXmlNodeAttributeValue(node, attrName);
}
return "";
}
/**
* @param node
* xml节点
* @param attrName
* xml属性名
* @return String
*/
public String getXmlNodeAttributeValue(Node node, String attrName) {
if (node == null) {
return "";
}
String val = node.valueOf("@" + attrName);
if (val == null) {
val = "";
}
return val.trim();
}
/**
* @param xpath
* xml元素路径
* @return boolean
*/
public boolean existsNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
return node != null;
}
/**
* @param xpath
* xml元素路径
* @param attrName
* xml属性
* @return boolean
*/
public boolean existsNodeAttribute(String xpath, String attrName) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
if (node == null) {
return false;
}
Element ele = (Element) node;
Attribute attr = ele.attribute(attrName);
return attr != null;
}
/**
* @param xpath
* xml元素路径
*/
public void removeNode(String xpath) {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
Node node = this.getNode(xpath);
if (node != null) {
boolean result = this.xmlDocument.remove(node);
if (!result) {
node.detach();
}
}
}
public String getXmlString() {
if (this.xmlDocument == null) {
throw new java.lang.NullPointerException("xml doc is null.");
}
String xml = this.xmlDocument.asXML();
return xml;
}
public Document getXmlDocument() {
return xmlDocument;
}
/**
* @param elePath
* xml元素路径 (e.g. /publication, /pub_members/pub_member[01],
* /pub_members, )
* @return Element
*/
public Element createElement(Element rootNode, String elePath) {
if (XmlUtils.isEmpty(elePath)) {
throw new java.lang.NullPointerException("can't create Element with NULL (elePath).");
}
elePath = elePath.toLowerCase();
String[] paths = XmlUtils.splitXPath(elePath); // 分割元素和元素的属性
String[] segs = paths[0].split("/"); // will return ['/','persons']
// or
// ['/','persons','person[1]','psn_id']
Element parentEle = (Element) rootNode.selectSingleNode(segs[1]);
if (parentEle == null) {
parentEle = rootNode.addElement(segs[1]);
}
// 只支持2级节点
if (segs.length > 2) {
String name = segs[2];
int pos = name.indexOf("[");
Integer seqNo = null;
if (pos > 0) {// 获取序号
String tmp = name.substring(pos + 1, name.length() - 1);
seqNo = Integer.parseInt(tmp);
}
// 删除序号
name = name.replaceAll("\\[.*\\]", "");
String selectedPath = segs[2];
Element ele = null;
if (seqNo != null) {
Element childEle = null;
// 页面提交的数据顺序是不确定的,因此如果前面序号的节点后到,则提前创建,防止页面获取XML数据乱序
for (int i = 1; i <= seqNo; i++) {
selectedPath = name + "[@seq_no=" + String.valueOf(i) + "]";
ele = (Element) parentEle.selectSingleNode(selectedPath); // segs[2]如:pub_member[01]
if (ele == null) {
ele = parentEle.addElement(name);
ele.addAttribute("seq_no", String.valueOf(i));
}
if (segs.length > 3) {
childEle = (Element) ele.selectSingleNode(segs[3]);
if (childEle == null) {
childEle = ele.addElement(segs[3]);
}
ele = childEle;
}
}
} else {
ele = (Element) parentEle.selectSingleNode(selectedPath);
if (ele == null) {
ele = parentEle.addElement(name);
}
}
return ele;
}
return parentEle;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static final void main(String[] args) {
LinkedHashMap<String, String> orderMap = new LinkedHashMap<String, String>();
orderMap.put("system_code", "sfms");
orderMap.put("result_type", "1");
orderMap.put("order_codes", "");
orderMap.put("err_msg", "");
List dataList = new ArrayList();
dataList.add("1");
dataList.add("2");
dataList.add("3");
dataList.add("4");
try {
WsXmlDocument doc = new WsXmlDocument(3);
System.out.println(doc.createPrimaryNode(orderMap));
System.out.println(doc.getXmlString());
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端调用
定义调用接口:
package com.iris.nsonline.nsoweb.service.ws.innocity;
import javax.jws.WebService;
/**
* 类说明:同步用户信息
*/
@WebService(serviceName = "syncUserWsService", targetNamespace = "http://ws.server.iris.com", endpointInterface = "com.iris.nsonline.nsoweb.service.ws.innocity.SyncUserWsService")
public interface SyncUserWsService {
public String syncUser(String sysCode,String paramXml) throws Exception;
}
Action进行调用:
package com.iris.nsonline.nsoweb.web.struts2.login;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.iris.nsonline.nsoweb.model.person.Person;
import com.iris.nsonline.nsoweb.model.person.PsnForm;
import com.iris.nsonline.nsoweb.security.utils.SecurityUtils;
import com.iris.nsonline.nsoweb.service.person.PersonService;
import com.iris.nsonline.nsoweb.service.person.ScmRelationAccountService;
import com.iris.nsonline.nsoweb.service.ws.innocity.SyncUserWsService;
import com.iris.nsonline.nsoweb.ws.utils.WsXmlDocument;
import com.iris.struts2.utils.Struts2Utils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
public class RelateAccountAction extends ActionSupport implements Preparable, ModelDriven<PsnForm>{
/**
*
*/
private static final long serialVersionUID = 7506884913405793653L;
protected final Logger logger = LoggerFactory.getLogger(getClass());
private PsnForm form;
@Autowired
private ScmRelationAccountService scmRelationAccountService;
@Value("${scm_relation_login_token}")
private String relationToken;
@Autowired
private SyncUserWsService syncUserWsService;
@Autowired
private PersonService personService;
@Action("/relation/scm/enterAjaxSaveAccountRelation")
public String enterAjaxSaveAccountRelation(){
Map<String, String> map = new HashMap<String, String>(2);
try {
Map<String, String> data = new HashMap<String, String>();
Long userId = SecurityUtils.getCurrentUserId();
if (userId!= null &&userId != 0L) {
form.setPsnId(userId);
form.setToken(this.relationToken);
// 去OpenUserUnionDemo查找记录,看是否有关联关系
Long openId = scmRelationAccountService.getOpenUserUnionByIdAndToken(userId,this.relationToken);
if (openId != null) {
if(syncUser(userId)){
map.put("result", "redirect");
}
Struts2Utils.renderJson(map, "encoding:UTF-8");
} else {
// 如果没关联,构建url跳到账号关联页面
String url = scmRelationAccountService.buildConnectionURL(form, form.getToken());
if (StringUtils.isNotBlank(url)) {
map.put("result", "success");
map.put("targetUrl", url);
Struts2Utils.renderJson(map, "encoding:UTF-8");
} else {
// url为空,说明生成URL失败,提示失败信息
data.put("result", "error");
data.put("errorMsg", "获取生成的URL为空");
Struts2Utils.renderJson(data, "encoding:UTF-8");
}
}
} else {
data.put("result", "error");
data.put("errorMsg", "人员ID为空");
Struts2Utils.renderJson(data, "encoding:UTF-8");
}
} catch (Exception e) {
logger.error("互联互通------跳转到账号关联页面失败", e);
}
return null;
}
@Action("/relation/scm/ajaxSaveAccountRelation")
public String ajaxSaveAccountRelation(){
try {
// 第三方系统获取当前登录的psnId
Map<String, String> map = new HashMap<String, String>(2);
Long userId = SecurityUtils.getCurrentUserId();
try {
if(userId>0){
form.setPsnId(userId);
form.setToken(this.relationToken);
if (form.getOpenId() != null && !form.getOpenId().equals(0L)&&scmRelationAccountService.checkSignatureRelation(form)) {
scmRelationAccountService.saveAccountRelation(form);
Struts2Utils.getSession().setAttribute("openId", form.getOpenId());//将openId存入session中
if(syncUser( userId)){
map.put("result", "success");
}
}
Struts2Utils.renderJson(map, "encoding:UTF-8");
}
} catch (Exception e) {
logger.error("模拟第三方系统保存关联关系出错", e);
map.put("result", "error");
Struts2Utils.renderJson(map, "encoding:UTF-8");
}
} catch (Exception e) {
logger.error("模拟第三方系统保存关联关系出错", e);
}
return null;
}
@Override
public PsnForm getModel() {
return form;
}
@Override
public void prepare() throws Exception {
if (form == null) {
form = new PsnForm();
}
}
public Boolean syncUser(Long userId) throws Exception{
Person person=personService.getPersonByPsnId(userId);
WsXmlDocument wsXmlDocument = new WsXmlDocument("<?xml version=\"1.0\" encoding=\"UTF-8\"?><params></params>");
LinkedHashMap<String, String> dataMap=new LinkedHashMap<String, String>();
dataMap.put("psnId", person.getPsnId().toString());
if(StringUtils.isNotEmpty(person.getFirstName())){
dataMap.put("firstName", person.getFirstName());
}
if(StringUtils.isNotEmpty(person.getLastName())){
dataMap.put("lastName", person.getLastName());
}
if(StringUtils.isNotEmpty(person.getName())){
dataMap.put("name", person.getName());
}
if(StringUtils.isNotEmpty(person.getEname())){
dataMap.put("ename", person.getEname());
}
if(StringUtils.isNotEmpty(person.getEmail())){
dataMap.put("email", person.getEmail());
}
if(StringUtils.isNotEmpty(person.getPosition())){
dataMap.put("position", person.getPosition());
}
if(StringUtils.isNotEmpty(person.getInsName())){
dataMap.put("insName", person.getInsName());
}
if(StringUtils.isNotEmpty(person.getAvatars())){
dataMap.put("avatars", person.getAvatars());
}
String xmlResult=syncUserWsService.syncUser("jxtt", wsXmlDocument.createPrimaryNode(dataMap));
//读取解析paramXml
wsXmlDocument = new WsXmlDocument(xmlResult);
//Element rootEle=(Element)xmlDocument.selectSingleNode(WsXmlDocument.WS_PARAM_PATH);
Element rootEle = (Element) wsXmlDocument.getRootNode("/data");
if (rootEle != null) {
//提取参数
String result=rootEle.elementTextTrim("result");
String incPsnId=rootEle.elementTextTrim("insPsnId");
//只有incPsnId或者scmPsnId有一个不为空
if (StringUtils.isNotBlank(result)) {
if(result.equals("success")){
person.setIncPsnId(Long.valueOf(incPsnId));
personService.save(person);
return true;
}
}
}
return false;
}
}
配置文件
applicationContext-jaxws.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<description>Spring公共配置文件</description>
<bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter">
<property name="baseAddress" value="${webserviceurl}/" />
</bean>
<bean id="syncUserWsService" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
<property name="serviceInterface" value="com.iris.nsonline.nsoweb.service.ws.innocity.SyncUserWsService" />
<property name="wsdlDocumentUrl" value="${inc.client.incSysUser.wsdlurl}" />
<property name="namespaceUri" value="http://ws.server.iris.com" />
<property name="serviceName" value="syncUserWsService" />
<property name="portName" value="syncUserWsServicePort" />
<property name="lookupServiceOnStartup" value="false"></property>
</bean>
</beans>
properties文件:
inc.client.incSysUser.wsdlurl=http\://test2.innocity.com\:39699/syncUserWsServiceImpl?wsdl