org.w3c.dom.Document和org.dom4j.Document轉化、w3c和String轉化、SAXReader等
阿新 • • 發佈:2019-02-04
<一>把String轉化成org.dom4j.Document:
①Document document = DocumentHelper.parseText(messageXml);
②StringReader sr = new StringReader(str); InputSource is = new InputSource(sr); SAXReader reader = new SAXReader(); Document document = DocumentHelper.createDocument(); document = reader.read(is);
<二>org.w3c.dom.Document和org.dom4j.Document轉化
<三>w3c和String轉化
<四>SAXReader可以用來讀入String 也可以讀目錄下檔案中的xml
package com.zteits.atms.util.dom; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.xml.sax.InputSource; /** * <p>Title: DomParse</p> * <p>Description:org.dom4j.document和org.w3c.dom.document轉換</p> * */ public class DomParse { /** * org.w3c.dom.Document -> org.dom4j.Document * @param doc Document(org.w3c.dom.Document) * @return Document */ public static org.dom4j.Document parse(org.w3c.dom.Document doc) throws Exception { if(doc == null) { return (null); } org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader(); return (xmlReader.read(doc)); } /** * org.dom4j.Document -> org.w3c.dom.Document * @param doc Document(org.dom4j.Document) * @throws Exception * @return Document */ public static org.w3c.dom.Document parse(org.dom4j.Document doc) throws Exception { if(doc == null) { return (null); } java.io.StringReader reader = new java.io.StringReader(doc.asXML()); org.xml.sax.InputSource source = new org.xml.sax.InputSource(reader); javax.xml.parsers.DocumentBuilderFactory documentBuilderFactory = javax.xml.parsers.DocumentBuilderFactory .newInstance(); javax.xml.parsers.DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); return (documentBuilder.parse(source)); } public static org.w3c.dom.Document parseXmlToDocument(String s) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder df; try { df = dbf.newDocumentBuilder(); StringReader reader = new StringReader(s.trim()); InputSource source = new InputSource(reader); return df.parse(source); } catch(Exception e) { e.printStackTrace(); throw new Exception(); } } public static String getValueByTagName(org.w3c.dom.Document Doc, String tagName) { try { if(Doc != null) { org.w3c.dom.NodeList nl = Doc.getElementsByTagName(tagName); if(nl.getLength() > 0) { return nl.item(0).getTextContent(); } } } catch(Exception e) { e.printStackTrace(); } return ""; } public static String[] getValuesByTagName(org.w3c.dom.Document Doc, String tagName) { try { if(Doc != null) { org.w3c.dom.NodeList nl = Doc.getElementsByTagName(tagName); String[] returnStrs = new String[nl.getLength()]; for(int i = 0; i < nl.getLength(); i++) { returnStrs[i] = nl.item(i).getTextContent(); } return returnStrs; } } catch(Exception e) { e.printStackTrace(); } return new String[0]; } public static String XMLtoStr(Document document) { String result = null; if(document != null) { StringWriter strWtr = new StringWriter(); StreamResult strResult = new StreamResult(strWtr); TransformerFactory tfac = TransformerFactory.newInstance(); try { Transformer t = tfac.newTransformer(); t.setOutputProperty(OutputKeys.ENCODING, "gb2312"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); t.transform(new DOMSource(document.getDocumentElement()), strResult); } catch(Exception e) { System.err.println("XML.toString(Document): " + e); } result = strResult.getWriter().toString(); } return result; } }
-------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
package com.zteits.atms.tgs.carsearch.logic;</p><p>import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List;</p><p>import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult;</p><p>import org.dom4j.Document; import org.dom4j.DocumentHelper;</p><p>import com.zteits.atms.common.globalmem.logic.MemSysPointInfo; import com.zteits.atms.orm.dao.SysPointDAO; import com.zteits.atms.orm.pojo.SysDepartment; import com.zteits.atms.orm.pojo.SysPoint; import com.zteits.atms.tgs.common.dao.TgsPassedcarDAOEx; import com.zteits.atms.tgs.common.dao.TgsPointDAOExtend; import com.zteits.atms.tgs.common.vo.PassVO; import com.zteits.atms.util.dom.DomParse;</p><p>/** * 過車查詢業務介面實現類 * @author lyg * */ public class TgsCarSearchImpl implements ITgsCarSearch {</p><p> TgsPassedcarDAOEx tgsPassedcarDAO; SysPointDAO sysPointDAO; private TgsPointDAOExtend tgsPointDAOExtend;</p><p> /** * * @return * @throws Exception */ public List<SysDepartment> findDept() throws Exception { try { return tgsPassedcarDAO.findDept(); } catch(Exception e) { e.printStackTrace(); throw e; } }</p><p> public List<PassVO> findDepartComboboxTree(boolean withAll) { List all = sysPointDAO.findAllPassEquip(); List<PassVO> returnList = new ArrayList();</p><p> PassVO pass = new PassVO(); if(withAll) { pass.setPassid("-1"); pass.setPassname("全部"); returnList.add(pass); }</p><p> for(Iterator it = all.iterator(); it.hasNext();) { pass = new PassVO((Object[])it.next()); returnList.add(pass); } return returnList; }</p><p> /** * 分頁查詢 * @param currentPage 當前頁數 * @param pageSize 每頁的記錄條數 * @param carNo 號牌號碼 * @param carNoType 號牌型別 * @param from 採集卡口 * @param fx 方向 * @param st 開始時間 * @param et 結束時間 * @param isFuzzy 是否進行模糊查詢 * @param bm 部門 * @param carlane 車道 * @return 卡口記錄陣列 */ public List findPageTgsCar(int currentPage, int pageSize, String carNo, String carNoType, String from, String fx, String st, String et, Boolean carNoEntire, String bm, String cd) {</p><p> List carlist = new ArrayList(); try { SimpleDateFormat aSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); carlist = this.tgsPassedcarDAO.findPageTgsCar(currentPage, pageSize, carNo, carNoType, from, fx, st, et, carNoEntire, bm, cd);</p><p> } catch(Exception e) { e.printStackTrace(); } return carlist; }</p><p> /** * 得到車輛的總數 * @param carNo 號牌號碼 * @param carNoType 號牌型別 * @param from 採集卡口 * @param fx 方向 * @param st 開始時間 * @param et 結束時間 * @param isFuzzy 是否進行模糊查詢 * @param bm 部門 * @param carlane 車道 * @return 返回記錄總數 */ public int findTotalTgsCar(String carNo, String carNoType, String from, String fx, String st, String et, Boolean isNoMatch, String bm, String cd) {</p><p> int count = 0; try { SimpleDateFormat aSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); count = this.tgsPassedcarDAO.getTotalTgsCar(carNo, carNoType, from, fx, st, et, isNoMatch, bm, cd);</p><p> } catch(Exception e) { e.printStackTrace(); } return count; }</p><p> /** * 根據部門程式碼(採集部門)查詢卡口資訊 * @param deptcode * 部門程式碼 * @return Object陣列型別 * @author songxianqin */ public List<PassVO> findTgsPointsByDpt(String deptcode) throws Exception { try {</p><p> return tgsPointDAOExtend.getTgsPointsByDpt(deptcode);</p><p> } catch(Exception e) { e.printStackTrace(); throw e;</p><p> } }</p><p> public TgsPassedcarDAOEx getTgsPassedcarDAO() { return tgsPassedcarDAO; }</p><p> public void setTgsPassedcarDAO(TgsPassedcarDAOEx tgsPassedcarDAO) { this.tgsPassedcarDAO = tgsPassedcarDAO; }</p><p> public SysPointDAO getSysPointDAO() { return sysPointDAO; }</p><p> public void setSysPointDAO(SysPointDAO sysPointDAO) { this.sysPointDAO = sysPointDAO; }</p><p> public TgsPointDAOExtend getTgsPointDAOExtend() { return tgsPointDAOExtend; }</p><p> public void setTgsPointDAOExtend(TgsPointDAOExtend tgsPointDAOExtend) { this.tgsPointDAOExtend = tgsPointDAOExtend; }</p><p> /** * 返回所有緩建點位pointcode * */ public Object[] getUnBuiltPoint() throws Exception { try { return this.tgsPointDAOExtend.getUnBuiltPoint(); } catch(Exception e) { e.printStackTrace(); throw e; } } public String findLocationTree(String conditions) throws Exception { //組合XML檔案 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document doc = null; org.w3c.dom.Element rootkk = null; org.w3c.dom.Element root = null; org.w3c.dom.Element root1 = null; org.w3c.dom.Element element = null; String dldmstr = ""; try { doc = builder.newDocument(); rootkk = doc.createElement("node"); rootkk.setAttribute("label", "卡口地點"); rootkk.setAttribute("checked", "0"); rootkk.setAttribute("leaf", "0"); doc.appendChild(rootkk); root = doc.createElement("node"); root.setAttribute("label", "泗陽縣公安局"); root.setAttribute("checked", "0"); root.setAttribute("leaf", "0"); rootkk.appendChild(root); List all = sysPointDAO.findAllPassEquip(conditions); Iterator passit = all.iterator(); HashMap dlmap = new HashMap(); while(passit.hasNext()) { Object[] pass = (Object[]) passit.next(); if(!dldmstr.equals(pass[2])){ root1 = doc.createElement("node"); root1.setAttribute("dldm", ""+pass[2]); root1.setAttribute("checked", "0"); root1.setAttribute("label", ""+pass[3]); root1.setAttribute("leaf", "0"); root.appendChild(root1); element = doc.createElement("node"); element.setAttribute("ID", ""+pass[0]); element.setAttribute("checked", "0"); element.setAttribute("label", ""+pass[1]); element.setAttribute("leaf", "1"); root1.appendChild(element); }else{ element = doc.createElement("node"); element.setAttribute("ID", ""+pass[0]); element.setAttribute("checked", "0"); element.setAttribute("label", ""+pass[1]); element.setAttribute("leaf", "1"); root1.appendChild(element); } dldmstr = ""+pass[2]; } TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.setOutputProperty("encoding", "GBK");// 解決中文問題,試過用GBK不行 ByteArrayOutputStream bos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(bos)); String xmlStr = bos.toString(); System.out.println(xmlStr); return xmlStr ; } catch(Exception e) { throw e; } } public static Document parse(org.w3c.dom.Document doc) throws Exception { if(doc == null) { return (null); } org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader(); return (xmlReader.read(doc)); } } </p>
---------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------
<p>package com.zteits.atms.execution.gps.function;</p><p>import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;</p><p>import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;</p><p>import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;</p><p>import com.zteits.atms.execution.gps.dao.GpsExecutionDao;
import com.zteits.atms.guard.function.IGpsExecution;</p><p> </p><p>public class GpsExecutionImpl implements IGpsExecution{</p><p>
private String activemq_url;
private String distance_location;</p><p> private Connection connection = null;
//建立一個Topic
private Topic topic = null;
private Session session = null;
//註冊消費者
private MessageConsumer comsumer = null;
</p><p>
private List<String> guardIdList = new ArrayList<String>();
private List<MessageConsumer> comsumerList = new ArrayList<MessageConsumer>();
private List<Session> sessionList = new ArrayList<Session>();
private List<Connection> connectionList = new ArrayList<Connection>();
private GpsExecutionDao gpsExecutionDao;
public GpsExecutionDao getGpsExecutionDao() {
return gpsExecutionDao;
}</p><p> public void setGpsExecutionDao(GpsExecutionDao gpsExecutionDao) {
this.gpsExecutionDao = gpsExecutionDao;
}</p><p>
public String getActivemq_url() {
return activemq_url;
}</p><p> public void setActivemq_url(String activemq_url) {
this.activemq_url = activemq_url;
}</p><p> public String getDistance_location() {
return distance_location;
}</p><p> public void setDistance_location(String distance_location) {
this.distance_location = distance_location;
}</p><p> /**
* 執行gps警衛任務
*/
@Override
public String executionGpsGuardinfos(final String guardid, String flag) throws Exception {
System.out.println("xxxxxxxxxx" + flag);
guardIdList.add(guardid);</p><p> try {
if("start".equals(flag)) {
gpsExecutionDao.updateGuardTask(guardid, "1");
//查詢gps關聯警員車輛中執行任務的裝置
final List guardGpsCarorpoliceRelationList = gpsExecutionDao.findByCarorpolice(guardid);
//查詢gps關聯訊號裝置
final Object[] guardDeviceRelationObj = gpsExecutionDao.findByGuardDevice(guardid).toArray();
//連線工廠
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(activemq_url);
connection = factory.createConnection();
connection.start();
//建立一個Topic
topic= new ActiveMQTopic("zteits/topic/GpsCarMessageTopic");
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//註冊消費者
comsumer = session.createConsumer(topic);
comsumerList.add(comsumer);
sessionList.add(session);
connectionList.add(connection);
comsumer.setMessageListener(new MessageListener(){
private Object[] sigObj = guardDeviceRelationObj;
public void onMessage(Message m) {
try {
System.out.println(sigObj.length);
String messageXml = ((TextMessage)m).getText();
//解析接受的xml
Document document = DocumentHelper.parseText(messageXml);
Element root = document.getRootElement();
Iterator<Element> it = root.elementIterator("carinfo");
while(it.hasNext()) {
Element element = it.next();
String devicecode = element.attributeValue("devicecode");
String location = element.attributeValue("longtitude") + "," + element.attributeValue("latitude");
String str = (String) guardGpsCarorpoliceRelationList.get(0);
if(str.equals(devicecode)) {
//判斷訊號機與gps車輛警員位置
sigObj = getContrastLocation(sigObj,location,guardid);
System.out.println(sigObj.length);
}
}
//System.out.println("Consumer1 get " + ((TextMessage)m).getText());
} catch (Exception e) {
e.printStackTrace();
try {
stopGpsGuardinfos(guardid);
} catch (Exception e1) {
e1.printStackTrace();
}
}finally {
if(sigObj.length == 0) {
try {
stopGpsGuardinfos(guardid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
return "success";
} else {
stopGpsGuardinfos(guardid);
return "success";
}
} catch (Exception e) {
stopGpsGuardinfos(guardid);
e.printStackTrace();
throw e;
}
}
/**
* 判斷gps車輛警員與訊號的位置
* @param object
* @param location
* @return
* @throws Exception
*/
public Object[] getContrastLocation(Object[] object, String location, String guardid) throws Exception {
try {
float lng1 = Float.parseFloat(location.split(",")[0]);
float lat1 = Float.parseFloat(location.split(",")[1]);
List list = new ArrayList();
for (int i = 0; i < object.length; i++) {
Object[] obj = (Object[]) object[i];
float lng2 = Float.parseFloat(((String) obj[5]).split(",")[0]);
float lat2 = Float.parseFloat(((String) obj[5]).split(",")[1]);
double radLat1 = lat1*Math.PI/180;
double radLat2 = lat2*Math.PI/180;
double a = radLat1 - radLat2;
double b = lng1*Math.PI/180-lng2*Math.PI/180;
double s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2), 2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
s=s*6378137.0;
s=Math.round(s*10000)/10000;
System.out.println(s);
if(s <= Double.parseDouble(distance_location)) {
sendMq(obj,object.length,guardid);
System.out.println("呼叫介面改變相位==========="+obj[0] + "," + obj[1] + "," + obj[2] + "," + obj[3] + "," + obj[4]);
//呼叫訊號webservice
/*JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
String wsUrl = "<a target=_blank href="http://13.75.9.10/TSC/TscService.asmx?wsdl">http://13.75.9.10/TSC/TscService.asmx?wsdl</a>";
String method = "SetStage";
Client client = dcf.createClient(wsUrl);
Object[] res = null;
res = client.invoke(method, (String)obj[1], (String)obj[2], (String)obj[3], (String)obj[4]);*/
// JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
// String wsUrl = "<a target=_blank href="http://localhost:8081/TSC/TscServicePort?wsdl">http://localhost:8081/TSC/TscServicePort?wsdl</a>";
// String method = "SetStage";
// Client client = dcf.createClient(wsUrl);
// Object[] res = null;
// res = client.invoke(method, (String)obj[1], (String)obj[2], (String)obj[3], (String)obj[4]);
} else {
list.add(object[i]);
}
}
return list.toArray();
} catch (Exception e) {
e.printStackTrace();
try {
comsumer.close();
session.close();
connection.close();
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
}
/**
* 停止執行方法
*/
public String stopGpsGuardinfos(String guardid) throws Exception{
try {
gpsExecutionDao.updateGuardTask(guardid, "0");
if(comsumer != null) {
comsumer.close();
}
if(session != null) {
session.close();
}
if(connection != null) {
connection.close();
}
return "success";
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* 停止所有開啟的監聽
* @throws Exception
*/
public void stopGps() throws Exception{
try {
System.out.println("我執行啦!!!");
if(guardIdList != null && guardIdList.size() != 0) {
for (int i = 0; i < guardIdList.size(); i++) {
gpsExecutionDao.updateGuardTask(guardIdList.get(i), "0");
}
}
if(comsumerList != null && comsumerList.size() != 0) {
for (int i = 0; i < comsumerList.size(); i++) {
if(comsumerList.get(i) != null) {
comsumerList.get(i).close();
}
}
}
if(sessionList != null && sessionList.size() != 0) {
for (int i = 0; i < sessionList.size(); i++) {
if(sessionList.get(i) != null) {
sessionList.get(i).close();
}
}
}
if(connectionList != null && connectionList.size() != 0) {
for (int i = 0; i < connectionList.size(); i++) {
if(connectionList.get(i) != null) {
connectionList.get(i).close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* 傳送mq訊息
* @param obj
* @param num
* @param guardid
*/
public void sendMq(Object[] obj, int num,String guardid){
ConnectionFactory connectionFactory;
Connection connection = null;
Session session = null;
Destination destination;
MessageProducer producer;
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic("zteits/topic/GuardMessageTopic");
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
String xmlStr = "<ZTEITS type='GUARDGPS'><LOCATIONLIST><LOCATION end='"+num+"' guardid='"+guardid+"' equipid='"+obj[6]+"' ";
xmlStr += "equipcode='"+obj[0]+"' lng='"+((String) obj[5]).split(",")[0]+"' lat='"+((String) obj[5]).split(",")[1]+"'>" +
"</LOCATION></LOCATIONLIST></ZTEITS>";
TextMessage message = session.createTextMessage(xmlStr);
producer.send(message);
session.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
session.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}</p><p>
}
</p>
=============================================================================================================================
<p>public Object[] vmsXml() {
// 誘導路段模板Map.
SAXReader saxReader = new SAXReader();
Document document;
List<VmsRoadMap> lst = new ArrayList<VmsRoadMap>();
try {
<span style="background-color: rgb(255, 255, 102);">document = saxReader.read(VmsImgPubAction.class
.getResource("/vmsRoadInfo.xml"));</span>
// 獲取根元素
<span style="background-color: rgb(255, 255, 102);">Element root = document.getRootElement();</span>
for (Iterator iter = root.elementIterator(); iter.hasNext();) {
Element e = (Element) iter.next();</p><p> List<Element> childList = e.elements();</p><p> String[][] roadArray = new String[childList.size()][6];
for (int i = 0; i < childList.size(); i++) {
VmsRoadMap vmsRoadMap = new VmsRoadMap();
vmsRoadMap.setVmsid(e.attributeValue("id"));
vmsRoadMap.setId(childList.get(i).attributeValue("id"));
vmsRoadMap.setDeviceid(childList.get(i).attributeValue(
"deviceid"));
vmsRoadMap.setX1(childList.get(i).attributeValue("x1"));
vmsRoadMap.setY1(childList.get(i).attributeValue("y1"));
vmsRoadMap.setX2(childList.get(i).attributeValue("x2"));
vmsRoadMap.setY2(childList.get(i).attributeValue("y2"));
lst.add(vmsRoadMap);
}
}
return lst.toArray();
} catch (Exception e1) {
e1.printStackTrace();
}</p><p> return null;
}</p>