XMLUtils.java [src/java/util] Revision: default  Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API, and application suite.
 *
 * 2012-2017, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

/**
 * XML Utilities.
 */
public class XMLUtils {

    public static String makeURL(String url, String sFull) {
        // - Change Rusle2 path separators to URL path separators.
        sFull = sFull.replace('\\', '/');
        // - URL encode the string to remove percent characters.
        // Do this before we do any other encodings (which will contain % chars).
        sFull = sFull.replace("%", "%25");
        sFull = sFull.replace("#", "%23");
        // - URL encode the string to remove spaces.
        sFull = sFull.replace(" ", "%20");

        // - Restore forward slashes, which should not be encoded.
        sFull = sFull.replace("%2F", "/");

        // Prepend the URL prefix.
        return url + '/' + sFull + ".xml";
    }


    public static String escapeXMLFileURL(String sFull) {
        // - Change Rusle2 path separators to URL path separators.
        sFull = sFull.replace('\\', '/');
        // - URL encode the string to remove percent characters.
        // Do this before we do any other encodings (which will contain % chars).
        sFull = sFull.replace("%", "%25");
        sFull = sFull.replace("#", "%23");
        // - URL encode the string to remove spaces.
        sFull = sFull.replace(" ", "%20");

        // - Restore forward slashes, which should not be encoded.
        sFull = sFull.replace("%2F", "/");

        // Prepend the URL prefix.
        return sFull + ".xml";
    }

    public static String escapeURL(String sFull) {
        // - Change Rusle2 path separators to URL path separators.
        sFull = sFull.replace('\\', '/');
        // - URL encode the string to remove percent characters.
        // Do this before we do any other encodings (which will contain % chars).
        sFull = sFull.replace("%", "%25");
        sFull = sFull.replace("#", "%23");
        // - URL encode the string to remove spaces.
        sFull = sFull.replace(" ", "%20");

        // - Restore forward slashes, which should not be encoded.
        sFull = sFull.replace("%2F", "/");

        // Prepend the URL prefix.
        return sFull;
    }
    
    /**
     * Return the string selected by an XPath expression in an XML document.
     *
     * @param doc The XML document to select from.
     * @param xpathStr The XPath expression to select with.
     * @param sDefault Default string to return if XPath string is not found. We
     * also return this string for an empty XPath result.
     */
    public static String getDocumentString(Document doc, String xpathStr, String sDefault) {
        try {
            // Create an XPath result set for the XML document.
            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();
            XPathExpression expr = xpath.compile(xpathStr);
            // Run the query and get a nodeset
            String nodeStr = (String) expr.evaluate(doc, XPathConstants.STRING);
            nodeStr = nodeStr.trim();
            return nodeStr.isEmpty() ? sDefault : nodeStr;
        } catch (XPathExpressionException ex) {
            return sDefault;
        }
    }


    /**
     * Get an XML document from a URL which corresponds to that resource.
     *
     * @param sURL The URL string to fetch the data from. This can be an http://
     * or file:// URL.
     */
    public static Document getXMLDocFromURL(String sURL) {
        try {
            URL url = new URL(sURL);
            InputStream xmlstream = url.openStream();

            // Create an XML document from the XML string.
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(xmlstream);
            return doc;
        } catch (Exception ex) {
            return null;
        }
    }


    /**
     * Check if a document is present for a given key
     *
     * @param urlPrefix
     * @param key
     */
    public static void checkKey(String urlPrefix, String key) {
        InputStream xmlStream = null;
        String u = null;
        try {
            u = makeURL(urlPrefix, key);
            URL url = new URL(u);
            xmlStream = url.openStream();
        } catch (IOException ex) {
            throw new IllegalArgumentException(u);
        } finally {
            try {
                if (xmlStream != null) {
                    xmlStream.close();
                }
            } catch (IOException ex) {
                // whatever
            }
        }
    }
}