entaxy-public/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/xml/CommonXMLUtils.java

253 lines
9.1 KiB
Java

/*-
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2021 EmDev LLC
* ==========
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.platform.base.support.xml;
import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
/*import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.lib.NamespaceConstant;
*/
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import ru.entaxy.platform.base.support.CommonUtils;
public class CommonXMLUtils {
// GETTING DOCUMENT
public static Document getDocument(URL url) throws Exception{
return getDocument(url.openStream());
}
public static Document getDocument(InputStream stream) throws Exception {
return getDocument(false, stream);
}
public static Document getDocument(boolean namespaceAware, InputStream stream) throws Exception {
InputSource is = new InputSource(stream);
return getDocument(namespaceAware, is);
}
public static Document newDocument(boolean namespaceAware) throws Exception{
return getDocument(namespaceAware, (File)null);
}
public static Document getDocument(boolean namespaceAware, String path) throws Exception{
return getDocument(namespaceAware, CommonUtils.isValid(path)?(new File(path)):null);
}
public static Document getDocument(boolean namespaceAware, File file) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(namespaceAware);
DocumentBuilder db = dbf.newDocumentBuilder();
if (file!=null)
return db.parse(file);
else
return db.newDocument();
}
public static Document newDocument() throws Exception {
return newDocument(false);
}
public static Document getDocument(String path) throws Exception{
return getDocument(false, path);
}
public static Document parseString(boolean namespaceAware, String xmlData) throws Exception{
InputSource is = new InputSource(new StringReader(xmlData));
return getDocument(namespaceAware, is);
}
public static Document getDocument(InputSource source) throws Exception {
return getDocument(false, source);
}
public static Document getDocument(boolean namespaceAware, InputSource source) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
DocumentBuilder builder = factory.newDocumentBuilder();
Document d = builder.parse( source );
return d;
}
public static String doc2string(Document doc) throws Exception{
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString;
}
public static String node2string(Node node) throws Exception {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter sw = new StringWriter();
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString();
}
// SAVING DOCUMENT
public static void saveDocument(Document doc, String path) throws Exception{
File file = new File(path);
saveDocument(doc, file);
}
public static void saveDocument(Document doc, File file) throws Exception{
DOMSource source = new DOMSource(doc);
Result result = new StreamResult(file);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
}
// MARSHAL
public static void jaxbMarshal(JAXBContext context, JAXBElement<?> object, Node node) throws Exception{
Marshaller m = context.createMarshaller();
jaxbMarshall(m, object, node);
}
public static void jaxbMarshall(Marshaller m, JAXBElement<?> object, Node node) throws Exception{
if (node==null || node.getNodeType()!=Node.ELEMENT_NODE)
throw new IllegalArgumentException("Node is not Element");
m.marshal(object, node);
}
public static String jaxbMarshall(JAXBContext context, JAXBElement<?> object) throws Exception{
String result = null;
Marshaller m = context.createMarshaller();
StringWriter sw = new StringWriter();
m.marshal(object, sw);
result = sw.toString();
return result;
}
// UNMARSHAL
/**
*
* @param context
* @param node
* @param classMap
* @return
* @throws Exception
*/
public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node, HashMap<String, Class<? extends Object>> classMap) throws Exception{
Unmarshaller um = context.createUnmarshaller();
return jaxbUnmarshall(um, node, classMap);
}
public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node, HashMap<String, Class<? extends Object>> classMap) throws Exception{
if (node.getNodeType()!=Node.ELEMENT_NODE)
throw new IllegalArgumentException("Node is not Element");
String nodeName = node.getNodeName();
String[] s = nodeName.split(":");
nodeName = s[s.length-1];
Class<?> objectClass = classMap.get(nodeName.toLowerCase());
if (objectClass==null)
throw new IllegalArgumentException("Node name " +nodeName+ " not found in map " + classMap.toString());
Object obj = um.unmarshal(node, objectClass);
return (JAXBElement<?>)obj;
}
public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Document doc) throws Exception{
JAXBContext context = JAXBContext.newInstance(
type.getPackage().getName(), type.getClassLoader());
NodeList list = doc.getChildNodes();
Node node = null;
for (int i=0; i<list.getLength(); i++){
if (list.item(i).getNodeType() == Node.ELEMENT_NODE){
node = list.item(i);
break;
}
}
if (node == null)
throw new Exception("Root element not found in document");
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Node node) throws Exception{
JAXBContext context = JAXBContext.newInstance(
type.getPackage().getName(), type.getClassLoader());
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node, Class<?> type) throws Exception{
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node, Class<?> type) throws Exception{
Object obj = um.unmarshal(node, type);
return (JAXBElement<?>)obj;
}
// XSLT
/*
public static void transform(URL input, URL xslt, Result result) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",TransformerFactoryImpl.class.getClassLoader());
Source xsltS = new StreamSource(xslt.openStream());
Transformer transformer = factory.newTransformer(xsltS);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
InputStream is = input.openStream();
Source inputS = new StreamSource(is);
transformer.transform(inputS, result);
}
*/
// XPath
/* public static XPath createXPath() throws Exception {
XPathFactory factory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON,
"net.sf.saxon.xpath.XPathFactoryImpl", net.sf.saxon.xpath.XPathFactoryImpl.class.getClassLoader());
XPath xpath = factory.newXPath();
return xpath;
}
public static String getStringXPathResult(org.w3c.dom.Node node, String expression) throws Exception {
XPath xpath = createXPath();
XPathExpression expr = xpath.compile(expression);
Object result = expr.evaluate(node, XPathConstants.STRING);
if (result == null)
return null;
return result.toString();
}*/
}