All Downloads are FREE. Search and download functionalities are using the official Maven repository.

sk.iway.iwcm.XmlUtils Maven / Gradle / Ivy

package sk.iway.iwcm;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Vector;

import javax.xml.XMLConstants;
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 org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

import sk.iway.iwcm.io.IwcmFile;
import sk.iway.iwcm.io.IwcmInputStream;
import sk.iway.iwcm.io.IwcmOutputStream;

/**
 *  XmlUtils.java - pomocne metody pre pracu s XML
 *
 *@Title        webjet4
 *@Company      Interway s.r.o. (www.interway.sk)
 *@Copyright    Interway s.r.o. (c) 2001-2008
 *@author       $Author: kmarton $
 *@version      $Revision: 1.6 $
 *@created      Date: 27.2.2008 15:45:28
 *@modified     $Date: 2010/02/11 13:55:35 $
 */
public class XmlUtils {

	protected XmlUtils() {
		//utility class
	}

	public static String getAttribute(Node node, String attrname) {
		if( node == null || attrname == null ) return null;
		NamedNodeMap ats = node.getAttributes();
		if( ats == null ) return null;
		for( int i = 0; i< ats.getLength(); i++ ) {
			Node n = ats.item(i);
			if( attrname.equalsIgnoreCase(n.getNodeName()) ) return n.getNodeValue();
		}
		return null;
	}



