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:net.sourceforge.dita4publishers.impl.ditabos.PointerRewritingBosVisitorBase.java

public boolean rewriteLocalUris(DitaBosMember member) throws BosException, AddressingException {
    // Find all pointers and then look up our dependencies by those values
    log.debug("Rewriting local URIs for BOS member " + member + "...");
    NodeList nl;/*from  w w w.  j  a v a2 s .  c om*/
    try {
        nl = (NodeList) DitaUtil.allHrefsAndConrefs.evaluate(member.getElement(), XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new BosException(
                "Unexpected exception evaluating XPath expression \"" + DitaUtil.allHrefsAndConrefs, e);
    }
    boolean contentModified = false;
    if (nl.getLength() > 0) {
        // Get local pointer to the DOM so we can mutate it.
        for (int i = 0; i < nl.getLength(); i++) {
            Element ref = (Element) nl.item(i);
            if (ref.hasAttribute("href") && DitaUtil.isLocalScope(ref))
                ;
            String href = ref.getAttribute("href");
            BosMember depMember = member.getDependency(href);
            if (depMember == null) {
                log.warn("rewriteUris(): Local reference with href value \"" + href
                        + "\" failed to result in a dependency lookup. This indicates an unresolvable local resource reference.");
                continue;
            }

            String newHref = constructNewHref(member, depMember, ref);
            ref.setAttribute("href", newHref);
            contentModified = true;
            log.debug("Rewriting pointer \"" + href + "\" to \"" + newHref + "\"");

        }
    }
    return contentModified;
}

From source file:com.cognifide.aet.job.common.datafilters.removenodes.RemoveNodesDataModifier.java

private void removeNodes(Document document) throws ProcessingException {
    try {// w w w.j  a  va2s.  c om
        NodeList nl = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            node.getParentNode().removeChild(node);
        }
    } catch (XPathExpressionException e) {
        throw new ProcessingException(e.getMessage(), e);
    }
}

From source file:cz.incad.cdk.cdkharvester.PidsRetriever.java

private void getDocs() throws Exception {
    String urlStr = harvestUrl + URIUtil.encodeQuery(actual_date);
    logger.log(Level.INFO, "urlStr: {0}", urlStr);
    org.w3c.dom.Document solrDom = solrResults(urlStr);
    String xPathStr = "/response/result/@numFound";
    expr = xpath.compile(xPathStr);/*  w  ww  .ja  v  a 2  s  .c  om*/
    int numDocs = Integer.parseInt((String) expr.evaluate(solrDom, XPathConstants.STRING));
    logger.log(Level.INFO, "numDocs: {0}", numDocs);
    if (numDocs > 0) {
        xPathStr = "/response/result/doc/str[@name='PID']";
        expr = xpath.compile(xPathStr);
        NodeList nodes = (NodeList) expr.evaluate(solrDom, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            String pid = node.getFirstChild().getNodeValue();
            String to = node.getNextSibling().getFirstChild().getNodeValue();
            qe.add(new DocEntry(pid, to));
        }
    }
}

From source file:dk.statsbiblioteket.doms.iprolemapper.webservice.IPRangesConfigReader.java

/**
 * Produce a <code>List</code> of <code>IPRangeRoles</code> instances
 * constructed from the information read from the XML configuration
 * specified by <code>rangesConfigFile</code>.
 * /*from w ww  .j ava 2 s  .  c om*/
 * @param rangesConfigFile
 *            a <code>File</code> instance configured with the path to the
 *            XML configuration file to read.
 * @return a list of <code>IPRangeRoles</code> instances, produced from the
 *         contents of the configuration file.
 * @throws IOException
 *             if any errors are encountered while reading the configuration
 *             file.
 */
