Example usage for javax.xml.xpath XPathConstants NODESET

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

Introduction

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

Prototype

QName NODESET

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

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:com.norconex.committer.gsa.XmlOutputTest.java

@Test
public void testWriteMultipleRecords() throws Exception {

    File file = tempFolder.newFile();
    FileOutputStream out = new FileOutputStream(file);
    XmlOutput xmlOutput = new XmlOutput(out);

    Properties metadata1 = new Properties();
    metadata1.addString("url", "http://www.corp.enterprise.com/hello01");
    metadata1.addString("mimetype", "text/plain");
    metadata1.addString("collector.content-type", "text/plain");
    metadata1.addString("last-modified", "Tue, 6 Nov 2007 12:45:26 GMT");
    metadata1.addString("Date", "Tue, 6 Nov 2007 12:45:26 GMT");
    String content1 = "This is hello01";

    Properties metadata2 = new Properties();
    metadata2.addString("url", "http://www.corp.enterprise.com/hello02");
    metadata2.addString("mimetype", "text/plain");
    metadata2.addString("collector.content-type", "text/plain");
    metadata2.addString("last-modified", "Tue, 6 Nov 2009 22:45:26 GMT");
    metadata2.addString("Date", "Tue, 6 Nov 2009 22:45:26 GMT");
    String content2 = "This is hello02";

    xmlOutput.write(Arrays.asList(buildMockAddOperation(metadata1, content1),
            buildMockAddOperation(metadata2, content2)));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document doc = dbf.newDocumentBuilder().parse(file);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate("/gsafeed/group/record", doc, XPathConstants.NODESET);
    assertEquals(2, nodes.getLength());//from  w  ww  .  j ava 2s.  com
}

From source file:eu.fbk.dh.tint.tokenizer.ItalianTokenizer.java

public ItalianTokenizer(@Nullable File settingFile) {
        Trie.TrieBuilder builder = Trie.builder().removeOverlaps();

        InputStream stream = null;
        if (settingFile != null) {
            try {
                stream = new FileInputStream(settingFile);
            } catch (FileNotFoundException e) {
                // continue
            }/*from  ww  w  .j av a  2  s.  com*/
        }
        if (stream == null) {
            stream = this.getClass().getResourceAsStream("/token-settings.xml");
        }

        logger.trace("Loading model");
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();

            XPathExpression expr;
            NodeList nl;
            int count;

            Document doc = dBuilder.parse(stream);
            doc.getDocumentElement().normalize();

            // Normalization rules
            expr = xpath.compile("/settings/normalization/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String hexCode = element.getAttribute("hexcode");
                String content = element.getTextContent();

                // Bad: need fix
                if (content.equals("`")) {
                    content = "'";
                }

                int num = Integer.parseInt(hexCode, 16);
                if (content.length() == 0) {
                    continue;
                }
                normalizedChars.put(num, content);
            }
            logger.info("Loaded {} normalization rules", normalizedChars.size());

            // end sentence chars
            expr = xpath.compile("/settings/sentenceSplitting/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String charID = element.getAttribute("id");
                sentenceChars.add(Integer.parseInt(charID));
            }
            logger.info("Loaded {} sentence splitting rules", sentenceChars.size());

            // splitting rules
            expr = xpath.compile("/settings/tokenSplitting/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String charID = element.getAttribute("id");
                splittingChars.add(Integer.parseInt(charID));
            }
            logger.info("Loaded {} token splitting rules", splittingChars.size());

            // expressions
            expr = xpath.compile("/settings/expressions/expression");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            StringBuilder b = new StringBuilder();
            b.append("(");
            boolean first = true;
            count = 0;
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String regExp = element.getAttribute("find");
                boolean merge = PropertiesUtils.getBoolean(element.getAttribute("merge"), true);
                Integer group = PropertiesUtils.getInteger(element.getAttribute("get"), 1);
                if (merge) {
                    if (!first) {
                        b.append("|");
                    }
                    b.append(regExp);
                    count++;
                    first = false;
                } else {
                    expressions.put(Pattern.compile(regExp), group);
                    count++;
                }
            }
            b.append(")");
            expressions.put(Pattern.compile(b.toString()), 1);
            logger.info("Loaded {} regular expressions", count);

            // abbreviations
            expr = xpath.compile("/settings/abbreviations/abbreviation");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            count = 0;
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                String abbr = item.getTextContent();
                abbr = getString(tokenArray(abbr));
                builder.addKeyword(" " + abbr + " ");
                count++;
            }
            logger.info("Loaded {} abbreviations", count);

        } catch (Exception e) {
            e.printStackTrace();
        }

        trie = builder.build();
    }

From source file:com.stevpet.sonar.plugins.dotnet.resharper.customseverities.BaseCustomSeverities.java

