Example usage for javax.xml.xpath XPath compile

List of usage examples for javax.xml.xpath XPath compile

Introduction

In this page you can find the example usage for javax.xml.xpath XPath compile.

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Returns a node from the xml document defined by the Xpath
 *
 * @param elements/*from  ww w. j  a  va2s  . c  om*/
 * @param xPath
 * @return
 */
public static Node xPathEvaluateNode(List<Element> elements, String xPath) throws MetsExportException {
    Document document = null;
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e1);
    }

    for (Element element : elements) {
        Node newNode = element.cloneNode(true);
        document.adoptNode(newNode);
        document.appendChild(newNode);
    }
    XPath xpathObject = XPathFactory.newInstance().newXPath();

    try {
        return (Node) xpathObject.compile(xPath).evaluate(document, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e);
    }
}

From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java

private String getConfigValue(String setting, String name, Document doc) throws XPathExpressionException {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression userExpr = xpath
            .compile("tagme/setting[@name=\"" + setting + "\"]/param[@name=\"" + name + "\"]/@value");
    return userExpr.evaluate(doc);
}

From source file:com.dianping.zebra.shard.jdbc.base.SingleDBBaseTestCase.java

protected void parseCreateTableScriptFile() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document configDoc = builder/*from  w w w.j a v a2 s .  com*/
            .parse(SingleDBBaseTestCase.class.getClassLoader().getResourceAsStream(getCreateTableScriptPath()));
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    NodeList tableScriptList = (NodeList) xpath.compile("/tables/table").evaluate(configDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < tableScriptList.getLength(); i++) {
        SingleCreateTableScriptEntry entry = new SingleCreateTableScriptEntry();
        Element ele = (Element) tableScriptList.item(i);
        entry.setTableName(ele.getAttribute("name"));
        entry.setCreateTableScript(ele.getTextContent());
        createdTableList.add(entry);
    }
}

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   ww w  .  j  av a2  s .  co 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:at.sti2.spark.handler.ImpactoriumHandler.java

public String extractInfoObjectIdentifier(String infoObjectResponse) {

    String reportId = null;/*from ww w.  j a v  a 2  s  .  co m*/

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //dbf.setNamespaceAware(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8")));

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//info-object");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;
        Node item = nodes.item(0);
        if (item != null) {
            NamedNodeMap attributesMap = item.getAttributes();
            Node idAttribute = attributesMap.getNamedItem("id");
            reportId = idAttribute.getNodeValue();
        }

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return reportId;
}

From source file:org.ow2.chameleon.fuchsia.push.base.subscriber.tool.HubDiscovery.java

public String hasHub(Document doc) {
    String hub = null;/*from   ww  w  .j av a  2s. co m*/

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    XPathExpression xPathExpression;

    try {
        xPathExpression = xPath.compile("/feed/link[@rel='hub']/@href");
        hub = xPathExpression.evaluate(doc);
        if ((hub == null) || (hub.length() == 0)) {
            xPathExpression = xPath.compile("//link[@rel='hub']/@href");
            hub = xPathExpression.evaluate(doc);
        }

        if (hub.length() == 0) {
            return null;
        }

        return hub;

    } catch (XPathExpressionException e) {
        LOGGER.error("XPathExpression invalid", e);
        return null;
    }
}

From source file:org.ow2.chameleon.fuchsia.push.base.subscriber.tool.HubDiscovery.java

public String hasTopic(Document doc) {
    String topic;//from w ww . j ava  2s.co  m

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    XPathExpression xPathExpression;

    try {
        xPathExpression = xPath.compile("/feed/link[@rel='self']/@href");
        topic = xPathExpression.evaluate(doc);
        if ((topic == null) || (topic.length() == 0)) {
            xPathExpression = xPath.compile("//link[@rel='self']/@href");
            topic = xPathExpression.evaluate(doc);
        }

        if (topic.length() == 0) {
            return null;
        }
        return topic;

    } catch (XPathExpressionException e) {
        LOGGER.error("Invalid XpathExpression", e);
        return null;
    }

}

From source file:org.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetriever.java

/**
 * Loads the portlet.xml file using the configured <tt>ResourceLoader</tt> and
 * parses the role-name elements from it, using these as the set of <tt>mappableAttributes</tt>.
 *///  w  w  w.  j ava  2s  .  c  o  m
