XMLUtils.java [src/java/m/rusle2] Revision:   Date:
/*
 * $Id$
 * 
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * 2010-2013, Olaf David and others, Colorado State University.
 *
 * CSIP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, version 2.1.
 *
 * CSIP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with OMS.  If not, see <http://www.gnu.org/licenses/lgpl.txt>.
 */
package m.rusle2;

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;

/**
 *
 * @author od
 */
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
            }
        }
    }
}