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.fedoracommons.funapi.pmh.AbstractPmhResolver.java

/**
 * {@inheritDoc}/*from www . j  a v a  2s . com*/
 */
public UnapiObject getObject(String id, String format) throws UnapiException {
    try {
        String record = getRecord(id, format);
        XPath xpath = getXPath();
        Node pmh = (Node) xpath.evaluate("//oai:OAI-PMH", new InputSource(new StringReader(record)),
                XPathConstants.NODE);

        Node metadata = (Node) xpath.evaluate("//oai:metadata/*", pmh, XPathConstants.NODE);

        if (metadata == null) {
            String error = xpath.evaluate("//oai:error/@code", pmh);
            if (error.equalsIgnoreCase("idDoesNotExist")) {
                throw new IdentifierException(error);
            } else if (error.equalsIgnoreCase("cannotDisseminateFormat")) {
                throw new FormatException(error);
            } else {
                throw new UnapiException(error);
            }
        }

        TransformerFactory xformFactory = TransformerFactory.newInstance();
        Transformer transformer = xformFactory.newTransformer();

        Source source = new DOMSource(metadata);
        StringWriter sw = new StringWriter();
        transformer.transform(source, new StreamResult(sw));
        InputStream in = new ByteArrayInputStream(sw.toString().getBytes("UTF-8"));
        return new UnapiObject(in, "application/xml");
    } catch (XPathExpressionException e) {
        throw new UnapiException(e.getMessage(), e);
    } catch (TransformerException e) {
        throw new UnapiException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnapiException(e.getMessage(), e);
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceXmlTests.java

@Parameters
protected static Collection<Object[]> getAllDescriptionUrls(String eval)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    ArrayList<String> results = new ArrayList<String>();

    //Checks the ServiceProviderCatalog at the specified baseUrl of the REST service in order to grab all urls
    //to other ServiceProvidersCatalogs contained within it, recursively, in order to find the URLs of all
    //query factories of the REST service.

    String v = "//oslc_v2:QueryCapability/oslc_v2:queryBase/@rdf:resource";

    ArrayList<String> serviceUrls = getServiceProviderURLsUsingXML(null);
    ArrayList<String> capabilityURLsUsingXML = TestsBase.getCapabilityURLsUsingXML(v, getxpathSubStmt(),
            getResourceTypeQuery(), serviceUrls, true);

    // Once we have the query URL, look for a resource to validate
    String where = setupProps.getProperty("changeRequestsWhere");
    if (where == null) {
        String queryProperty = setupProps.getProperty("queryEqualityProperty");
        String queryPropertyValue = setupProps.getProperty("queryEqualityValue");
        where = queryProperty + "=\"" + queryPropertyValue + "\"";
    }/*from   w ww.j a  v a2s. c  om*/

    String additionalParameters = setupProps.getProperty("queryAdditionalParameters", "");
    String query = (additionalParameters.length() == 0) ? "?" : "?" + additionalParameters + "&";
    query = query + "oslc.where=" + URLEncoder.encode(where, "UTF-8") + "&oslc.pageSize=1";

    for (String queryBase : capabilityURLsUsingXML) {
        String queryUrl = OSLCUtils.addQueryStringToURL(queryBase, query);
        HttpResponse resp = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, creds, OSLCConstants.CT_XML,
                headers);
        String respBody = EntityUtils.toString(resp.getEntity());
        EntityUtils.consume(resp.getEntity());
        assertTrue("Received " + resp.getStatusLine(),
                (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK));

        //Get XML Doc from response
        Document doc = OSLCUtils.createXMLDocFromResponseBody(respBody);

        //Check for results by reference (rdf:resource)
        Node result = (Node) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODE);

        if (result == null)
            //No results by reference. Check for inline results (rdf:about)
            result = (Node) OSLCUtils.getXPath().evaluate("//rdfs:member/oslc_cm_v2:ChangeRequest/@rdf:about",
                    doc, XPathConstants.NODE);
        if (result != null)
            results.add(result.getNodeValue());
        if (onlyOnce)
            break;
    }

    return toCollection(results);
}

