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.eclipse.lyo.testsuite.oslcv2.ServiceProviderCatalogXmlTests.java

public static Collection<Object[]> getReferencedCatalogUrlsUsingXML(String base)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    staticSetup();//ww w  .  j av a  2s . co  m
    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, basicCreds, OSLCConstants.CT_XML, headers);

    int statusCode = resp.getStatusLine().getStatusCode();
    if (HttpStatus.SC_OK != statusCode) {
        EntityUtils.consume(resp.getEntity());
        throw new IOException("Response code: " + statusCode + " for " + base);
    }

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

    // ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();
    Node rootElement = (Node) OSLCUtils.getXPath().evaluate("/rdf:RDF/*", baseDoc, XPathConstants.NODE);
    if (rootElement.getNamespaceURI().equals(OSLCConstants.OSLC_V2)
            && rootElement.getLocalName().equals("ServiceProviderCatalog")) {
        data.add(new Object[] { base });
    }

    // Get all ServiceProviderCatalog urls from the base document in order
    // to test them as well,
    // recursively checking them for other ServiceProviderCatalogs further
    // down.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_v2:serviceProviderCatalog/oslc_v2:ServiceProviderCatalog/@rdf:about", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        if (!spcs.item(i).getNodeValue().equals(base)) {
            Collection<Object[]> subCollection = getReferencedCatalogUrlsUsingXML(spcs.item(i).getNodeValue());
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

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

public void populateTable(String fileName)
        throws SQLException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    // factory.setNamespaceAware(true);
    factory.setNamespaceAware(true);//from  ww w . jav a  2 s. c  om
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    NodeList nodes = (NodeList) xPath.evaluate("/coffee-product-information/item[coffee = 'Columbian']", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node currentNode = nodes.item(i);
        // Retrieve the description element

        currentNode.normalize();

        if (currentNode == null) {
            System.out.println("Current node is null");
        }

        //      System.out.println(currentNode.getTextContent());

        Node descriptionNode = (Node) xPath.evaluate("description", currentNode, XPathConstants.NODE);

        if (descriptionNode == null) {
            System.out.println("DescriptionNode is null");
        } else {

            System.out.println(descriptionNode.getTextContent());

            NodeList descriptionNodeChildren = descriptionNode.getChildNodes();
            System.out.println("Description node has " + descriptionNodeChildren.getLength() + " child nodes");
            Node descNodeChild = descriptionNode.getFirstChild();
            System.out.println("Only child node type: " + descNodeChild.getNodeType());
        }

        //      System.out.println("Description: " + descriptionNode.getNodeValue());

        // System.out.println(nodes.item(i).getNodeValue());
    }

}

