Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:org.opencastproject.remotetest.util.WorkflowUtils.java

/**
 * Parses the workflow instance represented by <code>xml</code> and extracts the workflow state.
 * //ww  w  .j  a  va  2  s .  c om
 * @param xml
 *          the workflow instance
 * @return the workflow state
 * @throws Exception
 *           if parsing fails
 */
public static String getWorkflowState(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
            .getAttribute("state");
}

From source file:org.opencastproject.remotetest.server.perf.ConcurrentWorkflowTest.java

protected String getWorkflowInstanceStatus(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from w w  w  . j  av  a 2 s  .  com
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
            .getAttribute("state");
}

From source file:com.amalto.core.storage.datasource.DataSourceFactory.java

private static DataSource getDataSourceConfiguration(Node document, String name, String path)
        throws XPathExpressionException {
    Node dataSource = (Node) evaluate(document, path, XPathConstants.NODE);
    if (dataSource == null) {
        return null;
    }//from   w  w  w. j a v  a  2s  .co m
    String type = (String) evaluate(dataSource, "type", XPathConstants.STRING); //$NON-NLS-1$
    // Invoke extensions for datasource extensions
    ServiceLoader<DataSourceExtension> extensions = ServiceLoader.load(DataSourceExtension.class);
    if (LOGGER.isDebugEnabled()) {
        StringBuilder extensionsAsString = new StringBuilder();
        int i = 0;
        for (DataSourceExtension extension : extensions) {
            extensionsAsString.append(extension.getClass().getName()).append(' ');
            i++;
        }
        if (i == 0) {
            LOGGER.debug("No datasource extension found");
        } else {
            LOGGER.debug("Found datasource extensions (" + i + " found): " + extensionsAsString);
        }
    }
    for (DataSourceExtension extension : extensions) {
        if (extension.accept(type)) {
            return extension.create(dataSource, name);
        } else {
            LOGGER.debug("Extension '" + extension + "' is not eligible for datasource type '" + type + "'.");
        }
    }
    throw new NotImplementedException("No support for type '" + type + "'.");
}

From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java

/**
 * Returns the query result as a <code>Node</code> or <code>null</code> if the
 * xpath expression doesn't yield a resulting node.
 * /*from w  w  w .j  ava 2 s.  c o  m*/
 * @param node
 *          the context node
 * @param xpathExpression
 *          the xpath expression
 * @param processor
 *          the xpath processor
 * @return the selected node
 */
public static Node select(Node node, String xpathExpression, XPath processor) {
    if (node == null || processor == null) {
        return null;
    }
    try {
        Node result = (Node) processor.evaluate(xpathExpression, node, XPathConstants.NODE);

        // If we are running in test mode, we may neglect namespaces
        if (result == null) {
            NamespaceContext ctx = processor.getNamespaceContext();
            if (ctx instanceof XPathNamespaceContext && ((XPathNamespaceContext) ctx).isTest()) {
                if (xpathExpression.matches("(.*)[a-zA-Z0-9]+\\:[a-zA-Z0-9]+(.*)")) {
                    String xpNs = xpathExpression.replaceAll("[a-zA-Z0-9]+\\:", "");
                    result = (Node) processor.evaluate(xpNs, node, XPathConstants.NODE);
                }
            }
        }
        return result;
    } catch (XPathExpressionException e) {
        logger.warn("Error when selecting '{}' from {}", new Object[] { xpathExpression, node, e });
        return null;
    }
}

From source file:com.ephesoft.dcma.util.OCREngineUtil.java

private static void setWordNodeTextContent(XPathExpression xOcrWordExpr, XPathExpression ocrXWordExpr,
        NodeList wordList, int wordNodeIndex) throws XPathExpressionException {
    Node wordNode = wordList.item(wordNodeIndex);
    if (wordNode != null) {
        Node word = (Node) xOcrWordExpr.evaluate(wordNode, XPathConstants.NODE);
        if (word != null) {
            wordNode.setTextContent(word.getTextContent());
        } else {//  ww w . j  a  v a  2s .c o m
            word = (Node) ocrXWordExpr.evaluate(wordNode, XPathConstants.NODE);
            if (word != null) {
                wordNode.setTextContent(word.getTextContent());
            }
        }
    }
}