public List<IPRangeRoles> readFromXMLConfigFile(File rangesConfigFile) throws IOException {

    if (log.isTraceEnabled()) {
        log.trace("readFromXMLConfigFile(): Called with file path: " + rangesConfigFile);
    }

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    NodeList ipRangeNodes = null;

    try {
        final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        final Document configuationDocument = documentBuilder.parse(rangesConfigFile);

        final XPathFactory xPathFactory = XPathFactory.newInstance();
        final XPath xPath = xPathFactory.newXPath();

        ipRangeNodes = (NodeList) xPath.evaluate("/ipranges/iprange", configuationDocument,
                XPathConstants.NODESET);
    } catch (ParserConfigurationException parserConfigException) {
        throw new IOException("Failed setting up parser", parserConfigException);
    } catch (SAXException saxException) {
        throw new IOException("Failed parsing configuration file '" + rangesConfigFile + "'", saxException);

    } catch (XPathExpressionException xPathExpressionException) {
        throw new IOException("Failed parsing (evaluating) configuration" + " file '" + rangesConfigFile + "'",
                xPathExpressionException);

    }
    final List<IPRangeRoles> ipRangeList = new LinkedList<IPRangeRoles>();
    for (int nodeIdx = 0; nodeIdx < ipRangeNodes.getLength(); nodeIdx++) {
        try {
            ipRangeList.add(produceIPRangeInstance(ipRangeNodes.item(nodeIdx)));
        } catch (Exception cause) {
            String ipRangeNodeXMLString = "Malformed IpRange.";
            try {
                ipRangeNodeXMLString = DOM.domToString(ipRangeNodes.item(nodeIdx));
            } catch (Exception eTwo) {
                // Exception being ignored
            }
            Logs.log(log, Logs.Level.WARN, "readFromXMLConfigFile() failed to read IPRange: ",
                    ipRangeNodeXMLString, cause);
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("readFromXMLConfigFile(): Returning IP address ranges: " + ipRangeList);
    }
    return ipRangeList;
}

From source file:mupomat.utility.LongLatService.java

public String getXpathValue(Document doc, String strXpath) throws XPathExpressionException {
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile(strXpath);
    String resultData = null;/* w w  w . j  ava  2s.  c  om*/
    Object result4 = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result4;
    for (int i = 0; i < nodes.getLength(); i++) {
        resultData = nodes.item(i).getNodeValue();
    }
    return resultData;

}

From source file:org.joy.config.Configuration.java

private void parseClassPathEntry(Document doc, XPath path) throws XPathExpressionException {
    NodeList classpathEntrys = (NodeList) path.evaluate("configuration/classpath/entry", doc,
            XPathConstants.NODESET);
    if (classpathEntrys != null) {
        for (int i = 0; i < classpathEntrys.getLength(); i++) {
            String entry = parseElementNodeValue(classpathEntrys.item(i));
            if (StringUtil.isNotEmpty(entry)) {
                classPathEntries.add(entry);
            }//from w  w w. j  a v a2s . c  om
        }
    }
}

From source file:net.adamcin.commons.testing.sling.SlingPostResponse.java

public static SlingPostResponse createFromInputStream(InputStream stream, String encoding) throws IOException {

    InputSource source = new InputSource(new BufferedInputStream(stream));
    source.setEncoding(encoding == null ? "UTF-8" : encoding);

    SlingPostResponse postResponse = new SlingPostResponse();

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();

    try {/*from   w w  w  .j a v  a2  s  .c  om*/

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(source);

        postResponse
                .setStatus((String) xpath.compile(XPATH_ID_STATUS).evaluate(document, XPathConstants.STRING));
        postResponse
                .setMessage((String) xpath.compile(XPATH_ID_MESSAGE).evaluate(document, XPathConstants.STRING));
        postResponse.setLocation(
                (String) xpath.compile(XPATH_ID_LOCATION).evaluate(document, XPathConstants.STRING));
        postResponse.setParentLocation(
                (String) xpath.compile(XPATH_ID_PARENT_LOCATION).evaluate(document, XPathConstants.STRING));
        postResponse.setPath((String) xpath.compile(XPATH_ID_PATH).evaluate(document, XPathConstants.STRING));
        postResponse
                .setReferer((String) xpath.compile(XPATH_ID_REFERER).evaluate(document, XPathConstants.STRING));

        List<Change> changes = new ArrayList<Change>();

        NodeList changeLogNodes = (NodeList) xpath.compile(XPATH_ID_CHANGE_LOG).evaluate(document,
                XPathConstants.NODESET);

        if (changeLogNodes != null) {
            for (int i = 0; i < changeLogNodes.getLength(); i++) {
                String rawChange = changeLogNodes.item(i).getTextContent();
                rawChange = rawChange.substring(0, rawChange.length() - 2);
                String[] rawChangeParts = rawChange.split("\\(", 2);
                if (rawChangeParts.length != 2) {
                    continue;
                }
                String changeType = rawChangeParts[0];
                String[] rawArguments = rawChangeParts[1].split(", ");
                List<String> arguments = new ArrayList<String>();
                for (String rawArgument : rawArguments) {
                    arguments.add(rawArgument.substring(1, rawArgument.length() - 1));
                }

                Change change = new Change(changeType, arguments.toArray(new String[arguments.size()]));
                changes.add(change);
            }
        }

        postResponse.setChangeLog(changes);

    } catch (XPathExpressionException e) {
        LOGGER.error("Failed to evaluate xpath statement.", e);
        throw new IOException("Failed to evaluate xpath statement.", e);
    } catch (ParserConfigurationException e) {
        LOGGER.error("Failed to create DocumentBuilder.", e);
        throw new IOException("Failed to create DocumentBuilder.", e);
    } catch (SAXException e) {
        LOGGER.error("Failed to create Document.", e);
        throw new IOException("Failed to create Document.", e);
    }

    LOGGER.info("Returning post response");
    return postResponse;
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.DbpediaMapper.java

private boolean load(String query) throws EntityException, NoResultException {

    boolean success = true;

    label = "";//from   www  . j a v a  2  s.  c om
    description = "";
    String queryUrl = produceQueryUrl(query);

    try {
        Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(queryUrl);

        if (response != null) {

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

            NodeList nodes = (NodeList) xPath.evaluate("/ArrayOfResult/Result", response,
                    XPathConstants.NODESET);

            if (nodes.getLength() != 0) {

                // WE TAKE THE FIRST ENTITY FROM DBPEDIA
                label = ((String) xPath.evaluate("Label", nodes.item(0), XPathConstants.STRING));

                description = ((String) xPath.evaluate("Description", nodes.item(0), XPathConstants.STRING))
                        .toLowerCase();

                NodeList classesList = (NodeList) xPath.evaluate("Classes/Class", nodes.item(0),
                        XPathConstants.NODESET);

                classes = new ArrayList<String>(classesList.getLength());
                for (int i = 0; i < classesList.getLength(); i++) {
                    Node n = classesList.item(i);
                    String clazz = (String) xPath.evaluate("Label", n, XPathConstants.STRING);
                    classes.add(clazz);
                }
            }
            if (label.isEmpty()) {
                success = false;
                label = query;
            }

        }
    } catch (Exception e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");

        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        success = false;

    } catch (Error e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");
        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                throw new EntityException("Error during the mapping of the query " + query + " on dbPedia ("
                        + e.toString() + ")");
            }
        }
        success = false;

    }

    if (!success) {
        throw new NoResultException("mapping to dbpedia failed for query " + query);
    }
    return success;
}

