Example usage for javax.xml.xpath XPath compile

List of usage examples for javax.xml.xpath XPath compile

Introduction

In this page you can find the example usage for javax.xml.xpath XPath compile.

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

From source file:org.dasein.cloud.azure.Azure.java

public @Nullable String getStorageService() throws CloudException, InternalException {
    if (storageService == null) {
        ProviderContext ctx = getContext();

        if (ctx == null) {
            throw new AzureConfigException("No configuration was set for this request");
        }/*ww w  .ja  v  a2 s . c o  m*/
        AzureMethod method = new AzureMethod(this);

        Document xml = method.getAsXML(ctx.getAccountNumber(), "/services/storageservices");

        if (xml == null) {
            throw new CloudException("Unable to identify the storage service");
        }
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        try {
            XPathExpression expr = xpath
                    .compile("(/StorageServices/StorageService/StorageServiceProperties[GeoPrimaryRegion='"
                            + ctx.getRegionId() + "']/../ServiceName)[1]");
            storageService = expr.evaluate(xml).trim();
        } catch (XPathExpressionException e) {
            throw new CloudException(
                    "Failed to find storage service in the current region: " + ctx.getRegionId());
        }

        if (storageService == null || storageService.isEmpty())
            storageService = null;
    }
    return storageService;
}

From source file:com.espertech.esper.event.xml.SimpleXMLEventType.java

protected EventPropertyGetter doResolvePropertyGetter(String propertyExpression) {
    EventPropertyGetter getter = propertyGetterCache.get(propertyExpression);
    if (getter != null) {
        return getter;
    }//www.  jav  a2s .com

    if (!this.getConfigurationEventTypeXMLDOM().isXPathPropertyExpr()) {
        Property prop = PropertyParser.parse(propertyExpression, false);
        getter = prop.getGetterDOM();
        if (!prop.isDynamic()) {
            getter = new DOMConvertingGetter(propertyExpression, (DOMPropertyGetter) getter, String.class);
        }
    } else {
        XPathExpression xPathExpression;
        String xPathExpr;
        boolean isDynamic;
        try {
            Tree ast = PropertyParser.parse(propertyExpression);
            isDynamic = PropertyParser.isPropertyDynamic(ast);

            xPathExpr = SimpleXMLPropertyParser.parse(ast, propertyExpression, getRootElementName(),
                    defaultNamespacePrefix, isResolvePropertiesAbsolute);
            XPath xpath = getXPathFactory().newXPath();
            xpath.setNamespaceContext(namespaceContext);
            if (log.isInfoEnabled()) {
                log.info("Compiling XPath expression for property '" + propertyExpression + "' as '" + xPathExpr
                        + "'");
            }
            xPathExpression = xpath.compile(xPathExpr);
        } catch (XPathExpressionException e) {
            throw new EPException(
                    "Error constructing XPath expression from property name '" + propertyExpression + '\'', e);
        }

        QName xPathReturnType;
        if (isDynamic) {
            xPathReturnType = XPathConstants.NODE;
        } else {
            xPathReturnType = XPathConstants.STRING;
        }
        getter = new XPathPropertyGetter(propertyExpression, xPathExpr, xPathExpression, xPathReturnType, null,
                null);
    }

    // no fragment factory, fragments not allowed
    propertyGetterCache.put(propertyExpression, getter);
    return getter;
}

From source file:eumetsat.pn.common.ISO2JSON.java

private void appendIfResultNotNull(XPath xpath, Document xml, StringBuilder sb, String expression)
        throws XPathExpressionException {
    String result = xpath.compile(expression).evaluate(xml);
    if (result != null) {
        sb.append(result.trim());/*  w  w w  .  j  a  va 2s  .  c  o m*/
    }
}

From source file:android.databinding.tool.store.LayoutFileParser.java

private List<Node> get(Document doc, XPath xPath, String pattern) throws XPathExpressionException {
    final XPathExpression expr = xPath.compile(pattern);
    return toList((NodeList) expr.evaluate(doc, XPathConstants.NODESET));
}

From source file:com.rax.deployment.TopologyUpdateClient.java

private boolean isRmiURIinXML(String topologyXML)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dbFactory.newDocumentBuilder();

    ByteArrayInputStream input = new ByteArrayInputStream(topologyXML.getBytes("UTF-8"));
    Document doc = builder.parse(input);
    // doc.getDocumentElement().normalize();
    XPath xPath = XPathFactory.newInstance().newXPath();
    String rmiuri = getConfiguration().getThisHostname() + ":" + getConfiguration().getRmiPort();
    String expression = "/publishing-deployment-topology/target/agent/transport/rmi-uri";
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        String val = nodeList.item(i).getFirstChild().getNodeValue();
        vlogDebug("The node uri obtained: " + val);
        if (val.contains(rmiuri)) {
            vlogInfo("Agent already added for " + rmiuri);
            return true;
        }/*w ww.j a  v  a 2 s. c o  m*/
    }

    return false;

}