From source file:no.digipost.signature.client.asice.signature.CreateXAdESProperties.java

private void markAsIdProperty(final Document document, final String elementName, final String property) {
    XPath xPath = XPathFactory.newInstance().newXPath();
    try {//from   w w  w.ja  va  2 s . c o  m
        Element idElement = (Element) xPath.evaluate("//*[local-name()='" + elementName + "']", document,
                XPathConstants.NODE);
        idElement.setIdAttribute(property, true);

    } catch (XPathExpressionException e) {
        throw new XmlConfigurationException("XPath on generated XML failed.", e);
    }
}

From source file:com.cisco.dvbu.ps.common.adapters.config.SoapHttpConfig.java

private void parseCallback(Element eElement) throws AdapterException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {//  www.  j a v  a2s . c  o  m
        SoapHttpConnectorCallback cb = new SoapHttpConnectorCallback();
        cb.setOperation(eElement.getAttribute(AdapterConstants.CONNECTOR_SE_NAME));
        //         log.debug("Operation: " + cb.getOperation());
        cb.setEndpoint(eElement.getAttribute(AdapterConstants.CONNECTOR_SH_ENDPOINT));
        //         log.debug("Endpoint: " + cb.getEndpoint());
        cb.setName(cb.getEndpoint() + AdapterConstants.CONNECTOR_EP_SEPARATOR + cb.getOperation());
        Element e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_CB_SOAPACTION, eElement,
                XPathConstants.NODE);
        cb.setAction(e.getTextContent());
        //         log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_CB_RQ_BODY, eElement, XPathConstants.NODE);
        cb.setRequestBodyXsl(e.getTextContent().trim());
        //         log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_CB_RS_BODY, eElement, XPathConstants.NODE);
        cb.setResponseBodyXsl(e.getTextContent().trim());
        //         log.debug(e.getNodeName() + ": " + e.getTextContent());
        connCallbacks.put(cb.getName(), cb);
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(401,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
}

From source file:no.difi.sdp.client.asice.signature.CreateXAdESProperties.java

private void markAsIdProperty(Document document, final String elementName, String property) {
    XPath xPath = XPathFactory.newInstance().newXPath();
    try {// www  . j  a va2 s. co m
        Element idElement = (Element) xPath.evaluate("//*[local-name()='" + elementName + "']", document,
                XPathConstants.NODE);
        idElement.setIdAttribute(property, true);

    } catch (XPathExpressionException e) {
        throw new XmlKonfigurasjonException("XPath p generert XML feilet.", e);
    }
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.QueryTests.java

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription, find and add the simpleQuery service url
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));
        Node simpleQueryUrl = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:simpleQuery/oslc_cm:url", baseDoc,
                XPathConstants.NODE);
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { simpleQueryUrl.getTextContent() });
        return data;
    }/*  ww  w.j  av  a  2  s. c o  m*/

    String respBody = EntityUtils.toString(resp.getEntity());
    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(respBody);

    //ArrayList to contain the urls from all of the SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        String serviceUrl = OSLCUtils.absoluteUrlFromRelative(base, sDescs.item(i).getNodeValue());
        Collection<Object[]> subCollection = getReferencedUrls(serviceUrl);
        Iterator<Object[]> iter = subCollection.iterator();
        while (iter.hasNext()) {
            data.add(iter.next());
        }
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //simple query services from the eventual service description documents from them as well.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        String uri = spcs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        if (!uri.equals(base)) {
            Collection<Object[]> subCollection = getReferencedUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

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

/**
 * Parses the workflow instance represented by <code>xml</code> and extracts the workflow identifier.
 * //from   w ww .  j  a va  2  s  .  c om
 * @param xml
 *          the workflow instance
 * @return the workflow instance
 * @throws Exception
 *           if parsing fails
 */
public static String getWorkflowInstanceId(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("id");
}

From source file:io.selendroid.nativetests.GetWindowSourceTest.java

