Example usage for javax.xml.xpath XPath setNamespaceContext

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

Introduction

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

Prototype

public void setNamespaceContext(NamespaceContext nsContext);

Source Link

Document

Establish a namespace context.

Usage

From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java

/**
 * very useful: {@link http// w  ww.  ja va  2  s .c  o m
 * ://www.ibm.com/developerworks/library/x-javaxpathapi.html}
 * 
 * @param doc
 * @param path
 * @param scale
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
private String extractTextInternal(Document doc, String path)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    XPathFactory factory = XPathFactory.newInstance();

    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expr = xpath.compile(path);
    try {
        String result = (String) expr.evaluate(doc, XPathConstants.STRING);
        return result;
    } catch (Exception e) {
        log.error("XML extraction for path " + path + " failed: " + e.getMessage(), e);
        return "XML extraction for path " + path + " failed: " + e.getMessage();
    }
}

From source file:org.orcid.examples.jopmts.mvc.OrcidController.java

private XPath createXPath() {
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(createNamespaceContext());
    return xpath;
}

From source file:org.jboss.spring.factory.NamedXmlBeanFactory.java

private void initializeNames(Resource resource) {
    try {//  ww w  .  j  ava  2  s  . c  o  m
        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
                return "http://www.springframework.org/schema/beans";
            }

            @Override
            public String getPrefix(String namespaceURI) {
                return "beans";
            }

            @Override
            public Iterator getPrefixes(String namespaceURI) {
                return Collections.singleton("beans").iterator();
            }
        });
        String expression = "/beans:beans/beans:description";
        InputSource inputSource = new InputSource(resource.getInputStream());
        String description = xPath.evaluate(expression, inputSource);
        if (description != null) {
            Matcher bfm = Pattern.compile(Constants.BEAN_FACTORY_ELEMENT).matcher(description);
            if (bfm.find()) {
                this.name = bfm.group(1);
            }
            Matcher pbfm = Pattern.compile(Constants.PARENT_BEAN_FACTORY_ELEMENT).matcher(description);
            if (pbfm.find()) {
                String parentName = pbfm.group(1);
                try {
                    this.setParentBeanFactory((BeanFactory) Util.lookup(parentName, BeanFactory.class));
                } catch (Exception e) {
                    throw new BeanDefinitionStoreException(
                            "Failure during parent bean factory JNDI lookup: " + parentName, e);
                }
            }
            Matcher inst = Pattern.compile(Constants.INSTANTIATION_ELEMENT).matcher(description);
            if (inst.find()) {
                instantiate = Boolean.parseBoolean(inst.group(1));
            }
        }
        if (this.name == null || "".equals(StringUtils.trimAllWhitespace(this.name))) {
            this.name = this.defaultName;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.codice.ddf.admin.sources.opensearch.OpenSearchSourceUtils.java

public UrlAvailability getUrlAvailability(String url, String un, String pw) {
    UrlAvailability result = new UrlAvailability(url);
    boolean queryResponse;
    int status;/*from w w  w. j  av a  2 s  . c o m*/
    String contentType;
    HttpGet request = new HttpGet(url + SIMPLE_QUERY_PARAMS);
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;

    if (url.startsWith("https") && un != null && pw != null) {
        byte[] auth = Base64.encodeBase64((un + ":" + pw).getBytes());
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    try {
        client = getCloseableHttpClient(false);
        response = client.execute(request);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document responseXml = builder.parse(response.getEntity().getContent());
        queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                XPathConstants.BOOLEAN);
        status = response.getStatusLine().getStatusCode();
        contentType = response.getEntity().getContentType().getValue();
        if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
            return result.trustedCertAuthority(true).certError(false).available(true);
        } else {
            return result.trustedCertAuthority(true).certError(false).available(false);
        }
    } catch (SSLPeerUnverifiedException e) {
        // This is the hostname != cert name case - if this occurs, the URL's SSL cert configuration
        // is incorrect, or a serious network security issue has occurred.
        return result.trustedCertAuthority(false).certError(true).available(false);
    } catch (Exception e) {
        try {
            closeClientAndResponse(client, response);
            client = getCloseableHttpClient(true);
            response = client.execute(request);
            status = response.getStatusLine().getStatusCode();
            contentType = response.getEntity().getContentType().getValue();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document responseXml = builder.parse(response.getEntity().getContent());
            queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                    XPathConstants.BOOLEAN);
            if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
                return result.trustedCertAuthority(false).certError(false).available(true);
            }
        } catch (Exception e1) {
            return result.trustedCertAuthority(false).certError(false).available(false);
        }
    } finally {
        closeClientAndResponse(client, response);
    }
    return result;
}