public void afterPropertiesSet() throws Exception {
    Resource portletXml = resourceLoader.getResource("/WEB-INF/portlet.xml");
    Document doc = getDocument(portletXml.getInputStream());

    final XPathExpression roleNamesExpression;
    if (portletConfig == null) {
        final XPathFactory xPathFactory = XPathFactory.newInstance();

        final XPath xPath = xPathFactory.newXPath();
        roleNamesExpression = xPath.compile("/portlet-app/portlet/security-role-ref/role-name");
    } else {
        final XPathFactory xPathFactory = XPathFactory.newInstance();
        xPathFactory.setXPathVariableResolver(new XPathVariableResolver() {
            @Override
            public Object resolveVariable(QName variableName) {
                if ("portletName".equals(variableName.getLocalPart())) {
                    return portletConfig.getPortletName();
                }

                return null;
            }
        });
        final XPath xPath = xPathFactory.newXPath();
        roleNamesExpression = xPath
                .compile("/portlet-app/portlet[portlet-name=$portletName]/security-role-ref/role-name");
    }

    final NodeList securityRoles = (NodeList) roleNamesExpression.evaluate(doc, XPathConstants.NODESET);
    final Set<String> roleNames = new HashSet<String>();

    for (int i = 0; i < securityRoles.getLength(); i++) {
        Element secRoleElt = (Element) securityRoles.item(i);
        String roleName = secRoleElt.getTextContent().trim();
        roleNames.add(roleName);
        logger.info("Retrieved role-name '" + roleName + "' from portlet.xml");
    }

    if (roleNames.isEmpty()) {
        logger.info("No security-role-ref elements found in " + portletXml
                + (portletConfig == null ? "" : " for portlet " + portletConfig.getPortletName()));
    }

    mappableAttributes = Collections.unmodifiableSet(roleNames);
}

From source file:org.openhim.mediator.denormalization.CSDRequestActor.java

private void processHTTPResponse(MediatorHTTPResponse response) {
    BaseResolveIdentifier originalRequest = originalRequests
            .remove(response.getOriginalRequest().getCorrelationId());
    String csdResponse = response.getBody();

    try {/*from   www . ja  v a  2s. c o  m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(IOUtils.toInputStream(csdResponse));
        XPath xpath = XPathFactory.newInstance().newXPath();
        String resolvedId = xpath.compile(getXPAthExpressionForQueryType(originalRequest)).evaluate(doc);

        BaseResolveIdentifierResponse finalResponse = buildResponse(originalRequest, resolvedId);
        originalRequest.getRespondTo().tell(finalResponse, getSelf());
    } catch (ValidationException ex) {
        FinishRequest fr = new FinishRequest(ex.getMessage(), "text/plain", HttpStatus.SC_BAD_REQUEST);
        originalRequest.getRequestHandler().tell(fr, getSelf());
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
        originalRequest.getRequestHandler().tell(new ExceptError(ex), getSelf());
    }
}

From source file:nl.surfnet.sab.SabResponseParser.java

/**
 * Check that response contains the success status. Throw IOException with message otherwise.
 *///ww  w  .  j av a 2  s . c om
private void validateStatus(Document document, XPath xpath) throws XPathExpressionException, IOException {

    XPathExpression statusCodeExpression = xpath.compile(XPATH_STATUSCODE);
    String statusCode = (String) statusCodeExpression.evaluate(document, XPathConstants.STRING);

    if (SAMLP_SUCCESS.equals(statusCode)) {
        // Success, validation returns.
        return;
    } else {
        // Status message is only set if status code not 'success'.
        XPathExpression statusMessageExpression = xpath.compile(XPATH_STATUSMESSAGE);
        String statusMessage = (String) statusMessageExpression.evaluate(document, XPathConstants.STRING);

        if (SAMLP_RESPONDER.equals(statusCode) && statusMessage.startsWith(NOT_FOUND_MESSAGE_PREFIX)) {
            LOG.debug(
                    "Given nameId not found in SAB. Is regarded by us as 'valid' response, although server response indicates a server error.");
            return;
        } else {
            throw new IOException("Unsuccessful status. Code: '" + statusCode + "', message: " + statusMessage);
        }
    }
}