From source file:com.esri.gpt.server.openls.provider.services.route.DetermineRouteProvider.java

/**
 * /*from  w ww  .  j  a  v  a  2  s .co m*/
 * @param context
 * @param ndReq
 * @param xpath
 * @throws Exception
 */
private void parseRequest(OperationContext context, Node ndReq, XPath xpath) throws Exception {
    DetermineRouteParams routeParams = new DetermineRouteParams();
    Node ndRoutePlan = (Node) xpath.evaluate("xls:RoutePlan", ndReq, XPathConstants.NODE);
    if (ndRoutePlan != null) {
        RoutePlan routePlan = new RoutePlan();
        Node ndRoutePreference = (Node) xpath.evaluate("xls:RoutePreference", ndRoutePlan, XPathConstants.NODE);
        if (ndRoutePreference != null) {
            routePlan.setRoutePreference(ndRoutePreference.getTextContent());
        }
        Node ndWayPointList = (Node) xpath.evaluate("xls:WayPointList", ndRoutePlan, XPathConstants.NODE);
        if (ndWayPointList != null) {
            HashMap<String, Point> wayPointList = new HashMap<String, Point>();
            Node ndStartPoint = (Node) xpath.evaluate("xls:StartPoint", ndWayPointList, XPathConstants.NODE);
            if (ndStartPoint != null) {
                Node ndStartPOI = (Node) xpath.evaluate("xls:POI", ndStartPoint, XPathConstants.NODE);
                if (ndStartPOI != null) {
                    ndStartPoint = ndStartPOI;
                }
                Node ndStartPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndStartPoint,
                        XPathConstants.NODE);
                Point point = new Point();
                if (ndStartPos != null) {
                    String[] coords = ndStartPos.getTextContent().split(" ");
                    point.setX(coords[0]);
                    point.setY(coords[1]);
                } else {
                    geocode(context, ndStartPoint, xpath, point);
                }
                wayPointList.put("start", point);
            }
            Node ndViaPoint = (Node) xpath.evaluate("xls:ViaPoint", ndWayPointList, XPathConstants.NODE);
            if (ndViaPoint != null) {
                Node ndViaPOI = (Node) xpath.evaluate("xls:POI", ndStartPoint, XPathConstants.NODE);
                if (ndViaPOI != null) {
                    ndViaPoint = ndViaPOI;
                }
                Point point = new Point();
                Node ndViaPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndViaPoint,
                        XPathConstants.NODE);
                if (ndViaPos != null) {
                    String[] coords = ndViaPos.getTextContent().split(" ");
                    point.setX(coords[0]);
                    point.setY(coords[1]);
                } else {
                    geocode(context, ndViaPoint, xpath, point);
                }
                wayPointList.put("via", point);
            }
            Node ndEndPoint = (Node) xpath.evaluate("xls:EndPoint", ndWayPointList, XPathConstants.NODE);
            if (ndEndPoint != null) {
                Node ndEndPOI = (Node) xpath.evaluate("xls:POI", ndEndPoint, XPathConstants.NODE);
                if (ndEndPOI != null) {
                    ndEndPoint = ndEndPOI;
                }
                Node ndEndPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndEndPoint,
                        XPathConstants.NODE);
                Point point = new Point();
                if (ndEndPos != null) {
                    String[] coords = ndEndPos.getTextContent().split(" ");
                    point.setX(coords[0]);
                    point.setY(coords[1]);
                } else {
                    geocode(context, ndEndPoint, xpath, point);
                }
                wayPointList.put("end", point);
            }
            routePlan.setWayPointList(wayPointList);
        }

        Node ndAvoidList = (Node) xpath.evaluate("xls:AvoidList", ndRoutePlan, XPathConstants.NODE);
        if (ndAvoidList != null) {
            Node ndAvoidPOI = (Node) xpath.evaluate("xls:POI", ndAvoidList, XPathConstants.NODE);
            if (ndAvoidPOI != null) {
                ndAvoidList = ndAvoidPOI;
            }
            HashMap<String, Point> avoidPointList = new HashMap<String, Point>();
            Node ndStartPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndAvoidList,
                    XPathConstants.NODE);
            Point point = new Point();
            if (ndStartPos != null) {
                String[] coords = ndStartPos.getTextContent().split(" ");
                point.setX(coords[0]);
                point.setY(coords[1]);
            } else {
                geocode(context, ndAvoidList, xpath, point);
            }
            avoidPointList.put("avoid", point);
            routePlan.setAvoidPointList(avoidPointList);
        }

        routeParams.setRoutePlan(routePlan);
    }
    Node ndRouteInst = (Node) xpath.evaluate("xls:RouteInstructionsRequest", ndReq, XPathConstants.NODE);
    if (ndRouteInst != null) {
        RouteInstructionsRequest routeInst = new RouteInstructionsRequest();
        String format = (String) xpath.evaluate("@format", ndRouteInst, XPathConstants.STRING);
        String provideGeometry = (String) xpath.evaluate("@provideGeometry", ndRouteInst,
                XPathConstants.STRING);
        routeInst.setFormat(format);
        routeInst.setProvideGeometry(provideGeometry);
        routeParams.setRouteInstructions(routeInst);
    }
    Node ndRouteMap = (Node) xpath.evaluate("xls:RouteMapRequest", ndReq, XPathConstants.NODE);
    if (ndRouteMap != null) {
        RouteMap routeMap = new RouteMap();
        Node ndOutput = (Node) xpath.evaluate("xls:Output", ndRouteMap, XPathConstants.NODE);
        if (ndOutput != null) {
            ImageOutput imgOutput = new ImageOutput();
            Output output = new Output();
            String format = (String) xpath.evaluate("@format", ndOutput, XPathConstants.STRING);
            String width = (String) xpath.evaluate("@width", ndOutput, XPathConstants.STRING);
            String height = (String) xpath.evaluate("@height", ndOutput, XPathConstants.STRING);
            output.setFormat(format);
            output.setWidth(width);
            output.setHeight(height);
            imgOutput.setOutput(output);
            routeMap.setImageOutput(imgOutput);
        }
        routeParams.setRouteMap(routeMap);
    }
    context.getRequestOptions().setDetermineRouteParams(routeParams);

}