From source file:ru.itdsystems.alfresco.persistence.CrudPost.java

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws WebScriptException {
    // construct path elements array from request parameters
    List<String> pathElements = new ArrayList<String>();
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    pathElements.add(templateVars.get("application_name"));
    pathElements.add(templateVars.get("form_name"));
    doBefore(pathElements, null);/*  w  w  w  .  j a va 2  s. c  om*/
    // parse xml from request and perform a search
    Document searchXML;
    DocumentBuilder xmlBuilder;
    DocumentBuilderFactory xmlFact;
    try {
        xmlFact = DocumentBuilderFactory.newInstance();
        xmlFact.setNamespaceAware(true);
        xmlBuilder = xmlFact.newDocumentBuilder();
        searchXML = xmlBuilder.parse(req.getContent().getInputStream());
    } catch (Exception e) {
        throw new WebScriptException(500, "Error occured while parsing XML from request.", e);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Integer pageSize;
    Integer pageNumber;
    String lang;
    // String applicationName;
    // String formName;
    NodeList queries;
    // extract search details
    try {
        pageSize = new Integer(
                ((Node) xpath.evaluate("/search/page-size/text()", searchXML, XPathConstants.NODE))
                        .getNodeValue());
        pageNumber = new Integer(
                ((Node) xpath.evaluate("/search/page-number/text()", searchXML, XPathConstants.NODE))
                        .getNodeValue());
        lang = ((Node) xpath.evaluate("/search/lang/text()", searchXML, XPathConstants.NODE)).getNodeValue();
        // applicationName = ((Node) xpath.evaluate("/search/app/text()",
        // searchXML, XPathConstants.NODE)).getNodeValue();
        // formName = ((Node) xpath.evaluate("/search/form/text()",
        // searchXML,
        // XPathConstants.NODE)).getNodeValue();
        queries = (NodeList) xpath.evaluate("/search/query", searchXML, XPathConstants.NODESET);
        if (queries.getLength() == 0)
            throw new Exception("No queries found.");
    } catch (Exception e) {
        throw new WebScriptException(500, "XML in request is malformed.", e);
    }
    // check if requested query is supported
    if (!"".equals(queries.item(0).getTextContent()))
        throw new WebScriptException(500, "Freetext queries are not supported at the moment.");
    // resolve path to root data
    pathElements.add("data");
    NodeRef nodeRef = getRootNodeRef();
    // resolve path to file
    FileInfo fileInfo = null;
    Integer totalForms = 0;
    try {
        //         fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements, false);
        fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements);
    } catch (FileNotFoundException e) {
        // do nothing here
    }
    if (fileInfo != null) {
        // iterate through all forms
        List<ChildAssociationRef> assocs = nodeService.getChildAssocs(fileInfo.getNodeRef());
        List<String> details = new ArrayList<String>();
        Document resultXML;
        try {
            resultXML = xmlBuilder.newDocument();
        } catch (Exception e) {
            throw new WebScriptException(500, "Smth really strange happened o.O", e);
        }
        Element rootElement = resultXML.createElement("documents");
        rootElement.setAttribute("page-size", pageSize.toString());
        rootElement.setAttribute("page-number", pageNumber.toString());
        rootElement.setAttribute("query", "");
        resultXML.appendChild(rootElement);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ");
        int skip = pageSize * (pageNumber - 1);
        Integer found = 0;
        Integer searchTotal = 0;
        for (ChildAssociationRef assoc : assocs) {
            if ((nodeRef = nodeService.getChildByName(assoc.getChildRef(), ContentModel.ASSOC_CONTAINS,
                    "data.xml")) != null) {
                // parse file
                Document dataXML;
                try {
                    dataXML = xmlBuilder.parse(fileFolderService.getReader(nodeRef).getContentInputStream());
                } catch (Exception e) {
                    throw new WebScriptException(500, "Form file is malformed.", e);
                }
                totalForms++;
                details.clear();
                xpath.setNamespaceContext(new OrbeonNamespaceContext());
                // execute search queries
                for (int i = 1; i < queries.getLength(); i++) {
                    Node query = queries.item(i);
                    String path = query.getAttributes().getNamedItem("path").getNodeValue();
                    String match = query.getAttributes().getNamedItem("match").getNodeValue();
                    String queryString = query.getTextContent();
                    if (path == null || match == null || queryString == null)
                        throw new WebScriptException(500, "Search query XML is malformed.");
                    path = path.replace("$fb-lang", "'" + lang + "'");
                    boolean exactMatch = "exact".equals(match);
                    Node queryResult;
                    try {
                        queryResult = (Node) xpath.evaluate(path, dataXML.getDocumentElement(),
                                XPathConstants.NODE);
                    } catch (Exception e) {
                        throw new WebScriptException(500, "Error in query xpath expression.", e);
                    }
                    if (queryResult == null)
                        break;
                    String textContent = queryResult.getTextContent();
                    // TODO
                    // check type while comparing values
                    if (exactMatch && queryString.equals(textContent)
                            || !exactMatch && textContent != null && textContent.contains(queryString)
                            || queryString.isEmpty())
                        details.add(textContent);
                    else
                        break;
                }
                // add document to response xml
                if (details.size() == queries.getLength() - 1) {
                    searchTotal++;
                    if (skip > 0)
                        skip--;
                    else if (++found <= pageSize) {
                        Element item = resultXML.createElement("document");
                        String createdText = dateFormat
                                .format(fileFolderService.getFileInfo(nodeRef).getCreatedDate());
                        item.setAttribute("created",
                                createdText.substring(0, 26) + ":" + createdText.substring(26));
                        String modifiedText = dateFormat
                                .format(fileFolderService.getFileInfo(nodeRef).getModifiedDate());
                        item.setAttribute("last-modified",
                                modifiedText.substring(0, 26) + ":" + modifiedText.substring(26));
                        item.setAttribute("name", fileFolderService.getFileInfo(assoc.getChildRef()).getName());
                        resultXML.getDocumentElement().appendChild(item);
                        Element detailsElement = resultXML.createElement("details");
                        item.appendChild(detailsElement);
                        for (String detail : details) {
                            Element detailElement = resultXML.createElement("detail");
                            detailElement.appendChild(resultXML.createTextNode(detail));
                            detailsElement.appendChild(detailElement);
                        }
                    } /*
                      * else break;
                      */

                }
            }
        }
        rootElement.setAttribute("total", totalForms.toString());
        rootElement.setAttribute("search-total", searchTotal.toString());
        // stream output to client
        try {
            TransformerFactory.newInstance().newTransformer().transform(new DOMSource(resultXML),
                    new StreamResult(res.getOutputStream()));
        } catch (Exception e) {
            throw new WebScriptException(500, "Error occured while streaming output to client.", e);
        }
    }

}

From source file:com.esri.gpt.server.openls.provider.services.map.GetPortrayMapCapabilitiesProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * @param context the operation context//w  w  w .  j a  v  a2 s .c om
 * @param root the root node
 * @param xpath an XPath to enable queries (properly configured with name spaces)
 * @throws Exception if a processing exception occurs
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize 
    LOGGER.finer("Handling xls:GetPortrayMapCapabilitiesRequest request XML...");
    String locator = "xls:GetPortrayMapCapabilitiesRequest";
    Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndReq != null) {
        // params = processRequest(context, root,ndReq, xpath);
        try {
            executeRequest(context);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        generateResponse(context);
    }
}

From source file:com.sqewd.os.maracache.core.Config.java