From source file:org.codice.ddf.admin.sources.wfs.WfsSourceUtils.java

public Optional<WfsSourceConfiguration> getPreferredConfig(WfsSourceConfiguration configuration) {
    WfsSourceConfiguration config = new WfsSourceConfiguration(configuration);
    String wfsVersionExp = "/wfs:WFS_Capabilities/attribute::version";
    HttpGet getCapabilitiesRequest = new HttpGet(
            config.endpointUrl() + GET_CAPABILITIES_PARAMS + ACCEPT_VERSION_PARAMS);
    if (configuration.endpointUrl().startsWith("https") && config.sourceUserName() != null
            && config.sourceUserPassword() != null) {
        byte[] auth = Base64
                .encodeBase64((config.sourceUserName() + ":" + config.sourceUserPassword()).getBytes());
        getCapabilitiesRequest.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }// ww  w. ja v a2s.  c  o  m
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try {
        client = getCloseableHttpClient(true);
        response = client.execute(getCapabilitiesRequest);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document capabilitiesXml = builder.parse(response.getEntity().getContent());
        String wfsVersion = xpath.compile(wfsVersionExp).evaluate(capabilitiesXml);
        switch (wfsVersion) {
        case "2.0.0":
            return Optional.of((WfsSourceConfiguration) config.factoryPid(WFS2_FACTORY_PID));
        case "1.0.0":
            return Optional.of((WfsSourceConfiguration) config.factoryPid(WFS1_FACTORY_PID));
        default:
            return Optional.empty();
        }
    } catch (Exception e) {
        return Optional.empty();
    } finally {
        closeClientAndResponse(client, response);
    }
}

From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java

public HashMap<String, String> extractValues(Document xml, String path) {
    try {/*from ww  w  . j  ava  2  s . co m*/
        HashMap<String, String> resultMap = new HashMap<String, String>();

        XPathFactory factory = XPathFactory.newInstance();

        XPath xpath = factory.newXPath();
        xpath.setNamespaceContext(namespaceContext);
        XPathExpression expr = xpath.compile(path);

        NodeList list = (NodeList) expr.evaluate(xml, XPathConstants.NODESET);
        if (list != null) {
            for (int i = 0; i < list.getLength(); i++) {
                Node n = list.item(i);
                String content = n.getTextContent();
                if (content != null) {
                    resultMap.put(n.getLocalName(), content);
                }
            }
        }
        return resultMap;
    } catch (Exception e) {
        log.error("Could not parse XML " + " searching for path " + path + ": " + e.getMessage(), e);
        return null;
    }
}

From source file:org.jboss.spring.factory.NamedXmlApplicationContext.java