From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

/**
 * Close the specified stage./*from ww w.  ja  va2  s  .  co  m*/
 * 
 * @param stage the stage to close.
 * @throws StageException if any issue occurred whilst closing the stage.
 */
public void closeStage(Stage stage, String description) throws StageException {
    performStageAction(StageAction.CLOSE, stage, description);
    if (isAsyncClose()) {
        waitForActionToComplete(stage);
        // check the action completed successfully and no rules failed.
        URL url = getActivityURL(stage);
        Document doc = getDocument(url);
        // last stagingActivity that was a close
        String xpathExpr = "(/list/stagingActivity[name='close'])[last()]";
        Node lastCloseNode = (Node) evaluateXPath(xpathExpr, doc, XPathConstants.NODE);
        if (lastCloseNode == null) {
            throw new StageException("Stage activity completed but no close action was recorded!");
        }
        Node closed = (Node) evaluateXPath("events/stagingActivityEvent[name='repositoryClosed']",
                lastCloseNode, XPathConstants.NODE);
        if (closed != null) {
            // we have successfully closed the repository
            return;
        }
        Node failed = (Node) evaluateXPath("events/stagingActivityEvent[name='repositoryCloseFailed']",
                lastCloseNode, XPathConstants.NODE);
        if (failed == null) {
            throw new StageException(
                    "Close stage action was signalled as completed, but was not recorded as either failed or succeeded!");
        }
        StringBuilder failureMessage = new StringBuilder("Closing stage ").append(stage.getStageID())
                .append(" failed.\n");
        String cause = (String) evaluateXPath("properties/stagingProperty[name='cause']/value", failed,
                XPathConstants.STRING);
        failureMessage.append('\t').append(cause);
        NodeList failedRules = (NodeList) evaluateXPath(
                "events/stagingActivityEvent[name='ruleFailed']/properties/stagingProperty[name='failureMessage']/value",
                lastCloseNode, XPathConstants.NODESET);
        for (int i = 0; i < failedRules.getLength(); i++) {
            failureMessage.append("\n\t");
            failureMessage.append(failedRules.item(i).getTextContent());
        }
        throw new StageException(failureMessage.toString());
    }
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilderTest.java

@Test
public void testCreateCejshXml_TitleVolumeIssue() throws Exception {
    CejshConfig conf = new CejshConfig();
    CejshBuilder cb = new CejshBuilder(conf);
    Document articleDoc = cb.getDocumentBuilder()
            .parse(CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
    // issn must match some cejsh_journals.xml/cejsh/journal[@issn=$issn]
    final String pkgIssn = "0231-5955";
    Issue issue = new Issue();
    issue.setIssn(pkgIssn);/*w  w w  .j  av  a2  s .c  om*/
    issue.setIssueId("uuid-issue");
    issue.setIssueNumber("issue1");
    Volume volume = new Volume();
    volume.setVolumeId("uuid-volume");
    volume.setVolumeNumber("volume1");
    volume.setYear("1985");
    Article article = new Article(null, articleDoc.getDocumentElement(), null);
    cb.setIssue(issue);
    cb.setVolume(volume);

    Document articleCollectionDoc = cb.mergeElements(Collections.singletonList(article));
    DOMSource cejshSource = new DOMSource(articleCollectionDoc);
    DOMResult cejshResult = new DOMResult();
    //        dump(cejshSource);

    TransformErrorListener xslError = cb.createCejshXml(cejshSource, cejshResult);
    assertEquals(Collections.emptyList(), xslError.getErrors());
    final Node cejshRootNode = cejshResult.getNode();
    //        dump(new DOMSource(cejshRootNode));

    List<String> errors = cb.validateCejshXml(new DOMSource(cejshRootNode));
    assertEquals(Collections.emptyList(), errors);

    XPath xpath = ProarcXmlUtils.defaultXPathFactory().newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("b", CejshBuilder.NS_BWMETA105));
    assertNotNull(
            xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.ebfd7bf2-169d-476e-a230-0cc39f01764c']",
                    cejshRootNode, XPathConstants.NODE));
    assertEquals("volume1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-volume']/b:name",
            cejshRootNode, XPathConstants.STRING));
    assertEquals("issue1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-issue']/b:name",
            cejshRootNode, XPathConstants.STRING));
    assertEquals("1985", xpath.evaluate(
            "/b:bwmeta/b:element[@id='bwmeta1.element.9358223b-b135-388f-a71e-24ac2c8422c7-1985']/b:name",
            cejshRootNode, XPathConstants.STRING));
}