From source file:org.apache.servicemix.wsn.jms.JmsSubscription.java

protected boolean doFilter(Element content) {
    if (contentFilter != null) {
        if (!contentFilter.getDialect().equals(XPATH1_URI)) {
            throw new IllegalStateException("Unsupported dialect: " + contentFilter.getDialect());
        }/*from   w w  w. j a v a  2s.c o  m*/
        try {
            XPathFactory xpfactory = XPathFactory.newInstance();
            XPath xpath = xpfactory.newXPath();
            XPathExpression exp = xpath.compile(contentFilter.getContent().get(0).toString());
            Boolean ret = (Boolean) exp.evaluate(content, XPathConstants.BOOLEAN);
            return ret.booleanValue();
        } catch (XPathExpressionException e) {
            log.warn("Could not filter notification", e);
        }
        return false;
    }
    return true;
}

From source file:android.databinding.tool.store.LayoutFileParser.java

private File stripFileAndGetOriginal(File xml, String binderId)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    L.d("parsing resource file %s", xml.getAbsolutePath());
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xml);
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    final XPathExpression commentElementExpr = xPath
            .compile("//comment()[starts-with(., \" From: file:\")][last()]");
    final NodeList commentElementNodes = (NodeList) commentElementExpr.evaluate(doc, XPathConstants.NODESET);
    L.d("comment element nodes count %s", commentElementNodes.getLength());
    if (commentElementNodes.getLength() == 0) {
        L.d("cannot find comment element to find the actual file");
        return null;
    }/*from   w ww  . j  a  v  a 2s.c  o  m*/
    final Node first = commentElementNodes.item(0);
    String actualFilePath = first.getNodeValue().substring(" From:".length()).trim();
    L.d("actual file to parse: %s", actualFilePath);
    File actualFile = urlToFile(new java.net.URL(actualFilePath));
    if (!actualFile.canRead()) {
        L.d("cannot find original, skipping. %s", actualFile.getAbsolutePath());
        return null;
    }

    // now if file has any binding expressions, find and delete them
    // TODO we should rely on namespace to avoid parsing file twice
    boolean changed = isBindingLayout(doc, xPath);
    if (changed) {
        stripBindingTags(xml, binderId);
    }
    return actualFile;
}

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);//from  ww  w  .  j ava  2  s .  c  o m
    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:edu.sabanciuniv.sentilab.sare.controllers.aspect.AspectLexiconFactory.java

protected AspectLexiconFactory addXmlAspect(AspectLexicon lexicon, Node aspectNode)
        throws XPathExpressionException {

    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");
    Validate.notNull(aspectNode, CannedMessages.NULL_ARGUMENT, "node");

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

    // if the node is called "lexicon" then we're at the root, so we won't need to add an aspect and its expressions.
    AspectLexicon aspect = lexicon;/*  w  w w.java 2s . c o  m*/
    if (!"aspect-lexicon".equalsIgnoreCase(aspectNode.getLocalName())) {
        String title = Validate.notEmpty(
                (String) xpath.compile("./@title").evaluate(aspectNode, XPathConstants.STRING),
                CannedMessages.EMPTY_ARGUMENT, "./aspect/@title");
        ;

        // fetch or create aspect.
        aspect = lexicon.findAspect(title);
        if (aspect == null) {
            aspect = lexicon.addAspect(title);
        }

        // get all expressions or keywords, whatever they're called.
        NodeList expressionNodes = (NodeList) xpath.compile("./expressions/expression").evaluate(aspectNode,
                XPathConstants.NODESET);
        if (expressionNodes == null || expressionNodes.getLength() == 0) {
            expressionNodes = (NodeList) xpath.compile("./keywords/keyword").evaluate(aspectNode,
                    XPathConstants.NODESET);
        }

        // add each of them if they don't exist.
        if (expressionNodes != null) {
            for (int index = 0; index < expressionNodes.getLength(); index++) {
                String expression = expressionNodes.item(index).getTextContent().trim();
                if (!aspect.hasExpression(expression)) {
                    aspect.addExpression(expression);
                }
            }
        }
    }

    // get all sub-aspects and add them recursively.
    NodeList subAspectNodes = (NodeList) xpath.compile("./aspects/aspect").evaluate(aspectNode,
            XPathConstants.NODESET);
    if (subAspectNodes != null) {
        for (int index = 0; index < subAspectNodes.getLength(); index++) {
            this.addXmlAspect(aspect, subAspectNodes.item(index));
        }
    }

    return this;
}

From source file:com.vimeo.VimeoUploadClient.java

/**
 * parse xml response/*from w w  w . ja va 2s.  com*/
 * 
 * @param content
 * @param path
 * @param returnType
 * @return
 */
private Object path(String content, String path, QName returnType) {
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(content)));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile(path);
        return expr.evaluate(doc, returnType);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}