/**
 * Get the String nodes through the reader
 * @return list of string nodes/*from   w w w .j  a  v a  2 s.co m*/
* @throws XPathExpressionException 
 */
private NodeList getStringNodes(InputSource source) throws XPathExpressionException {
    XPath xpath = createXPathForInspectCode();
    NodeList nodes = new EmptyNodeList();
    nodes = (NodeList) xpath.evaluate("//s:String", source, XPathConstants.NODESET);
    return nodes;
}

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);//from   ww w.j  a  v  a 2 s  .  co m
    // 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:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.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 we don't need to recurse as this is the only one we can find
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { base });
        EntityUtils.consume(resp.getEntity());
        return data;
    }/*from   www  .j a v  a2  s .c  o m*/

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

    //ArrayList to contain the urls from all 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 uri = sDescs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        data.add(new Object[] { uri });
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //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:net.sourceforge.dita4publishers.impl.dita.InMemoryDitaKeySpace.java

/**
 * Processes a DITA map document to add any new keys to the key space
 * @param mapElement//  ww  w .j a  va  2  s .  c  o  m
 * @throws DitaApiException 
 */
public void addKeyDefinitions(Element mapElement) throws DitaApiException {
    NodeList keydefs = null;
    try {
        keydefs = (NodeList) DitaUtil.allKeyDefs.evaluate(mapElement, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(
                "Unexpected exception evaluating XPath expression \"" + DitaUtil.ALL_KEYDEFS_XPATH + "\"");
    }

    log.debug("addKeyDefinitions(): Found " + keydefs.getLength() + " key-defining topicrefs in the map");
    for (int i = 0; i < keydefs.getLength(); i++) {
        Element keydef = (Element) keydefs.item(i);
        String keydefStr = keydef.getAttribute("keys");
        StringTokenizer tokenizer = new StringTokenizer(keydefStr, " ");
        while (tokenizer.hasMoreTokens()) {
            String key = tokenizer.nextToken();
            registerKeyDefinition(mapElement, keydef, key);
        }
    }
}

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

protected static List<String> getElems(Document doc, String tag) {
    try {//from  w  w w  .ja v  a 2s .co  m
        List<String> elems = new ArrayList<>();
        XPathExpression success = xpath.compile("//" + tag);
        NodeList nl = (NodeList) success.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            elems.add(nl.item(i).getTextContent());
        }
        return elems;
    } catch (XPathExpressionException e) {
        throw new EnaSubmissionException("Could not parse submission receipt", e);
    }
}

From source file:com.hotwire.test.steps.application.IosApplication.java

public String getExpectedAnalytics(String analyticsParams) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from ww  w. j  a  v  a2  s .c o  m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("vertical");
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    String paramsToPath = "//" + (analyticsParams.replaceAll(":", "/")) + "/node()";
    XPathExpression expr = xpath.compile(paramsToPath);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < nodes.getLength(); i++) {
        sb.append((nodes.item(i).getNodeName() + "=" + nodes.item(i).getTextContent()).trim());
    }
    String expectedParams = sb.toString().replaceAll("#text=", ";");

    return expectedParams;
}

From source file:com.streak.logging.analysis.AnalysisUtility.java

public static List<String> fetchCloudStorageUris(String bucketName, String startKey, String endKey,
        HttpRequestFactory requestFactory) throws IOException {
    List<String> result = new ArrayList<String>();

    String bucketUri = "http://commondatastorage.googleapis.com/" + bucketName;
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(bucketUri + "?marker=" + startKey));
    HttpResponse response = request.execute();

    try {//w  w  w  .  j  a  v  a 2 s  . c om
        Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getContent());
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key/text()", responseDoc,
                XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            String key = nodes.item(i).getNodeValue();
            if (key.compareTo(endKey) >= 0) {
                break;
            }
            if (key.endsWith(".schema.json")) {
                continue;
            }
            result.add("gs://" + bucketName + "/" + key);
        }
    } catch (SAXException e) {
        throw new IOException("Error parsing cloud storage response", e);
    } catch (ParserConfigurationException e) {
        throw new IOException("Error configuring cloud storage parser", e);
    } catch (XPathExpressionException e) {
        throw new IOException("Error finding keys", e);
    }

    return result;
}

From source file:org.opencastproject.remotetest.server.OaiPmhServerTest.java

@Test
public void testListMetadataFormatsAll() throws Exception {
    Document response = doGetRequest("verb=ListMetadataFormats");
    assertXpathExists(response, "//*[local-name() = 'ListMetadataFormats']");
    List<String> prefixes = Utils.nodeListToStringList(
            (NodeList) Utils.xpath(response, "//*[local-name() = 'metadataPrefix']", XPathConstants.NODESET));
    assertTrue(prefixes.contains("oai_dc"));
    assertTrue(prefixes.contains("matterhorn"));
}