From source file:com.cordys.coe.ac.httpconnector.samples.JIRAResponseHandler.java

/**
 * This method checks the HTML for errors during processing.
 * //from   www . j  av a2  s  .com
 * @param document
 *            The HTML document.
 * @param httpMethod
 *            The actual HTTP method that was executed.
 * 
 * @throws HandlerException
 *             In case the response contains any functional errors.
 * @throws XPathExpressionException
 *             In case one of the XPaths fail.
 */
protected void checkErrors(org.w3c.dom.Document document, HttpMethod httpMethod)
        throws HandlerException, XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate("//span[@class='errMsg']/text()", document,
            XPathConstants.NODESET);
    int length = nodeList.getLength();

    if (length != 0) {
        // The first error message found will be used.
        HandlerException he = new HandlerException(
                HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML,
                nodeList.item(0).getNodeValue());

        for (int i = 0; i < length; i++) {
            Node node = nodeList.item(i);
            he.addAdditionalErrorMessage(node.getNodeValue());
        }
        throw he;
    }

    // There is another possibility of which errors might be returned. There
    // is a td with
    // class formErrors. And it that holds the errors as list items.
    nodeList = (NodeList) xpath.evaluate("//td[@class='formErrors']/div[@class='errorArea']/ul/li/text()",
            document, XPathConstants.NODESET);
    length = nodeList.getLength();

    if (length != 0) {
        // The first error message found will be used.
        HandlerException he = new HandlerException(
                HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML,
                nodeList.item(0).getNodeValue());

        for (int i = 0; i < length; i++) {
            Node node = nodeList.item(i);
            he.addAdditionalErrorMessage(node.getNodeValue());
        }
        throw he;
    }

    if (httpMethod.getStatusCode() == 500) {
        // Find the short description
        Node n = (Node) xpath.evaluate("//b[.='Cause: ']", document, XPathConstants.NODE);
        String shortError = n.getNextSibling().getNextSibling().getNodeValue().trim();

        // The first error message found will be used.
        HandlerException he = new HandlerException(
                HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML,
                "System Error: " + shortError);

        // Find the stacktrace if available.
        he.addAdditionalErrorMessage(
                (String) xpath.evaluate("//pre[@id='stacktrace']/text()", document, XPathConstants.STRING));

        throw he;
    }
}

