一、前言
基于airavata-common相关版本(0.9)包中org.apache.airavata.common.utils.XMLUtil工具类,可以对xml文档进行读取相互转换(String和XmlElement)、深度克隆deepClone、持久化保存文件saveXML、加载解析loadXML、校验分析validate等操作。
二、源码说明
1.XMLUtil
package org.apache.airavata.common.utils;@b@@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.StringReader;@b@import java.io.StringWriter;@b@import java.net.MalformedURLException;@b@import java.net.URL;@b@import java.util.ArrayList;@b@import java.util.Iterator;@b@import java.util.LinkedList;@b@import java.util.List;@b@import javax.xml.parsers.DocumentBuilder;@b@import javax.xml.parsers.DocumentBuilderFactory;@b@import javax.xml.parsers.ParserConfigurationException;@b@import org.apache.airavata.common.exception.UtilsException;@b@import org.apache.xmlbeans.XmlCursor;@b@import org.apache.xmlbeans.XmlError;@b@import org.apache.xmlbeans.XmlObject;@b@import org.apache.xmlbeans.XmlOptions;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@import org.w3c.dom.Document;@b@import org.w3c.dom.Element;@b@import org.w3c.dom.Text;@b@import org.xml.sax.SAXException;@b@import org.xmlpull.infoset.XmlDocument;@b@import org.xmlpull.infoset.XmlElement;@b@import org.xmlpull.infoset.XmlNamespace;@b@import org.xmlpull.mxp1.MXParserFactory;@b@import org.xmlpull.mxp1_serializer.MXSerializer;@b@@b@public class XMLUtil@b@{@b@ public static final org.xmlpull.infoset.XmlInfosetBuilder BUILDER = org.xmlpull.infoset.XmlInfosetBuilder.newInstance();@b@ public static final org.xmlpull.v1.builder.XmlInfosetBuilder BUILDER3 = org.xmlpull.v1.builder.XmlInfosetBuilder.newInstance(new MXParserFactory());@b@ private static final Logger logger = LoggerFactory.getLogger(XMLUtil.class);@b@ private static final String PROPERTY_SERIALIZER_INDENTATION = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation";@b@ private static final String INDENT = " ";@b@@b@ public static org.xmlpull.v1.builder.XmlElement stringToXmlElement3(String string)@b@ {@b@ return BUILDER3.parseFragmentFromReader(new StringReader(string));@b@ }@b@@b@ public static XmlElement stringToXmlElement(String string)@b@ {@b@ XmlDocument document = BUILDER.parseString(string);@b@ XmlElement element = document.getDocumentElement();@b@ return element;@b@ }@b@@b@ public static XmlElement xmlElement3ToXmlElement5(org.xmlpull.v1.builder.XmlElement element)@b@ {@b@ String string = xmlElementToString(element);@b@ return stringToXmlElement(string);@b@ }@b@@b@ public static org.xmlpull.v1.builder.XmlElement xmlElement5ToXmlElement3(XmlElement element)@b@ {@b@ String string = xmlElementToString(element);@b@ return stringToXmlElement3(string);@b@ }@b@@b@ public static String xmlElementToString(org.xmlpull.v1.builder.XmlElement element)@b@ {@b@ MXSerializer serializer = new MXSerializer();@b@ StringWriter writer = new StringWriter();@b@ serializer.setOutput(writer);@b@ serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " ");@b@ BUILDER3.serialize(element, serializer);@b@ String xmlText = writer.toString();@b@ return xmlText;@b@ }@b@@b@ public static String xmlElementToString(XmlElement element)@b@ {@b@ String string;@b@ if (element == null)@b@ string = "";@b@ else@b@ string = BUILDER.serializeToStringPretty(element);@b@@b@ return string;@b@ }@b@@b@ public static Element xppElementToDomElement(XmlElement xppElement, Document document)@b@ {@b@ Element domElement = document.createElement(xppElement.getName());@b@@b@ for (XmlNamespace namespace : xppElement.namespaces()) {@b@ logger.debug(new StringBuilder().append("namespace: ").append(namespace).toString());@b@ }@b@@b@ for (org.xmlpull.infoset.XmlAttribute attribute : xppElement.attributes()) {@b@ domElement.setAttribute(attribute.getName(), attribute.getValue());@b@ }@b@@b@ for (??? = xppElement.children().iterator(); ???.hasNext(); ) { Object object = ???.next();@b@ if (object instanceof XmlElement) {@b@ domElement.appendChild(xppElementToDomElement((XmlElement)object, document));@b@ } else if (object instanceof String) {@b@ Text text = document.createTextNode((String)object);@b@ domElement.appendChild(text);@b@ } else {@b@ logger.debug(new StringBuilder().append("object.getClass(): ").append(object.getClass()).toString());@b@ }@b@ }@b@ return domElement;@b@ }@b@@b@ @Deprecated@b@ public static xsul5.wsdl.WsdlDefinitions wsdlDefinitions3ToWsdlDefintions5(xsul.wsdl.WsdlDefinitions definitions3)@b@ {@b@ return WSDLUtil.wsdlDefinitions3ToWsdlDefintions5(definitions3);@b@ }@b@@b@ @Deprecated@b@ public static xsul.wsdl.WsdlDefinitions wsdlDefinitions5ToWsdlDefintions3(xsul5.wsdl.WsdlDefinitions definitions5)@b@ {@b@ return WSDLUtil.wsdlDefinitions5ToWsdlDefintions3(definitions5);@b@ }@b@@b@ public static Element xppElementToDomElement(org.xmlpull.v1.builder.XmlElement xppElement, Document document)@b@ {@b@ Element domElement = document.createElement(xppElement.getName());@b@@b@ Iterator nsIt = xppElement.namespaces();@b@ while (nsIt.hasNext()) {@b@ org.xmlpull.v1.builder.XmlNamespace namespace = (org.xmlpull.v1.builder.XmlNamespace)nsIt.next();@b@ logger.debug(new StringBuilder().append("namespace: ").append(namespace).toString());@b@ }@b@@b@ Iterator attrIt = xppElement.attributes();@b@ while (attrIt.hasNext()) {@b@ org.xmlpull.v1.builder.XmlAttribute attribute = (org.xmlpull.v1.builder.XmlAttribute)attrIt.next();@b@@b@ domElement.setAttribute(attribute.getName(), attribute.getValue());@b@ }@b@@b@ Iterator elementIt = xppElement.children();@b@ while (elementIt.hasNext()) {@b@ Object object = elementIt.next();@b@ if (object instanceof org.xmlpull.v1.builder.XmlElement) {@b@ domElement.appendChild(xppElementToDomElement((org.xmlpull.v1.builder.XmlElement)object, document));@b@ } else if (object instanceof String) {@b@ Text text = document.createTextNode((String)object);@b@ domElement.appendChild(text);@b@ } else {@b@ logger.debug(new StringBuilder().append("object.getClass(): ").append(object.getClass()).toString());@b@ }@b@ }@b@ return domElement;@b@ }@b@@b@ public static XmlElement deepClone(XmlElement element)@b@ throws UtilsException@b@ {@b@ XmlElement clonedElement;@b@ try@b@ {@b@ clonedElement = element.clone();@b@ clonedElement.setParent(null);@b@ return clonedElement;@b@ }@b@ catch (CloneNotSupportedException e) {@b@ throw new UtilsException(e);@b@ }@b@ }@b@@b@ public static void saveXML(XmlElement element, File file)@b@ throws IOException@b@ {@b@ XmlDocument document = BUILDER.newDocument();@b@ document.setDocumentElement(element);@b@ String xmlText = BUILDER.serializeToStringPretty(document);@b@ IOUtil.writeToFile(xmlText, file);@b@ }@b@@b@ public static void saveXML(org.xmlpull.v1.builder.XmlElement element, File file)@b@ throws IOException@b@ {@b@ saveXML(xmlElement3ToXmlElement5(element), file);@b@ }@b@@b@ public static XmlElement loadXML(InputStream stream)@b@ throws IOException@b@ {@b@ String xmlText = IOUtil.readToString(stream);@b@ XmlDocument document = BUILDER.parseString(xmlText);@b@ return document.getDocumentElement();@b@ }@b@@b@ public static XmlElement loadXML(File file)@b@ throws IOException@b@ {@b@ return loadXML(new FileInputStream(file));@b@ }@b@@b@ public static boolean isXML(String string)@b@ {@b@ try@b@ {@b@ stringToXmlElement(string);@b@ return true; } catch (RuntimeException e) {@b@ }@b@ return false;@b@ }@b@@b@ public static void validate(XmlObject xmlObject)@b@ throws UtilsException@b@ {@b@ XmlOptions validateOptions = new XmlOptions();@b@ ArrayList errorList = new ArrayList();@b@ validateOptions.setErrorListener(errorList);@b@@b@ boolean isValid = xmlObject.validate(validateOptions);@b@ if (isValid)@b@ {@b@ return;@b@ }@b@@b@ StringBuilder stringBuilder = new StringBuilder();@b@ for (int i = 0; i < errorList.size(); ++i) {@b@ XmlError error = (XmlError)errorList.get(i);@b@ logger.warn(new StringBuilder().append("Message: ").append(error.getMessage()).toString());@b@ logger.warn(new StringBuilder().append("Location of invalid XML: ").append(error.getCursorLocation().xmlText()).toString());@b@ stringBuilder.append(new StringBuilder().append("Message:").append(error.getMessage()).toString());@b@ stringBuilder.append(new StringBuilder().append("Location of invalid XML: ").append(error.getCursorLocation().xmlText()).toString());@b@ }@b@ throw new UtilsException(stringBuilder.toString());@b@ }@b@@b@ public static String getLocalPartOfQName(String qname)@b@ {@b@ int index = qname.indexOf(58);@b@ if (index < 0)@b@ return qname;@b@@b@ return qname.substring(index + 1);@b@ }@b@@b@ public static String getPrefixOfQName(String qname)@b@ {@b@ int index = qname.indexOf(58);@b@ if (index < 0)@b@ return null;@b@@b@ return qname.substring(0, index);@b@ }@b@@b@ public static XmlNamespace declareNamespaceIfNecessary(String prefixCandidate, String uri, boolean alwaysUseSuffix, XmlElement element)@b@ {@b@ XmlNamespace namespace = element.lookupNamespaceByName(uri);@b@ if (namespace == null)@b@ return declareNamespace(prefixCandidate, uri, alwaysUseSuffix, element);@b@@b@ return namespace;@b@ }@b@@b@ public static XmlNamespace declareNamespace(String prefixCandidate, String uri, boolean alwaysUseSuffix, XmlElement element)@b@ {@b@ if ((prefixCandidate == null) || (prefixCandidate.length() == 0))@b@ prefixCandidate = "a";@b@@b@ String prefix = prefixCandidate;@b@ if (alwaysUseSuffix)@b@ prefix = new StringBuilder().append(prefix).append("0").toString();@b@@b@ if (element.lookupNamespaceByPrefix(prefix) != null) {@b@ int i = 1;@b@ prefix = new StringBuilder().append(prefixCandidate).append(i).toString();@b@ while (element.lookupNamespaceByPrefix(prefix) != null)@b@ ++i;@b@ }@b@@b@ XmlNamespace namespace = element.declareNamespace(prefix, uri);@b@ return namespace;@b@ }@b@@b@ public static void removeElements(XmlElement xml, String name)@b@ {@b@ XmlElement xmlElement;@b@ Iterable removeElements = xml.elements(null, name);@b@ LinkedList removeList = new LinkedList();@b@ for (Iterator i$ = removeElements.iterator(); i$.hasNext(); ) { xmlElement = (XmlElement)i$.next();@b@ removeList.add(xmlElement);@b@ }@b@ for (i$ = removeList.iterator(); i$.hasNext(); ) { xmlElement = (XmlElement)i$.next();@b@ xml.removeChild(xmlElement);@b@ }@b@ Iterable children = xml.children();@b@ for (Iterator i$ = children.iterator(); i$.hasNext(); ) { Object object = i$.next();@b@ if (object instanceof XmlElement) {@b@ XmlElement element = (XmlElement)object;@b@ removeElements(element, name);@b@ }@b@ }@b@ }@b@@b@ public static Document retrievalXMLDocFromUrl(String url)@b@ {@b@ URL xmlUrl;@b@ try@b@ {@b@ xmlUrl = new URL(url);@b@ InputStream in = xmlUrl.openStream();@b@ Document ret = null;@b@@b@ DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();@b@ domFactory.setValidating(false);@b@ domFactory.setNamespaceAware(false);@b@ DocumentBuilder builder = domFactory.newDocumentBuilder();@b@@b@ ret = builder.parse(in);@b@@b@ return ret;@b@ } catch (MalformedURLException e) {@b@ e.printStackTrace();@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ } catch (ParserConfigurationException e) {@b@ e.printStackTrace();@b@ } catch (SAXException e) {@b@ e.printStackTrace();@b@ }@b@@b@ return null;@b@ }@b@@b@ public static Document retrievalXMLDocForParse(String url)@b@ {@b@ URL xmlUrl;@b@ try@b@ {@b@ xmlUrl = new URL(url);@b@ InputStream in = xmlUrl.openStream();@b@ DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();@b@ xmlFact.setNamespaceAware(true);@b@ DocumentBuilder builder = xmlFact.newDocumentBuilder();@b@ Document doc = builder.parse(in);@b@@b@ return doc;@b@ } catch (MalformedURLException e) {@b@ e.printStackTrace();@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ } catch (ParserConfigurationException e) {@b@ e.printStackTrace();@b@ } catch (SAXException e) {@b@ e.printStackTrace();@b@ }@b@@b@ return null;@b@ }@b@@b@ public static boolean isEqual(XmlElement elem1, XmlElement elem2) throws Exception@b@ {@b@ if ((elem1 == null) && (elem2 == null))@b@ return true;@b@ if (elem1 == null)@b@ return false;@b@ if (elem2 == null) {@b@ return false;@b@ }@b@@b@ if (!(elem1.getName().equals(elem2.getName()))) {@b@ return false;@b@ }@b@@b@ Iterator children1 = elem1.children().iterator();@b@ Iterator children2 = elem2.children().iterator();@b@@b@ Object child1 = null;@b@ Object child2 = null;@b@ if ((children1.hasNext()) && (children2.hasNext())) {@b@ child1 = children1.next();@b@ child2 = children2.next();@b@@b@ if ((!(children1.hasNext())) && (!(children2.hasNext())))@b@ {@b@ return compareObjs(child1, child2);@b@ }@b@@b@ List elemSet1 = getXmlElementsOnly(elem1.children().iterator());@b@ List elemSet2 = getXmlElementsOnly(elem2.children().iterator());@b@@b@ if (elemSet1.size() != elemSet2.size())@b@ return false;@b@@b@ for (int i = 0; i < elemSet1.size(); ++i)@b@ if (!(isEqual((XmlElement)elemSet1.get(i), (XmlElement)elemSet2.get(i))))@b@ return false;@b@@b@@b@ return true;@b@ }@b@@b@ return true;@b@ }@b@@b@ private static List<XmlElement> getXmlElementsOnly(Iterator itr)@b@ {@b@ LinkedList list = new LinkedList();@b@ while (itr.hasNext()) {@b@ Object obj = itr.next();@b@ if (obj instanceof XmlElement)@b@ list.add((XmlElement)obj);@b@ }@b@@b@ return list;@b@ }@b@@b@ private static boolean compareObjs(Object child1, Object child2)@b@ throws Exception@b@ {@b@ if ((child1 instanceof String) && (child2 instanceof String)) {@b@ return child1.equals(child2);@b@ }@b@@b@ if ((child1 instanceof XmlElement) && (child2 instanceof XmlElement))@b@ return isEqual((XmlElement)child1, (XmlElement)child2);@b@@b@ return false;@b@ }@b@}
2.IOUtil
package org.apache.airavata.common.utils;@b@@b@import java.io.ByteArrayOutputStream;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.FileReader;@b@import java.io.FileWriter;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.InputStreamReader;@b@import java.io.Reader;@b@import java.io.Writer;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@@b@public class IOUtil@b@{@b@ private static final Logger logger = LoggerFactory.getLogger(IOUtil.class);@b@@b@ public static void writeToFile(String content, String path)@b@ throws IOException@b@ {@b@ logger.debug(new StringBuilder().append("Path:").append(path).append(" Content:").append(content).toString());@b@@b@ FileWriter fw = new FileWriter(path);@b@ writeToWriter(content, fw);@b@ }@b@@b@ public static void writeToFile(String content, File file)@b@ throws IOException@b@ {@b@ FileWriter fw = new FileWriter(file);@b@ writeToWriter(content, fw);@b@ }@b@@b@ public static void writeToFile(InputStream inputStream, File file)@b@ throws IOException@b@ {@b@ FileOutputStream outputStream = new FileOutputStream(file);@b@ byte[] bytes = new byte[1024];@b@@b@ while ((len = inputStream.read(bytes)) != -1) {@b@ int len;@b@ outputStream.write(bytes, 0, len);@b@ }@b@ outputStream.close();@b@ }@b@@b@ public static void writeToWriter(String content, Writer writer)@b@ throws IOException@b@ {@b@ writer.write(content);@b@ writer.close();@b@ }@b@@b@ public static String readFileToString(String path)@b@ throws IOException@b@ {@b@ FileReader read = new FileReader(path);@b@ return readToString(read);@b@ }@b@@b@ public static String readFileToString(File file)@b@ throws IOException@b@ {@b@ FileReader reader = new FileReader(file);@b@ return readToString(reader);@b@ }@b@@b@ public static String readToString(InputStream stream)@b@ throws IOException@b@ {@b@ return readToString(new InputStreamReader(stream));@b@ }@b@@b@ public static String readToString(Reader reader)@b@ throws IOException@b@ {@b@ char[] cbuf = new char[1024];@b@ StringBuilder sbuf = new StringBuilder();@b@@b@ while ((len = reader.read(cbuf)) != -1) {@b@ int len;@b@ sbuf.append(cbuf, 0, len);@b@ }@b@ return sbuf.toString();@b@ }@b@@b@ public static byte[] readToByteArray(File file)@b@ throws IOException@b@ {@b@ return readToByteArray(new FileInputStream(file));@b@ }@b@@b@ public static byte[] readToByteArray(InputStream inputStream)@b@ throws IOException@b@ {@b@ byte[] buf = new byte[1024];@b@ ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();@b@@b@ while ((len = inputStream.read(buf)) != -1) {@b@ int len;@b@ byteArrayStream.write(buf, 0, len);@b@ }@b@ return byteArrayStream.toByteArray();@b@ }@b@@b@ public static boolean deleteDirectory(File path)@b@ {@b@ File[] arr$;@b@ int i$;@b@ if (path.exists()) {@b@ File[] files = path.listFiles();@b@ arr$ = files; int len$ = arr$.length; for (i$ = 0; i$ < len$; ++i$) { File file = arr$[i$];@b@ if (file.isDirectory())@b@ deleteDirectory(file);@b@ else@b@ file.delete();@b@ }@b@ }@b@@b@ return path.delete();@b@ }@b@@b@ public static String getExtension(File file)@b@ {@b@ String ext = null;@b@ String name = file.getName();@b@@b@ int index = name.lastIndexOf(46);@b@ if ((index > 0) && (index < name.length() - 1))@b@ ext = name.substring(index + 1).toLowerCase();@b@@b@ return ext;@b@ }@b@}