private Element findElementByXpath(String expr, String source) throws Exception {
    String xml = JsonXmlUtil.toXml(new JSONObject(source));
    InputSource is = new InputSource(new StringReader(xml));
    XPath xPath = XPathFactory.newInstance().newXPath();

    XPathExpression xpathExpr = xPath.compile(expr);
    return (Element) xpathExpr.evaluate(is, XPathConstants.NODE);
}

From source file:org.eclipse.lyo.testsuite.oslcv2.SimplifiedQueryAtomTests.java

protected void validateNonEmptyResponse(String query)
        throws XPathExpressionException, IOException, ParserConfigurationException, SAXException {
    String queryUrl = OSLCUtils.addQueryStringToURL(currentUrl, query);

    // Send ATOM feed request
    HttpResponse response = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, basicCreds,
            OSLCConstants.CT_ATOM, headers);

    int statusCode = response.getStatusLine().getStatusCode();
    if (HttpStatus.SC_OK != statusCode) {
        EntityUtils.consume(response.getEntity());
        throw new IOException("Response code: " + statusCode + " for " + queryUrl);
    }/*from w  w  w.  ja  va 2 s . c  o  m*/

    String responseBody = EntityUtils.toString(response.getEntity());

    //
    // Validate ATOM feed response
    //
    InputStream bais = new ByteArrayInputStream(responseBody.getBytes());

    // Create mapping of ATOM variables
    Abdera abdera = new Abdera();
    org.apache.abdera.model.Document<Feed> model = abdera.getParser().parse(bais);
    Feed feed = model.getRoot();

    List<Entry> entries = feed.getEntries();

    // We expect at least one change request in query ATOM response
    //      assertTrue( entries.size()>=1 );

    for (Entry entry : entries) {
        String content = entry.getContent();

        //Get XML Doc from Atom Description
        Document description = OSLCUtils.createXMLDocFromResponseBody(content);
        Node result = (Node) OSLCUtils.getXPath().evaluate("//rdf:Description/@rdf:about", description,
                XPathConstants.NODE);

        if (result != null) {
            String node = result.getNodeValue();
            assertNotNull(node);
            break;
        }
    }
}

From source file:com.oracle.tutorial.jdbc.RSSFeedsTable.java

public void addRSSFeed(String fileName) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, TransformerConfigurationException, TransformerException, SQLException {
    // Parse the document and retrieve the name of the RSS feed

    String titleString = null;//  w  w  w. jav  a  2 s . c  o m

    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    Node titleElement = (Node) xPath.evaluate("/rss/channel/title[1]", doc, XPathConstants.NODE);

    if (titleElement == null) {
        System.out.println("Unable to retrieve title element");
        return;
    } else {
        titleString = titleElement.getTextContent().trim().toLowerCase().replaceAll("\\s+", "_");
        System.out.println("title element: [" + titleString + "]");
    }

    System.out.println(JDBCTutorialUtilities.convertDocumentToString(doc));

    PreparedStatement insertRow = null;
    SQLXML rssData = null;

    System.out.println("Current DBMS: " + this.dbms);

    try {
        if (this.dbms.equals("mysql")) {
            // For databases that support the SQLXML data type, this creates a
            // SQLXML object from org.w3c.dom.Document.

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values" + " (?, ?)";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);

            System.out.println("Creating SQLXML object with MySQL");
            rssData = con.createSQLXML();
            System.out.println("Creating DOMResult object");
            DOMResult dom = (DOMResult) rssData.setResult(DOMResult.class);
            dom.setNode(doc);

            insertRow.setSQLXML(2, rssData);
            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

        else if (this.dbms.equals("derby")) {

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values"
                    + " (?, xmlparse(document cast (? as clob) preserve whitespace))";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);
            String convertedDoc = JDBCTutorialUtilities.convertDocumentToString(doc);
            insertRow.setClob(2, new StringReader(convertedDoc));

            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (Exception ex) {
        System.out.println("Another exception caught:");
        ex.printStackTrace();
    }

    finally {
        if (insertRow != null) {
            insertRow.close();
        }
    }
}