	public static String getText(Node node, boolean concatenate)
	{
		if (node == null)
			return null;
		Vector nl = getChildNodes(node,Node.TEXT_NODE);
		if (nl.size()==0)
			return null;

		StringBuilder result = new StringBuilder();
		for(int i=0;i nl = getChildNodes(node,Node.CDATA_SECTION_NODE);
		if (nl.size()==0)
			return null;

		StringBuilder result = new StringBuilder();
		for(int i=0;i getChildNodes( Node parent, short type )
	{
		Node node;
		Vector result  = new Vector<>();
		for( node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
			if( node.getNodeType() == type ) {
				result.add( node );
			}
		}
		return( result );
	}
	/*
		Removes the node's childnodes with the specified nodeType
	*/
	public static void removeChildNodes(Node node,short type)
	{
		if (node==null)
			return;
		NodeList nl = node.getChildNodes();
		if ( nl == null )
			return;
		int i=0;
		while (i<(nl=node.getChildNodes()).getLength())
		{
			Node n = nl.item(i);
			if (n.getNodeType()==type)
			{
				node.removeChild(n);
			}
			else
				i++;
		}
	}

	/*
		Removes all the node's childnodes
		Even the text nodes
	*/
	public static void removeAllChildren(Node node)
	{
		NodeList nl;
		while ((nl=node.getChildNodes()).getLength()>0)
			node.removeChild(nl.item(0));
	}

	/*
		Gets the node's childnodes with the specified nodeName
	*/
	public static Vector getChildNodes(Node parent, String tagName) {
		Vector result  = new Vector<>();
		if (parent == null) return result;
		NodeList nl = parent.getChildNodes();
		int length = nl.getLength();
		for (int i=0; i removeChildNodes(Node node,String name)
	{
		Vector nl = getChildNodes(node,name);
		for(int i=0;i getNodesWithAttribute(Node node,String attributeName,String attributeValue)
	{
		if ( node == null )
			return new Vector<>();
		else
			return getNodesWithAttribute(node.getChildNodes(),attributeName,attributeValue);
	}
	/*
		Selects the nodes from the NodeList which has attribute 'attributeName' with 'attributeValue'
	*/
	public static Vector getNodesWithAttribute(NodeList nl,String attributeName,String attributeValue)
	{
		Vector result  = new Vector<>();
		Element child;
		for(int i=0;i getSameNameSiblings(Node node)
	{
		if (node.getParentNode()!=null)
		{
			return getChildNodes(node.getParentNode(),node.getNodeName());
		}
		return new Vector<>();
	}

	/*
		Adds a new node with the specified tagName to the parent
	*/
	public static Element addNode(Node parent,String tagName)
	{
		Document doc = parent.getOwnerDocument();
		Element newNode = doc.createElement(tagName);
		parent.appendChild(newNode);
		return newNode;
	}
	/*
		Adds a new node with the specified tagName and value to the parent
	*/
	public static Element addNode(Node parent,String tagName,String value)
	{
		Element newNode = addNode(parent,tagName);
		setText(newNode,value);
		return newNode;
	}

	/*
		Searches for the node's childNodes with the specified name
		and returns the first one if exists or null
	*/
	public static Node getFirstChild( Node parent, String tagName )
	{
		Node node;
		Node result = null;

		for( node = parent.getFirstChild(); ( node != null ) && ( result == null ); node = node.getNextSibling())
		{
			if(( node.getNodeType() == Node.ELEMENT_NODE ) && ( tagName.equals( node.getNodeName())))
			{
				result = node;
			}
		}

		return( result );
	}

	/*
		Searches for the node's childNodes with the specified name
		and returns the textValue if a node was found
		if no node found or no text value exists returns an empty String
	*/
	public static String getFirstChildValue(Node node,String tagName)
	{
		String result = "";
		Node childnode = getFirstChild(node,tagName);
		if (childnode!=null)
			result = XmlUtils.getText(childnode);

		return result;
	}


	/*
		Returns whether the node has child nodes with the type Node.TEXT_NODE or not
	*/
	public static boolean hasNonTextChild(Node node)
	{
		int childcount = node.getChildNodes().getLength();
		int textchildcount = XmlUtils.getChildNodes(node,Node.TEXT_NODE).size();
		return (childcount!=textchildcount);
	}


	public static Node createSimpleElement(Document doc, String name, boolean value) {
		return createSimpleElement(doc, name, String.valueOf(value));
	}
	public static Node createSimpleElement(Document doc, String name, int value) {
		return createSimpleElement(doc, name, String.valueOf(value));
	}
	public static Node createSimpleElement(Document doc, String name, double value) {
		return createSimpleElement(doc, name, String.valueOf(value));
	}
	public static Node createSimpleElement(Document doc, String name, String value) {
		Element elem = doc.createElement(name);
		if(value != null)
			elem.appendChild(doc.createTextNode(value));
		return elem;
	}

	/**
	 * Returns the value of the given node as a boolean
	 */
	public static boolean nodeToBoolean(Node node) {
		if(node == null) {
			return false;
			//throw new IllegalArgumentException("null node");
		}
		String value;
		if(node instanceof Attr) {
			Attr attr = (Attr)node;
			value = attr.getValue();
		} else {
			value = getText(node);
		}

		if(value == null) throw new IllegalArgumentException("could not convert " + value + " to boolean");

		if(value.equals("true")) {
			return true;
		} else if(value.equals("false")) {
			return false;
		} else {
			throw new IllegalArgumentException("could not convert " + value + " to boolean");
		}
	}

	/** Adds an attribute with the specified name to the given element only if
	 *  the value parameter is not null. */
	public static void addAttr(Element parent, String name, String value) {
		if (value != null) {
			parent.setAttribute(name,value);
		}
	}

	/*
		@return the attribute value, or the specified defaultValue, if the node is not an instance
		of Element, or the specified attribute doesn't exist
	*/
	public static String getAttribute(Node node,String attribute, String defaultValue) {
		if (!(node instanceof Element))
			return defaultValue;
		String attrValue = ((Element)node).getAttribute(attribute);
		return attrValue == null || "".equals(attrValue) ? defaultValue : attrValue;
	}

	/*
		Returns the attribute value
		searches the parents if no attribute found in the node
	*/
	public static String getAttributeUp(Node node,String attribute)
	{
		if (!(node instanceof Element))
			return "";
		Element element = (Element)node;
		String result = "";
		do
		{
			result = element.getAttribute(attribute);
			if (result!=null)
				if (result.length()>0)
					return result;

			element=(Element)element.getParentNode();
		} while ((element!=null) && (element.getNodeType()!=Node.DOCUMENT_NODE)) ;

		return "";
	}

	public static boolean hasElementWithValue(Node parent,String tagName,String value)
	{
		return getElementsWithValue(parent,tagName,value).size()>0;
	}

	public static Vector getElementsWithValue(Node parent,String tagName,String value)
	{
		Vector nl = new Vector<>();
		if ((parent instanceof Element) && (value!=null))
		{
			NodeList elements = ((Element)parent).getElementsByTagName(tagName);
			for (int i=0;i getChildNodesByPath( final Node source, String path ) {
		if( path == null ) return null;
		if( path.charAt(0) == ('/') ) path = path.substring(1);
		int ps = path.indexOf('/');
		if( ps != -1 ) {
			String chstr = path.substring(0,ps);
			Node tch = getFirstChild( source, chstr);
			if( tch != null ) {
				return getChildNodesByPath(tch,path.substring(ps+1));
			}
		} else {
			return getChildNodes( source,path);
		}
		return null;
	}

	public static String normalizeAndPrint(String s) {
		if (s==null) return "";
		int len = s.length();
		StringWriter sout = new StringWriter();
		PrintWriter pw = new PrintWriter(sout);
		for (int i = 0; i < len; i++) {
			char c = s.charAt(i);
			normalizeAndPrint(pw,c,true);
		}
		pw.flush();
		return sout.toString();
	} // normalizeAndPrint(String)

	/** Normalizes and print the given character. */
	protected static void normalizeAndPrint(PrintWriter fOut, char c, boolean fCanonical ) {
		switch (c) {
			case '<': {
				fOut.print("<");
				break;
			}
			case '>': {
				fOut.print(">");
				break;
			}
			case '&': {
				fOut.print("&");
				break;
			}
			case '"': {
				fOut.print(""");
				break;
			}
			case '\r':
			case '\n': { //NOSONAR
				if (fCanonical) {
					fOut.print("&#");
					fOut.print(Integer.toString(c));
					fOut.print(';');
					break;
				}
				// else, default print char
			}
			default: {
				fOut.print(c);
			}
		}

	} // normalizeAndPrint(char)


	/**
	 * Vrati objekt typu Document zo zadaneho URL (lokalne)
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Document readDocument(String url) throws Exception
	{
		IwcmFile file = new IwcmFile(Tools.getRealPath(url));
		if (file.exists())
		{
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			// to be compliant, completely disable DOCTYPE declaration:
			docBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

			IwcmInputStream in = new IwcmInputStream(file);
			InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
			InputSource is = new InputSource(reader);
			is.setEncoding("utf-8");

			Document doc = docBuilder.parse(is);

			reader.close();
			in.close();

			return doc;
		}
		return null;
	}

	/**
	 * Ulozi objekt typu Document na zadane URL (lokalne)
	 * @param doc
	 * @param url
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static boolean saveDocument(Document doc, String url, String encoding) throws Exception
	{
		IwcmFile file = new IwcmFile(Tools.getRealPath(url));
		if (file.exists())
		{
			TransformerFactory xf = TransformerFactory.newInstance();
			// to be compliant, prohibit the use of all protocols by external entities:
			xf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
			xf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

			xf.setAttribute("indent-number", Integer.valueOf(2));

			Transformer xformer = xf.newTransformer();
			xformer.setOutputProperty(OutputKeys.METHOD, "xml");
			xformer.setOutputProperty(OutputKeys.INDENT, "yes");
			xformer.setOutputProperty(OutputKeys.ENCODING, encoding);

			Result result = new StreamResult(new OutputStreamWriter(new IwcmOutputStream(file), encoding));

			xformer.transform(new DOMSource(doc), result);
			return true;
		}
		return false;
	}

	/**
	 * Funkcia, ktora ziska text z xml tagu tagName v elemente el.
	 *
	 * @param tagName	Nazov tagu, z ktoreho chceme vytiahnut text
	 * @param el		Element, v ktorom sa nachadza dany tag
	 *
	 * @return	Vrati text, ktory sa nachadza v danom retazci. Ak nastane hocijaka chyba, vrati prazdny retazec.
	 *
	 * @author kmarton
	 */
	public static String getTextFromNode(String tagName, Element el)
	{
		NodeList list = null;
		try
		{
   		NodeList item = el.getElementsByTagName(tagName);
   		Element element = (Element)item.item(0);
   		list = element.getChildNodes();
		}
		catch (NullPointerException e)
		{
			return "";
		}

		if (list.item(0) != null)
   		return (list.item(0)).getNodeValue().trim();
   	else
   		return "";
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy