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:cz.incad.kramerius.virtualcollections.VirtualCollectionsManager.java

public static VirtualCollection doVC(String pid, FedoraAccess fedoraAccess, ArrayList<String> languages) {
    try {//from  ww w.ja  va2  s .  c  o  m
        String xPathStr;
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr;

        ArrayList<String> langs = new ArrayList<String>();
        if (languages == null || languages.isEmpty()) {
            String[] ls = KConfiguration.getInstance().getPropertyList("interface.languages");
            for (int i = 0; i < ls.length; i++) {
                String lang = ls[++i];
                langs.add(lang);
            }
        } else {
            langs = new ArrayList<String>(languages);
        }
        String name = "";
        boolean canLeave = true;
        fedoraAccess.getDC(pid);
        Document doc = fedoraAccess.getDC(pid);
        xPathStr = "//dc:title/text()";
        expr = xpath.compile(xPathStr);
        Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        if (node != null) {
            name = StringEscapeUtils.escapeXml(node.getNodeValue());
        }

        xPathStr = "//dc:type/text()";
        expr = xpath.compile(xPathStr);
        node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        if (node != null) {
            canLeave = Boolean.parseBoolean(StringEscapeUtils.escapeXml(node.getNodeValue()));
        }
        VirtualCollection vc = new VirtualCollection(name, pid, canLeave);

        for (String lang : langs) {
            String dsName = TEXT_DS_PREFIX + lang;
            String value = IOUtils.readAsString(fedoraAccess.getDataStream(pid, dsName),
                    Charset.forName("UTF8"), true);
            vc.addDescription(lang, value);
        }
        return vc;
    } catch (Exception vcex) {
        logger.log(Level.WARNING, "Could not get virtual collection for  " + pid + ": " + vcex.toString());
        return null;
    }
}

From source file:Main.java

/**
 * Checks in under a given root element whether it can find a child element
 * which matches the XPath expression supplied. Returns {@link Element} if
 * exists./*from w w  w.  jav a2 s  . c o m*/
 * 
 * Please note that the XPath parser used is NOT namespace aware. So if you
 * want to find a element <beans><sec:http> you need to use the following
 * XPath expression '/beans/http'.
 * 
 * @param xPathExpression the xPathExpression (required)
 * @param root the parent DOM element (required)
 * 
 * @return the Element if discovered (null if not found)
 */