From source file:com.espertech.esper.event.xml.SimpleXMLEventType.java

protected EventPropertyGetter doResolvePropertyGetter(String propertyExpression) {
    EventPropertyGetter getter = propertyGetterCache.get(propertyExpression);
    if (getter != null) {
        return getter;
    }/*  w ww  .ja  va  2 s  . co m*/

    if (!this.getConfigurationEventTypeXMLDOM().isXPathPropertyExpr()) {
        Property prop = PropertyParser.parse(propertyExpression, false);
        getter = prop.getGetterDOM();
        if (!prop.isDynamic()) {
            getter = new DOMConvertingGetter(propertyExpression, (DOMPropertyGetter) getter, String.class);
        }
    } else {
        XPathExpression xPathExpression;
        String xPathExpr;
        boolean isDynamic;
        try {
            Tree ast = PropertyParser.parse(propertyExpression);
            isDynamic = PropertyParser.isPropertyDynamic(ast);

            xPathExpr = SimpleXMLPropertyParser.parse(ast, propertyExpression, getRootElementName(),
                    defaultNamespacePrefix, isResolvePropertiesAbsolute);
            XPath xpath = getXPathFactory().newXPath();
            xpath.setNamespaceContext(namespaceContext);
            if (log.isInfoEnabled()) {
                log.info("Compiling XPath expression for property '" + propertyExpression + "' as '" + xPathExpr
                        + "'");
            }
            xPathExpression = xpath.compile(xPathExpr);
        } catch (XPathExpressionException e) {
            throw new EPException(
                    "Error constructing XPath expression from property name '" + propertyExpression + '\'', e);
        }

        QName xPathReturnType;
        if (isDynamic) {
            xPathReturnType = XPathConstants.NODE;
        } else {
            xPathReturnType = XPathConstants.STRING;
        }
        getter = new XPathPropertyGetter(propertyExpression, xPathExpr, xPathExpression, xPathReturnType, null,
                null);
    }

    // no fragment factory, fragments not allowed
    propertyGetterCache.put(propertyExpression, getter);
    return getter;
}