Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License").
   * You may not use this file except in compliance with the License.
   * A copy of the License is located at
   *
   *  http://aws.amazon.com/apache2.0
   *
  * or in the "license" file accompanying this file. This file 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.
  */
 package com.amazonaws.util;
 import java.net.URL;
 import java.util.Date;
 
 
 
Utility methods for extracting data from XML documents using Xpath expressions.
 
 public class XpathUtils {
    
The default property name to load the Xalan DTM manager.
 
     private static final String DTM_MANAGER_DEFAULT_PROP_NAME =
       "com.sun.org.apache.xml.internal.dtm.DTMManager";
    
The default property name to load the Xalan Document Builder Factory.
 
     private static final String DOCUMENT_BUILDER_FACTORY_PROP_NAME =
       "javax.xml.parsers.DocumentBuilderFactory";
     private static final Log log = LogFactory.getLog(XpathUtils.class);

    
Used to optimize performance by avoiding expensive file access every time a DTMManager is constructed as a result of constructing a Xalan xpath context!
 
     private static void speedUpDTMManager() {
         // https://github.com/aws/aws-sdk-java/issues/238
         // http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance
         String className = System.getProperty();
         if (className == null) {
             DTMManager dtmManager = new XPathContext().getDTMManager();
             if (dtmManager instanceof DTMManagerDefault) {
                 // This would avoid the file system to be accessed every time
                 // the internal XPathContext is instantiated.
                 System.setProperty(,
                         DTMManagerDefault.class.getName());
             }
         }
     }

    
Used to optimize performance by avoiding expensive file access every time a DocumentBuilderFactory is constructed as a result of constructing a Xalan document factory.
 
     private static void speedUpDcoumentBuilderFactory() {
         String className = System.getProperty();
         if (className == null) {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             if (factory instanceof DocumentBuilderFactoryImpl) {
                 // This would avoid the file system to be accessed every time
                 // the internal DocumentBuilderFactory is instantiated.
                 System.setProperty(,
                         DocumentBuilderFactoryImpl.class.getName());
             }
         }
     }
 
     // static initialization block to conservatively speed things up whenever we
     // can
     static {
         try {
             speedUpDcoumentBuilderFactory();
         } catch(Throwable t) {
             .debug("Ingore failure in speeding up DocumentBuilderFactory"t);
        }
        try {
            speedUpDTMManager();
        } catch(Throwable t) {
            .debug("Ingore failure in speeding up DTMManager"t);
        }
    }    
    
    // XPath is not thread safe and not reentrant.
    
Returns a new instance of XPath, which is not thread safe and not reentrant.
    public static XPath xpath() {
        return XPathFactory.newInstance().newXPath();
    }

    
This method closes the given input stream upon completion.
    public static Document documentFrom(InputStream is)
            throws SAXExceptionIOExceptionParserConfigurationException {
        is = new NamespaceRemovingInputStream(is);
        // DocumentBuilderFactory is not thread safe
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = factory.newDocumentBuilder().parse(is);
        is.close();
        return doc;
    }
    public static Document documentFrom(String xmlthrows SAXException,
            IOExceptionParserConfigurationException {
        return documentFrom(new ByteArrayInputStream(xml.getBytes(.)));
    }
    public static Document documentFrom(URL urlthrows SAXException,
            IOExceptionParserConfigurationException {
        return documentFrom(url.openStream());
    }

    
Evaluates the specified XPath expression and returns the results as a Double.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Double result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Double asDouble(String expressionNode node)
            throws XPathExpressionException {
        return asDouble(expressionnodexpath());
    }

    
Same as asDouble(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Double asDouble(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String doubleString = evaluateAsString(expressionnodexpath);
        return (isEmptyString(doubleString)) ? null : Double.parseDouble(doubleString);
    }

    
Evaluates the specified XPath expression and returns the result as a string.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The string result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static String asString(String expressionNode node)
            throws XPathExpressionException {
        return evaluateAsString(expressionnodexpath());
    }

    
Same as asString(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static String asString(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        return evaluateAsString(expressionnodexpath);
    }

    
Evaluates the specified XPath expression and returns the result as an Integer.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Integer result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Integer asInteger(String expressionNode node)
            throws XPathExpressionException {
        return asInteger(expressionnodexpath());
    }

    
Same as asInteger(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Integer asInteger(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String intString = evaluateAsString(expressionnodexpath);
        return (isEmptyString(intString)) ? null : Integer.parseInt(intString);
    }

    
Evaluates the specified XPath expression and returns the result as a Boolean.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Boolean result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Boolean asBoolean(String expressionNode node)
            throws XPathExpressionException {
        return asBoolean(expressionnodexpath());
    }

    
Same as asBoolean(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Boolean asBoolean(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String booleanString = evaluateAsString(expressionnodexpath);
        return (isEmptyString(booleanString)) ? null : Boolean.parseBoolean(booleanString);
    }

    
Evaluates the specified XPath expression and returns the result as a Float.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Float result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Float asFloat(String expressionNode node)
            throws XPathExpressionException {
        return asFloat(expressionnodexpath());
    }

    
Same as asFloat(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Float asFloat(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String floatString = evaluateAsString(expressionnodexpath);
        return (isEmptyString(floatString)) ? null : Float.valueOf(floatString);
    }

    
Evaluates the specified XPath expression and returns the result as a Long.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Long result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Long asLong(String expressionNode node)
            throws XPathExpressionException {
        return asLong(expressionnodexpath());
    }

    
Same as asLong(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Long asLong(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String longString = evaluateAsString(expressionnodexpath);
        return (isEmptyString(longString)) ? null : Long.parseLong(longString);
    }

    
Evaluates the specified XPath expression and returns the result as a Byte.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Byte result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Byte asByte(String expressionNode node)
            throws XPathExpressionException {
        return asByte(expressionnodexpath());
    }

    
Same as asByte(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Byte asByte(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String byteString = evaluateAsString(expressionnodexpath);
        return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString);
    }

    
Evaluates the specified XPath expression and returns the result as a Date. Assumes that the node's text is formatted as an ISO 8601 date, as specified by xs:dateTime.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Date result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Date asDate(String expressionNode node)
            throws XPathExpressionException {
        return asDate(expressionnodexpath());
    }

    
Same as asDate(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Date asDate(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String dateString = evaluateAsString(expressionnodexpath);
        if (isEmptyString(dateString)) return null;
        try {
            return DateUtils.parseISO8601Date(dateString);
        } catch (Exception e) {
            .warn("Unable to parse date '" + dateString + "':  " + e.getMessage(), e);
            return null;
        }
    }

    
Evaluates the specified xpath expression, base64 decodes the data and returns the result as a ByteBuffer.

This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { asDouble(java.lang.String,org.w3c.dom.Node,javax.xml.xpath.XPath) instead. Note javax.xml.xpath.XPath is not thread-safe and not reentrant.

Parameters:
expression The Xpath expression to evaluate.
node The node on which to evaluate the expression.
Returns:
A ByteBuffer of base64 decoded data from the result of evaluating the specified Xpath expression.
Throws:
javax.xml.xpath.XPathExpressionException If there are any problems evaluating the Xpath expression.
    public static ByteBuffer asByteBuffer(String expressionNode node)
            throws XPathExpressionException {
        return asByteBuffer(expressionnodexpath());
    }

    
Same as asByteBuffer(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static ByteBuffer asByteBuffer(String expressionNode nodeXPath xpath)
            throws XPathExpressionException {
        String base64EncodedString = evaluateAsString(expressionnodexpath);
        if (isEmptyString(base64EncodedString)) return null;
        if (!isEmpty(node)) {
            byte[] decodedBytes = Base64.decode(base64EncodedString);
            return ByteBuffer.wrap(decodedBytes);
        }
        return null;
    }

    
Returns true if the specified node is null or has no children.

Parameters:
node The node to test.
Returns:
True if the specified node is null or has no children.
    public static boolean isEmpty(Node node) {
        return (node == null);
    }

    
Evaluates the specified XPath expression and returns the result as a Node.

Parameters:
nodeName The XPath expression to evaluate.
node The node to run the expression on.
Returns:
The Node result.
Throws:
javax.xml.xpath.XPathExpressionException If there was a problem processing the specified XPath expression.
    public static Node asNode(String nodeNameNode node)
            throws XPathExpressionException {
        return asNode(nodeNamenodexpath());
    }

    
Same as asNode(java.lang.String,org.w3c.dom.Node) but allows an xpath to be passed in explicitly for reuse.
    public static Node asNode(String nodeNameNode nodeXPath xpath)
            throws XPathExpressionException {
        if (node == nullreturn null;
        return (Nodexpath.evaluate(nodeNamenode.);
    }

    
Returns the length of the specified node list.

Parameters:
list The node list to measure.
Returns:
The length of the specified node list.
    public static int nodeLength(NodeList list) {
        return list == null ? 0 : list.getLength();
    }

    
Evaluates the specified expression on the specified node and returns the result as a String.

Parameters:
expression The Xpath expression to evaluate.
node The node on which to evaluate the expression.
Returns:
The result of evaluating the specified expression, or null if the evaluation didn't return any result.
Throws:
javax.xml.xpath.XPathExpressionException If there are any problems evaluating the Xpath expression.
    private static String evaluateAsString(String expressionNode node,
            XPath xpaththrows XPathExpressionException {
        if (isEmpty(node)) return null;
        if (!expression.equals(".")) {
            /*
             * If the expression being evaluated doesn't select a node, we want
             * to return null to distinguish between cases where a node isn't
             * present (which should be represented as null) and when a node is
             * present, but empty (which should be represented as the empty
             * string).
             *
             * We skip this test if the expression is "." since we've already
             * checked that the node exists.
             */
            if (asNode(expressionnodexpath) == nullreturn null;
        }
        String s = xpath.evaluate(expressionnode);
        return s.trim();
    }

    
Returns true if the specified string is null or empty.

Parameters:
s The string to test.
Returns:
True if the specified string is null or empty.
    private static boolean isEmptyString(String s) {
        return s == null || s.trim().length() == 0;
    }
New to GrepCode? Check out our FAQ X