public static Element findFirstElement(String xPathExpression, Element root) {
    if (xPathExpression == null || root == null || xPathExpression.length() == 0) {
        throw new IllegalArgumentException("Xpath expression and root element required");
    }

    Element rootElement = null;
    try {

        XPathExpression expr = compiledExpressionCache.get(xPathExpression);
        if (expr == null) {
            expr = xpath.compile(xPathExpression);
            compiledExpressionCache.put(xPathExpression, expr);
        }
        rootElement = (Element) expr.evaluate(root, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Unable evaluate xpath expression", e);
    }
    return rootElement;
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.opinion.OpinionCorpusFactory.java

@Override
protected OpinionCorpusFactory addXmlPacket(OpinionCorpus corpus, InputStream input)
        throws ParserConfigurationException, SAXException, IOException, XPathException {

    Validate.notNull(corpus, CannedMessages.NULL_ARGUMENT, "corpus");
    Validate.notNull(input, CannedMessages.NULL_ARGUMENT, "input");

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*  w ww.j  ava2 s. c om*/
    Document doc = domFactory.newDocumentBuilder().parse(input);

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

    OpinionDocumentFactory opinionFactory;

    if ("document".equals(doc.getDocumentElement().getLocalName())) {
        opinionFactory = new OpinionDocumentFactory().setCorpus(corpus).setXmlNode(doc.getDocumentElement());
        corpus.addDocument(opinionFactory.create());
        return this;
    }

    Node corpusNode = (Node) xpath.compile("/corpus").evaluate(doc, XPathConstants.NODE);
    if (corpusNode == null) {
        corpusNode = Validate.notNull(doc.getDocumentElement(), CannedMessages.NULL_ARGUMENT, "/corpus");
    }

    String title = (String) xpath.compile("./@title").evaluate(corpusNode, XPathConstants.STRING);
    String description = (String) xpath.compile("./@description").evaluate(corpusNode, XPathConstants.STRING);
    String language = (String) xpath.compile("./@language").evaluate(corpusNode, XPathConstants.STRING);

    if (StringUtils.isNotEmpty(title)) {
        corpus.setTitle(title);
    }

    if (StringUtils.isNotEmpty(description)) {
        corpus.setDescription(description);
    }

    if (StringUtils.isNotEmpty(language)) {
        corpus.setLanguage(language);
    }

    NodeList documentNodes = (NodeList) xpath.compile("./document").evaluate(corpusNode,
            XPathConstants.NODESET);
    if (documentNodes == null || documentNodes.getLength() == 0) {
        documentNodes = corpusNode.getChildNodes();
        Validate.isTrue(documentNodes != null && documentNodes.getLength() > 0, CannedMessages.NULL_ARGUMENT,
                "/corpus/document");
    }

    for (int index = 0; index < documentNodes.getLength(); index++) {
        opinionFactory = new OpinionDocumentFactory().setCorpus(corpus).setXmlNode(documentNodes.item(index));
        corpus.addDocument(opinionFactory.create());
    }

    return this;
}

From source file:com.nortal.jroad.util.SOAPUtil.java

/**
 * Evaluates an {@link XPath} expression and returns a <i>single</i> matching node.
 *
 * @param context The context in which to run the expression.
 * @param expression A valid {@link XPath} expression.
 * @return {@link Node}, if one is found, <code>null</code> otherwise.
 * @throws XPathException If the provided expression is invalid or multiple nodes match.
 *//*from   w  ww . ja  v  a2 s.c o m*/
public static Node getNodeByXPath(Object context, String expression) throws XPathException {
    return (Node) XPathFactory.newInstance().newXPath().evaluate(expression, context, XPathConstants.NODE);
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.aspect.AspectLexiconFactory.java

@Override
protected AspectLexiconFactory addXmlPacket(AspectLexicon lexicon, InputStream input)
        throws ParserConfigurationException, SAXException, IOException, XPathException {

    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");
    Validate.notNull(input, CannedMessages.NULL_ARGUMENT, "input");

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*ww w.  j  ava 2s. c  o m*/
    Document doc = domFactory.newDocumentBuilder().parse(input);

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

    if ("aspect".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) {
        return this.addXmlAspect(lexicon, doc.getDocumentElement());
    }

    Node lexiconNode = (Node) xpath.compile("/aspect-lexicon").evaluate(doc, XPathConstants.NODE);
    if (lexiconNode == null) {
        lexiconNode = Validate.notNull(doc.getDocumentElement(), CannedMessages.NULL_ARGUMENT,
                "/aspect-lexicon");
    }

    String title = (String) xpath.compile("./@title").evaluate(lexiconNode, XPathConstants.STRING);
    String description = (String) xpath.compile("./@description").evaluate(lexiconNode, XPathConstants.STRING);

    if (StringUtils.isNotEmpty(title)) {
        lexicon.setTitle(title);
    }

    if (StringUtils.isNotEmpty(description)) {
        lexicon.setDescription(description);
    }

    return this.addXmlAspect(lexicon, lexiconNode);
}

From source file:ch.entwine.weblounge.bridge.oaipmh.harvester.OaiPmhResponse.java

public static Node xpathNode(XPath xpath, Node context, String expr) {
    if (expr.startsWith("/"))
        throw new IllegalArgumentException(
                "an xpath expression that evaluates relative to a given context node "
                        + "must not be absolute, i.e. start with a '/'. In this case the expression is evaluated against the"
                        + "whole document which might not be wanted.");
    try {//w w w.  java2  s  .co  m
        return (Node) xpath.evaluate(expr, context, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("malformed xpath expression " + expr, e);
    }
}

From source file:com.vitembp.services.imaging.OverlayDefinition.java

/**
 * Initializes a new instance of the OverlayDefinition class.
 * @param toBuildFrom /*  w  w  w  .  ja  v  a 2  s . com*/
 */
private OverlayDefinition(String toBuildFrom) throws IOException {
    // load the definition from XML using xpath methods
    // first parse the document
    Document def;
    try {
        def = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(toBuildFrom.getBytes(Charsets.UTF_8)));
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        throw new IOException("Could not parse XML input.", ex);
    }
    // prevents issues caused by parser returning multiple text elements for
    // a single text area
    def.getDocumentElement().normalize();

    // get the overlay type
    XPath xPath = XPathFactory.newInstance().newXPath();
    try {
        Node type = (Node) xPath.evaluate("/overlay/type", def, XPathConstants.NODE);
        this.overlayType = OverlayType.valueOf(type.getTextContent());
    } catch (XPathExpressionException | IllegalArgumentException ex) {
        throw new IOException("Exception parsing type.", ex);
    }

    // get element definitions
    try {
        NodeList elements = (NodeList) xPath.evaluate("/overlay/elements/element", def, XPathConstants.NODESET);

        this.elementDefinitions = new ArrayList<>();
        for (int i = 0; i < elements.getLength(); i++) {
            this.elementDefinitions.add(new ElementDefinition(elements.item(i)));
        }
    } catch (XPathExpressionException | IllegalArgumentException ex) {
        throw new IOException("Exception parsing elements.", ex);
    }
}

From source file:com.amalto.core.save.context.BeforeSaving.java

public void save(SaverSession session, DocumentSaverContext context) {
    // Invoke the beforeSaving
    MutableDocument updateReportDocument = context.getUpdateReportDocument();
    if (updateReportDocument == null) {
        throw new IllegalStateException("Update report is missing."); //$NON-NLS-1$
    }/*w w  w .ja v a  2  s. c om*/
    OutputReport outputreport = session.getSaverSource().invokeBeforeSaving(context, updateReportDocument);

    if (outputreport != null) { // when a process was found
        String errorCode;
        message = outputreport.getMessage();
        if (!validateFormat(message))
            throw new BeforeSavingFormatException(message);
        try {
            Document doc = Util.parse(message);
            // handle output_report
            String xpath = "//report/message"; //$NON-NLS-1$
            Node errorNode;
            synchronized (XPATH) {
                errorNode = (Node) XPATH.evaluate(xpath, doc, XPathConstants.NODE);
            }
            errorCode = null;
            if (errorNode instanceof Element) {
                Element errorElement = (Element) errorNode;
                errorCode = errorElement.getAttribute("type"); //$NON-NLS-1$
                Node child = errorElement.getFirstChild();
                if (child instanceof org.w3c.dom.Text) {
                    message = child.getTextContent();
                } else {
                    message = ""; //$NON-NLS-1$   
                }
            }

            if (!"info".equals(errorCode)) { //$NON-NLS-1$
                throw new BeforeSavingErrorException(message);
            }

            // handle output_item
            if (outputreport.getItem() != null) {
                xpath = "//exchange/item"; //$NON-NLS-1$
                SkipAttributeDocumentBuilder builder = new SkipAttributeDocumentBuilder(
                        SaverContextFactory.DOCUMENT_BUILDER, false);
                doc = builder.parse(new InputSource(new StringReader(outputreport.getItem())));
                Node item;
                synchronized (XPATH) {
                    item = (Node) XPATH.evaluate(xpath, doc, XPathConstants.NODE);
                }
                if (item != null && item instanceof Element) {
                    Node node = null;
                    Node current = item.getFirstChild();
                    while (current != null) {
                        if (current instanceof Element) {
                            node = current;
                            break;
                        }
                        current = item.getNextSibling();
                    }
                    if (node != null) {
                        // set back the modified item by the process
                        DOMDocument document = new DOMDocument(node, context.getUserDocument().getType(),
                                context.getDataCluster(), context.getDataModelName());
                        context.setUserDocument(document);
                        context.setDatabaseDocument(null);
                        // Redo a set of actions and security checks.
                        // TMDM-4599: Adds UpdateReport phase so a new update report is generated based on latest changes.
                        next = new ID(
                                new GenerateActions(new Security(new UpdateReport(new ApplyActions(next)))));
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Exception occurred during before saving phase.", e); //$NON-NLS-1$
        }
    }

    next.save(session, context);
}

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

/**
 * Parses the job instance represented by <code>xml</code> and extracts the job identifier.
 * /*from w  w w .  j ava  2s  . c o m*/
 * @param xml
 *          the job instance
 * @return the job identifier
 * @throws Exception
 *           if parsing fails
 */
public static String getJobId(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:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

@Override
public InputStream generateEhCacheConfig() {
    try {/*from  w ww  . j a  va2  s .  co m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setExpandEntityReferences(false);
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        Document document = documentBuilder.parse(this.getClass().getResourceAsStream(EHCACHE_XML_CONFIG));
        // <diskStore path="java.io.tmpdir"/>
        XPathExpression compile = pathFactory.compile("ehcache/diskStore"); //$NON-NLS-1$
        Node node = (Node) compile.evaluate(document, XPathConstants.NODE);
        node.getAttributes().getNamedItem("path") //$NON-NLS-1$
                .setNodeValue(dataSource.getCacheDirectory() + '/' + dataSource.getName());
        return toInputStream(document);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}