Example usage for javax.xml.xpath XPathExpression evaluate

List of usage examples for javax.xml.xpath XPathExpression evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpression evaluate.

Prototype

public String evaluate(InputSource source) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as a String .

Usage

From source file:org.dasein.cloud.azure.Azure.java

public @Nullable String getStorageService() throws CloudException, InternalException {
    if (storageService == null) {
        ProviderContext ctx = getContext();

        if (ctx == null) {
            throw new AzureConfigException("No configuration was set for this request");
        }// w w  w.  j av a 2 s.c o m
        AzureMethod method = new AzureMethod(this);

        Document xml = method.getAsXML(ctx.getAccountNumber(), "/services/storageservices");

        if (xml == null) {
            throw new CloudException("Unable to identify the storage service");
        }
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        try {
            XPathExpression expr = xpath
                    .compile("(/StorageServices/StorageService/StorageServiceProperties[GeoPrimaryRegion='"
                            + ctx.getRegionId() + "']/../ServiceName)[1]");
            storageService = expr.evaluate(xml).trim();
        } catch (XPathExpressionException e) {
            throw new CloudException(
                    "Failed to find storage service in the current region: " + ctx.getRegionId());
        }

        if (storageService == null || storageService.isEmpty())
            storageService = null;
    }
    return storageService;
}

From source file:org.easymock.itests.OsgiBaseTest.java

protected String getEasyMockVersion() {
    String version = getImplementationVersion(EasyMock.class);
    // Null means we are an IDE, not in Maven. So we have an IDE project dependency instead
    // of a Maven dependency with the jar. Which explains why the version is null (no Manifest
    // since there's no jar. In that case we get the version from the pom.xml and hope the Maven
    // jar is up-to-date in the local repository
    if (version == null) {
        try {//from www.j  a va 2  s  .  c  o m
            XPath xPath = xPathFactory.newXPath();
            XPathExpression xPathExpression;
            try {
                xPathExpression = xPath.compile("/project/parent/version");
            } catch (XPathExpressionException e) {
                throw new RuntimeException(e);
            }

            DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
            xmlFact.setNamespaceAware(false);
            DocumentBuilder builder = xmlFact.newDocumentBuilder();
            Document doc = builder.parse(new File("pom.xml"));
            version = xPathExpression.evaluate(doc);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return version;
}

From source file:org.dasein.cloud.azure.Azure.java

public @Nullable String getStorageEndpoint() throws CloudException, InternalException {
    if (storageEndpoint == null) {
        ProviderContext ctx = getContext();

        if (ctx == null) {
            throw new AzureConfigException("No configuration was set for this request");
        }/*  www  . j a  v  a2  s  .c o  m*/
        AzureMethod method = new AzureMethod(this);

        Document xml = method.getAsXML(ctx.getAccountNumber(), "/services/storageservices");

        if (xml == null) {
            throw new CloudException("Unable to identify the blob endpoint");
        }
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        try {
            XPathExpression expr = xpath
                    .compile("(/StorageServices/StorageService/StorageServiceProperties[GeoPrimaryRegion='"
                            + ctx.getRegionId() + "']/Endpoints/Endpoint[contains(.,'.blob.')])[1]");
            storageEndpoint = expr.evaluate(xml).trim();
        } catch (XPathExpressionException e) {
            throw new CloudException("Invalid blob endpoint search expression");
        }

        if (storageEndpoint == null || storageEndpoint.isEmpty())
            storageEndpoint = null;
    }
    return storageEndpoint;
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2AutoResponder.java

private Response generateACK(Status status, String hl7Message,
        HL7v2ResponseGenerationProperties hl7v2Properties) throws Exception {
    boolean errorOnly = false;
    boolean always = false;
    boolean successOnly = false;

    hl7Message = hl7Message.trim();//from   w  ww .  j av  a  2  s  . c o m
    boolean isXML = StringUtils.isNotBlank(hl7Message) && hl7Message.charAt(0) == '<';

    String ACK = null;
    String statusMessage = null;
    String error = null;

    try {
        if (serializationProperties.isConvertLineBreaks() && !isXML) {
            hl7Message = StringUtil.convertLineBreaks(hl7Message, serializationSegmentDelimiter);
        }

        // Check if we have to look at MSH15     
        if (hl7v2Properties.isMsh15ACKAccept()) {
            // MSH15 Dictionary:
            // AL: Always
            // NE: Never
            // ER: Error / Reject condition
            // SU: Successful completion only

            String msh15 = "";

            // Check if the message is ER7 or XML
            if (isXML) { // XML form
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression msh15Query = xpath.compile("//MSH.15/text()");
                DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = domFactory.newDocumentBuilder();
                Reader reader = new CharArrayReader(hl7Message.toCharArray());
                Document doc = builder.parse(new InputSource(reader));
                msh15 = msh15Query.evaluate(doc);
            } else { // ER7
                char fieldDelim = hl7Message.charAt(3); // Usually |
                char componentDelim = hl7Message.charAt(4); // Usually ^

                Pattern fieldPattern = Pattern.compile(Pattern.quote(String.valueOf(fieldDelim)));
                Pattern componentPattern = Pattern.compile(Pattern.quote(String.valueOf(componentDelim)));

                String mshString = StringUtils.split(hl7Message, serializationSegmentDelimiter)[0];
                String[] mshFields = fieldPattern.split(mshString);

                if (mshFields.length > 14) {
                    msh15 = componentPattern.split(mshFields[14])[0]; // MSH.15.1
                }
            }

            if (msh15 != null && !msh15.equals("")) {
                if (msh15.equalsIgnoreCase("AL")) {
                    always = true;
                } else if (msh15.equalsIgnoreCase("NE")) {
                    logger.debug("MSH15 is NE, Skipping ACK");
                    return null;
                } else if (msh15.equalsIgnoreCase("ER")) {
                    errorOnly = true;
                } else if (msh15.equalsIgnoreCase("SU")) {
                    successOnly = true;
                }
            }
        }

        String ackCode = "AA";
        String ackMessage = "";
        boolean nack = false;

        if (status == Status.ERROR) {
            if (successOnly) {
                // we only send an ACK on success
                return null;
            }
            ackCode = hl7v2Properties.getErrorACKCode();
            ackMessage = hl7v2Properties.getErrorACKMessage();
            nack = true;
        } else if (status == Status.FILTERED) {
            if (successOnly) {
                return null;
            }
            ackCode = hl7v2Properties.getRejectedACKCode();
            ackMessage = hl7v2Properties.getRejectedACKMessage();
            nack = true;
        } else {
            if (errorOnly) {
                return null;
            }
            ackCode = hl7v2Properties.getSuccessfulACKCode();
            ackMessage = hl7v2Properties.getSuccessfulACKMessage();
        }

        ACK = HL7v2ACKGenerator.generateAckResponse(hl7Message, isXML, ackCode, ackMessage,
                generationProperties.getDateFormat(), new String(), deserializationSegmentDelimiter);
        statusMessage = "HL7v2 " + (nack ? "N" : "") + "ACK successfully generated.";
        logger.debug("HL7v2 " + (nack ? "N" : "") + "ACK successfully generated: " + ACK);
    } catch (Exception e) {
        logger.warn("Error generating HL7v2 ACK.", e);
        throw new Exception("Error generating HL7v2 ACK.", e);
    }

    return new Response(status, ACK, statusMessage, error);
}

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

XPathExpression conjoinXPaths(Document fragment, String base) throws Exception {
    String path = "//*";
    final Element e = fragment.getDocumentElement();
    if (e == null)
        return null;
    final XPathIterator conjunction = new XPathIterator(e, base);
    if (conjunction.hasNext()) {
        path += "[";
        boolean first = true;
        while (conjunction.hasNext()) {
            if (!first)
                path += " and ";
            XPathExpression x = conjunction.next();
            String exp = x.toString();
            boolean positive = true;
            if (exp.startsWith("-")) {
                positive = false;/*w w  w.j ava 2s.c o m*/
                exp = exp.substring(1);
            }
            // remove the initial '/'
            exp = exp.substring(1);
            if (positive)
                path += exp;
            else
                path += "not(" + exp + ")";
            first = false;
        }
        path += "]";
    }
    XPath xpath = xPathFactory.newXPath();
    // add namespace prefix resolver to the xpath based on the current element
    xpath.setNamespaceContext(new AbstractNamespaceContext() {
        public String getNamespaceURI(String prefix) {
            // for the empty prefix lookup the default namespace
            if (prefix.isEmpty())
                return e.lookupNamespaceURI(null);
            for (int i = 0; i < conjunction.contexts.size(); i++) {
                NamespaceContext c = conjunction.contexts.get(i);
                String ns = c.getNamespaceURI(prefix);
                if (ns != null)
                    return ns;
            }
            return null;
        }
    });
    final String exp = path;
    final XPathExpression compiled = xpath.compile(path);
    if (verbose)
        System.out.println(exp);

    return new XPathExpression() {
        public String evaluate(Object source) throws XPathExpressionException {
            return compiled.evaluate(source);
        }

        public String evaluate(InputSource source) throws XPathExpressionException {
            return compiled.evaluate(source);
        }

        public Object evaluate(Object source, QName returnType) throws XPathExpressionException {
            return compiled.evaluate(source, returnType);
        }

        public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException {
            return compiled.evaluate(source, returnType);
        }

        public String toString() {
            return exp;
        }
    };
}

From source file:com.rapid.core.Pages.java

public void loadpages(ServletContext servletContext)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {

    // clear the pages
    _pages.clear();//www  .  ja v  a  2  s.c om

    // force the pages to be resorted
    _sortedPageHeaders = null;

    // create a new map for caching page files by id's
    _pageHeaders = new HashMap<String, PageHeader>();

    // initiate pages folder 
    File pagesFolder = new File(_application.getConfigFolder(servletContext) + "/pages");

    // if the folder is there
    if (pagesFolder.exists()) {

        // these are not thread safe so can't be reused
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();

        // create objects for xml parsing          
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        // compile the xpath expressions
        XPathExpression xpathId = xpath.compile("/page/id");
        XPathExpression xpathName = xpath.compile("/page/name");
        XPathExpression xpathTitle = xpath.compile("/page/title");

        // loop the .page.xml files and add to the application
        for (File pageFile : pagesFolder.listFiles(_filenameFilter)) {

            // parse the xml file
            Document doc = docBuilder.parse(pageFile);

            // get the page id from the file
            String pageId = xpathId.evaluate(doc);
            // get the name
            String pageName = xpathName.evaluate(doc);
            // get the title
            String pageTitle = xpathTitle.evaluate(doc);

            // cache the page id against the file so we don't need to use the expensive parsing operation again
            _pageHeaders.put(pageId, new PageHeader(pageId, pageName, pageTitle, pageFile));

        }

    }

}

From source file:de.pangaea.fixo3.xml.ProcessXmlFiles.java

private void run() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException,
        XPathExpressionException {
    // src/test/resources/, src/main/resources/files
    File folder = new File("src/main/resources/files");
    File[] files = folder.listFiles(new FileFilter() {

        @Override//from w ww. j  ava 2s.co  m
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith(".xml"))
                return true;

            return false;
        }
    });

    JsonArrayBuilder json = Json.createArrayBuilder();

    Document doc;
    String deviceLabel, deviceComment, deviceImage;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    final Map<String, String> prefixToNS = new HashMap<>();
    prefixToNS.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    prefixToNS.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    prefixToNS.put("sml", "http://www.opengis.net/sensorml/2.0");
    prefixToNS.put("gml", "http://www.opengis.net/gml/3.2");
    prefixToNS.put("gmd", "http://www.isotc211.org/2005/gmd");

    XPath x = XPathFactory.newInstance().newXPath();
    x.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            Objects.requireNonNull(prefix, "Namespace prefix cannot be null");
            final String uri = prefixToNS.get(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("Undeclared namespace prefix: " + prefix);
            }
            return uri;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException();
        }
    });

    XPathExpression exGmlName = x.compile("/sml:PhysicalSystem/gml:name");
    XPathExpression exGmlDescription = x.compile("/sml:PhysicalSystem/gml:description");
    XPathExpression exGmdUrl = x.compile(
            "/sml:PhysicalSystem/sml:documentation/sml:DocumentList/sml:document/gmd:CI_OnlineResource/gmd:linkage/gmd:URL");
    XPathExpression exTerm = x
            .compile("/sml:PhysicalSystem/sml:classification/sml:ClassifierList/sml:classifier/sml:Term");

    int m = 0;
    int n = 0;

    for (File file : files) {
        log.info(file.getName());
        doc = dbf.newDocumentBuilder().parse(new FileInputStream(file));

        deviceLabel = exGmlName.evaluate(doc).trim();
        deviceComment = exGmlDescription.evaluate(doc).trim();
        deviceImage = exGmdUrl.evaluate(doc).trim();
        NodeList terms = (NodeList) exTerm.evaluate(doc, XPathConstants.NODESET);

        JsonObjectBuilder jobDevice = Json.createObjectBuilder();

        jobDevice.add("name", toUri(deviceLabel));
        jobDevice.add("label", deviceLabel);
        jobDevice.add("comment", toAscii(deviceComment));
        jobDevice.add("image", deviceImage);

        JsonArrayBuilder jabSubClasses = Json.createArrayBuilder();

        for (int i = 0; i < terms.getLength(); i++) {
            Node term = terms.item(i);
            NodeList attributes = term.getChildNodes();

            String attributeLabel = null;
            String attributeValue = null;

            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                String attributeName = attribute.getNodeName();

                if (attributeName.equals("sml:label")) {
                    attributeLabel = attribute.getTextContent();
                } else if (attributeName.equals("sml:value")) {
                    attributeValue = attribute.getTextContent();
                }
            }

            if (attributeLabel == null || attributeValue == null) {
                throw new RuntimeException("Attribute label or value cannot be null [attributeLabel = "
                        + attributeLabel + "; attributeValue = " + attributeValue + "]");
            }

            if (attributeLabel.equals("model")) {
                continue;
            }

            if (attributeLabel.equals("manufacturer")) {
                jobDevice.add("manufacturer", attributeValue);
                continue;
            }

            n++;

            Quantity quantity = getQuantity(attributeValue);

            if (quantity == null) {
                continue;
            }

            m++;

            JsonObjectBuilder jobSubClass = Json.createObjectBuilder();
            JsonObjectBuilder jobCapability = Json.createObjectBuilder();
            JsonObjectBuilder jobQuantity = Json.createObjectBuilder();

            String quantityLabel = getQuantityLabel(attributeLabel);
            String capabilityLabel = deviceLabel + " " + quantityLabel;

            jobCapability.add("label", capabilityLabel);

            jobQuantity.add("label", quantity.getLabel());

            if (quantity.getValue() != null) {
                jobQuantity.add("value", quantity.getValue());
            } else if (quantity.getMinValue() != null && quantity.getMaxValue() != null) {
                jobQuantity.add("minValue", quantity.getMinValue());
                jobQuantity.add("maxValue", quantity.getMaxValue());
            } else {
                throw new RuntimeException(
                        "Failed to determine quantity value [attributeValue = " + attributeValue + "]");
            }

            jobQuantity.add("unitCode", quantity.getUnitCode());
            jobQuantity.add("type", toUri(quantityLabel));

            jobCapability.add("quantity", jobQuantity);
            jobSubClass.add("capability", jobCapability);

            jabSubClasses.add(jobSubClass);
        }

        jobDevice.add("subClasses", jabSubClasses);

        json.add(jobDevice);
    }

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);

    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(properties);
    JsonWriter jsonWriter = jsonWriterFactory.createWriter(new FileWriter(new File(jsonFileName)));
    jsonWriter.write(json.build());
    jsonWriter.close();

    System.out.println("Fraction of characteristics included: " + m + "/" + n);
}

From source file:com.novartis.opensource.yada.test.ServiceTest.java

/**
 * Validation method for XML response/*  w  w w  . ja  v  a 2 s.  co  m*/
 * 
 * @param result the query result
 * @return {@code true} if result complies with expected output spec
 * @throws YADAResponseException when the test result is invalid
 */
public boolean validateXMLResult(String result) throws YADAResponseException {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(result)));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression resultSets = xpath.compile("/RESULTSETS");
        XPathExpression nestedTotal = xpath.compile("//RESULTSET/@total[1]");
        XPathExpression resultSet = xpath.compile("/RESULTSET");
        XPathExpression colCase = xpath.compile("//" + COL_STRING + "[1]");
        String evalSets = resultSets.evaluate(doc);
        String evalSet = resultSet.evaluate(doc);
        XPathExpression colInt = xpath.compile("//" + COL_INTEGER + "[1]");
        XPathExpression colNum = xpath.compile("//" + COL_NUMBER + "[1]");
        XPathExpression colDat = xpath.compile("//" + COL_DATE + "[1]");
        XPathExpression colTim = xpath.compile("//" + COL_TIME + "[1]");
        if ((evalSets != null && evalSets.length() > 0) || (evalSet != null && evalSet.length() > 0)) {
            String eval = nestedTotal.evaluate(doc);
            if (eval != null && eval.length() > 0 && Integer.parseInt(eval) > 0) {
                logMarkupResult(result);
                String evalCol = colCase.evaluate(doc);
                if (evalCol == null || evalCol.length() == 0) {
                    colInt = xpath.compile("//" + COL_INTEGER_LC + "[1]");
                    colNum = xpath.compile("//" + COL_NUMBER_LC + "[1]");
                    colDat = xpath.compile("//" + COL_DATE_LC + "[1]");
                    colTim = xpath.compile("//" + COL_TIME_LC + "[1]");
                }
                try {
                    return validateInteger(colInt.evaluate(doc)) && validateNumber(colNum.evaluate(doc))
                            && validateDate(colDat.evaluate(doc)) && validateTime(colTim.evaluate(doc));
                } catch (NumberFormatException e) {
                    String msg = "Unable to validate result content.";
                    throw new YADAResponseException(msg, e);
                } catch (ParseException e) {
                    String msg = "Unable to validate result content.";
                    throw new YADAResponseException(msg, e);
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new YADAResponseException("XML Document creation failed.", e);
    } catch (SAXException e) {
        throw new YADAResponseException("XML Document creation failed.", e);
    } catch (IOException e) {
        throw new YADAResponseException("XML Document creation failed.", e);
    } catch (XPathExpressionException e) {
        throw new YADAResponseException("Results do not contain expected XML content", e);
    }
    return true;
}

From source file:org.apache.ambari.view.slider.rest.client.SliderAppJmxHelper.java

public static void extractMetricsFromJmxXML(InputStream jmxStream, String jmxUrl,
        Map<String, String> jmxProperties, Map<String, Metric> metrics)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(jmxStream);
    for (String key : metrics.keySet()) {
        Metric metric = metrics.get(key);
        XPathExpression xPathExpression = metric.getxPathExpression();
        if (xPathExpression != null) {
            String value = xPathExpression.evaluate(doc);
            if (value != null) {
                jmxProperties.put(key, value.toString().trim());
            }/*w  ww.ja  v a  2  s  .co m*/
        }
    }
}

From source file:org.apache.ode.bpel.compiler.v1.xpath10.jaxp.JaxpXPath10ExpressionCompilerImpl.java

/**
 * Verifies validity of a xpath expression.
 *//*from  w  w  w  . j  a  va 2 s .c om*/
protected void doJaxpCompile(OXPath10Expression out, Expression source) throws CompilationException {
    String xpathStr;
    Node node = source.getExpression();
    if (node == null) {
        throw new IllegalStateException("XPath string and xpath node are both null");
    }

    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.errXPathSyntax(xpathStr));
    }

    try {
        __log.debug("JAXP compile: xpath = " + xpathStr);
        // use default XPath implementation
        XPathFactory xpf = XPathFactory.newInstance();
        __log.debug("JAXP compile: XPathFactory impl = " + xpf.getClass());
        XPath xpath = xpf.newXPath();
        xpath.setXPathFunctionResolver(
                new JaxpFunctionResolver(_compilerContext, out, source.getNamespaceContext(), _bpelNsURI));
        xpath.setXPathVariableResolver(new JaxpVariableResolver(_compilerContext, out));
        xpath.setNamespaceContext(source.getNamespaceContext());
        XPathExpression xpe = xpath.compile(xpathStr);
        // dummy evaluation to resolve variables and functions (hopefully complete...)
        xpe.evaluate(DOMUtils.newDocument());
        out.xpath = xpathStr;
    } catch (XPathExpressionException e) {
        throw new CompilationException(__msgs.errUnexpectedCompilationError(e.getMessage()), e);
    }
}