private void initializeNames(Resource resource) {
    try {//from ww  w. j  ava 2 s . c o m
        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
                return "http://www.springframework.org/schema/beans";
            }

            @Override
            public String getPrefix(String namespaceURI) {
                return "beans";
            }

            @Override
            public Iterator getPrefixes(String namespaceURI) {
                return Collections.singleton("beans").iterator();
            }
        });
        String expression = "/beans:beans/beans:description";
        InputSource inputSource = new InputSource(resource.getInputStream());
        String description = xPath.evaluate(expression, inputSource);
        if (description != null) {
            Matcher bfm = Pattern.compile(Constants.BEAN_FACTORY_ELEMENT).matcher(description);
            if (bfm.find()) {
                this.name = bfm.group(1);
            }
            Matcher pbfm = Pattern.compile(Constants.PARENT_BEAN_FACTORY_ELEMENT).matcher(description);
            if (pbfm.find()) {
                String parentName = pbfm.group(1);
                try {
                    this.getBeanFactory()
                            .setParentBeanFactory((BeanFactory) Util.lookup(parentName, BeanFactory.class));
                } catch (Exception e) {
                    throw new BeanDefinitionStoreException(
                            "Failure during parent bean factory JNDI lookup: " + parentName, e);
                }
            }
        }
        if (this.name == null || "".equals(StringUtils.trimAllWhitespace(this.name))) {
            this.name = this.defaultName;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.javacrumbs.springws.test.util.DefaultXmlUtil.java

@SuppressWarnings("unchecked")
public boolean isSoap(Document document) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(SOAP_NAMESPACE_CONTEXT);
    try {/* www .j av  a 2  s . c o  m*/
        for (Iterator iterator = SOAP_NAMESPACE_CONTEXT.getBoundPrefixes(); iterator.hasNext();) {
            String prefix = (String) iterator.next();
            if ((Boolean) xpath.evaluate("/" + prefix + ":Envelope", document, XPathConstants.BOOLEAN)) {
                return true;
            }
        }
    } catch (XPathExpressionException e) {
        logger.warn(e);
    }
    return false;
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionNamespaceContextHelperTest.java

@Test
public void testReturnNamespaceMapFromNode() throws Exception {
    //Retrieve ER xpath context
    XPath xpath;
    xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new EntityResolutionNamespaceContext());

    //Get the test attribute parameters configuration
    InputStream attributeParametersStream = getClass().getResourceAsStream("/xml/TestAttributeParameters.xml");
    assertNotNull(attributeParametersStream);

    //Convert to DOM document
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);

    Document attributeParametersDocument = converter.toDOMDocument(attributeParametersStream);

    NodeList parameterNodes = null;

    //Perform Xpath to retrieve attribute parameters
    parameterNodes = (NodeList) xpath.evaluate("er-ext:AttributeParameter",
            attributeParametersDocument.getDocumentElement(), XPathConstants.NODESET);

    //Loop through attribute parameters to retrieve namespace map associated with attribute xpath
    for (int i = 0; i < parameterNodes.getLength(); i++) {
        Node node = parameterNodes.item(i);

        String attributeXpathValue = xpath.evaluate("er-ext:AttributeXPath", node);
        Map<String, String> namespaceMap = EntityResolutionNamespaceContextHelpers
                .returnNamespaceMapFromNode(attributeXpathValue, node);

        for (Map.Entry<String, String> entry : namespaceMap.entrySet()) {
            LOG.debug("Namespace Map Entry, Prefix : " + entry.getKey() + " Namespace : " + entry.getValue());
        }/*from   w w  w  .  j  a  va2 s . c  o m*/

        if (attributeXpathValue.equals("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName")) {
            assertEquals("http://niem.gov/niem/niem-core/2.0", namespaceMap.get("nc"));
            assertEquals("http://local.org/IEPD/Extensions/PersonSearchResults/1.0", namespaceMap.get("ext"));
        }

        if (attributeXpathValue.equals("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName")) {
            assertEquals("http://niem.gov/niem/niem-core/2.0", namespaceMap.get("nc"));
            assertEquals("http://local.org/IEPD/Extensions/PersonSearchResults/1.0", namespaceMap.get("ext"));
        }

    }
}

From source file:org.codice.ddf.admin.sources.csw.CswSourceUtils.java

public Optional<CswSourceConfiguration> getPreferredConfig(CswSourceConfiguration config) {
    CswSourceConfiguration preferred = new CswSourceConfiguration(config);
    HttpGet getCapabilitiesRequest = new HttpGet(preferred.endpointUrl() + GET_CAPABILITIES_PARAMS);
    CloseableHttpClient client = null;//from  w w w.  j av a  2  s  .co m
    CloseableHttpResponse response = null;
    if (config.endpointUrl().startsWith("https") && config.sourceUserName() != null
            && config.sourceUserPassword() != null) {
        byte[] auth = Base64
                .encodeBase64((config.sourceUserName() + ":" + config.sourceUserPassword()).getBytes());
        getCapabilitiesRequest.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    try {
        client = getCloseableHttpClient(true);
        response = client.execute(getCapabilitiesRequest);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document capabilitiesXml = builder.parse(response.getEntity().getContent());
        if ((Boolean) xpath.compile(HAS_CATALOG_METACARD_EXP).evaluate(capabilitiesXml,
                XPathConstants.BOOLEAN)) {
            return Optional.of((CswSourceConfiguration) preferred.factoryPid(CSW_PROFILE_FACTORY_PID));
        } else if ((Boolean) xpath.compile(HAS_GMD_ISO_EXP).evaluate(capabilitiesXml, XPathConstants.BOOLEAN)) {
            return Optional.of(((CswSourceConfiguration) preferred.factoryPid(CSW_GMD_FACTORY_PID))
                    .outputSchema(GMD_OUTPUT_SCHEMA));
        } else {
            return Optional.of(((CswSourceConfiguration) (preferred.factoryPid(CSW_SPEC_FACTORY_PID)))
                    .outputSchema(xpath.compile(GET_FIRST_OUTPUT_SCHEMA).evaluate(capabilitiesXml)));
        }
    } catch (Exception e) {
        return Optional.empty();
    } finally {
        closeClientAndResponse(client, response);
    }
}