From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

public static void configurePackage(String env, File configFile) throws Exception {
    Transformer transformer = tltf.get();

    // get the list of files in proxies folder
    XMLFileListUtil listFileUtil = new XMLFileListUtil();

    ConfigTokens conf = FileReader.getBundleConfigs(configFile);

    Map<String, List<File>> filesToProcess = new HashMap<String, List<File>>();
    filesToProcess.put("proxy", listFileUtil.getProxyFiles(configFile));
    filesToProcess.put("policy", listFileUtil.getPolicyFiles(configFile));
    filesToProcess.put("target", listFileUtil.getTargetFiles(configFile));

    doTokenReplacement(env, conf, filesToProcess);

    // special case ...
    File proxyFile = listFileUtil.getAPIProxyFiles(configFile).get(0);
    Document xmlDoc = FileReader.getXMLDocument(proxyFile); // there would be only one file, at least one file

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expression = xpath.compile("/APIProxy/Description");

    NodeList nodes = (NodeList) expression.evaluate(xmlDoc, XPathConstants.NODESET);
    if (nodes.item(0).hasChildNodes()) {
        // sets the description to whatever is in the <proxyname>.xml file
        nodes.item(0).setTextContent(expression.evaluate(xmlDoc));
    } else {/*  w  w  w  . j a  v  a2s .  c  om*/
        // if Description is empty, then it reverts back to appending the username, git hash, etc
        nodes.item(0).setTextContent(getComment(proxyFile));
    }

    DOMSource source = new DOMSource(xmlDoc);
    StreamResult result = new StreamResult(proxyFile);
    transformer.transform(source, result);
}