/**
 * Load the configuration from the path and file specified.
 *
 * @throws ConfigException/* w  ww.ja  v a 2  s  .c  o  m*/
 */
public void load() throws ConfigException {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(filePath);

        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        XPath xp = XPathFactory.newInstance().newXPath();
        Element root = (Element) xp.compile(configPath).evaluate(doc, XPathConstants.NODE);
        if (root == null) {
            throw new ConfigException("Cannot find specified path in document. [path=" + configPath + "]");
        }

        node = new ConfigPath(root.getNodeName(), null);
        load(node, root);

        state = EObjectState.Available;
    } catch (ParserConfigurationException pse) {
        state = EObjectState.Exception;
        state.setException(pse);
        throw new ConfigException("Error building the configuration document.", pse);
    } catch (IOException ioe) {
        state = EObjectState.Exception;
        state.setException(ioe);
        throw new ConfigException("Error reading configuration file [path=" + filePath + "]", ioe);
    } catch (SAXException se) {
        state = EObjectState.Exception;
        state.setException(se);
        throw new ConfigException("Error parsing document [document=" + filePath + "]", se);
    } catch (XPathExpressionException xpe) {
        state = EObjectState.Exception;
        state.setException(xpe);
        throw new ConfigException("Error parsing specified XPath expression.", xpe);
    }
}

From source file:cz.incad.kramerius.utils.solr.SolrUtils.java

/**
 * Disect pid from given solr document//from  w w  w . ja  v  a2s .c o m
 * @param parseDocument Parsed solr document
 * @return PID 
 * @throws XPathExpressionException cannot disect pid
 */
public static String disectPid(Document parseDocument) throws XPathExpressionException {
    synchronized (parseDocument) {
        Node pidNode = (Node) docPidExpr().evaluate(parseDocument, XPathConstants.NODE);
        if (pidNode != null) {
            Element pidElm = (Element) pidNode;
            return pidElm.getTextContent().trim();
        }
        return null;
    }
}

From source file:org.ensembl.gti.seqstore.database.cramstore.EnaCramSubmitter.java

protected static boolean isSuccess(Document doc) {
    try {/* w ww.  j  a  v  a  2  s.  c  om*/
        XPathExpression success = xpath.compile("/RECEIPT[@success]");
        Node nl = (Node) success.evaluate(doc, XPathConstants.NODE);
        return "true".equals(nl.getAttributes().getNamedItem("success").getTextContent());
    } catch (XPathExpressionException e) {
        throw new EnaSubmissionException("Could not parse submission receipt", e);
    }
}

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

/**
 * Parses the job instance represented by <code>xml</code> and extracts the job type.
 * //from  w ww  .  ja v a2  s.c o  m
 * @param xml
 *          the job instance
 * @return the job type
 * @throws Exception
 *           if parsing fails
 */
public static String getJobType(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("type");
}

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

protected void validateNonEmptyResponse(String query)
        throws XPathExpressionException, IOException, ParserConfigurationException, SAXException {
    String queryUrl = OSLCUtils.addQueryStringToURL(currentUrl, query);
    HttpResponse response = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, basicCreds,
            OSLCConstants.CT_XML, headers);
    int statusCode = response.getStatusLine().getStatusCode();
    if (HttpStatus.SC_OK != statusCode) {
        EntityUtils.consume(response.getEntity());
        throw new IOException("Response code: " + statusCode + " for " + queryUrl);
    }// w w w  .j  a  v  a  2s . co m

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

    Document doc = OSLCUtils.createXMLDocFromResponseBody(responseBody);
    Node results = (Node) OSLCUtils.getXPath().evaluate("//oslc:ResponseInfo/@rdf:about", doc,
            XPathConstants.NODE);

    // Only test oslc:ResponseInfo if found
    if (results != null) {
        assertEquals("Expended ResponseInfo/@rdf:about to equal request URL", queryUrl, results.getNodeValue());
        results = (Node) OSLCUtils.getXPath().evaluate("//oslc:totalCount", doc, XPathConstants.NODE);
        if (results != null) {
            int totalCount = Integer.parseInt(results.getTextContent());
            assertTrue("Expected oslc:totalCount > 0", totalCount > 0);
        }

        NodeList resultList = (NodeList) OSLCUtils.getXPath().evaluate("//rdf:Description/rdfs:member", doc,
                XPathConstants.NODESET);
        assertNotNull("Expected rdfs:member(s)", resultList);
        assertNotNull("Expected > 1 rdfs:member(s)", resultList.getLength() > 0);
    }
}

From source file:com.tranek.chivalryserverbrowser.XMLData2.java

/**
 * Returns the XML data for the element specified by the given XPath
 *
 * @param path The XPath to get the XML data for
 * @return The element with the given XPath
 *//* www  . ja v a2s  .  c o  m*/
public XMLData2 getXPath(String path) {
    if (xpath == null) {
        xpath = XPathFactory.newInstance().newXPath();
    }

    try {
        return new XMLData2((Element) xpath.evaluate(path, this.root, XPathConstants.NODE));
    } catch (XPathExpressionException e) {
        return null;
    }
}