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.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get the author affiliations for a given article
 * @param doc article xml//from  w  ww. j  av  a  2  s . c o m
 * @param doc article xml
 * @return author affiliations
 */
public ArrayList<AuthorExtra> getAuthorAffiliations(Document doc) {

    ArrayList<AuthorExtra> list = new ArrayList<AuthorExtra>();
    Map<String, String> affiliateMap = new HashMap<String, String>();

    if (doc == null) {
        return list;
    }

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

        XPathExpression affiliationListExpr = xpath.compile("//aff");
        XPathExpression affiliationAddrExpr = xpath.compile("//addr-line");

        NodeList affiliationNodeList = (NodeList) affiliationListExpr.evaluate(doc, XPathConstants.NODESET);

        // Map all affiliation id's to their affiliation strings
        for (int i = 0; i < affiliationNodeList.getLength(); i++) {
            Node node = affiliationNodeList.item(i);
            // Not all <aff>'s have the 'id' attribute.
            String id = (node.getAttributes().getNamedItem("id") == null) ? ""
                    : node.getAttributes().getNamedItem("id").getTextContent();
            // Not all <aff> id's are affiliations.
            if (id.startsWith("aff")) {
                DocumentFragment df = doc.createDocumentFragment();
                df.appendChild(node);
                String address = ((Node) affiliationAddrExpr.evaluate(df, XPathConstants.NODE))
                        .getTextContent();
                affiliateMap.put(id, address);
            }
        }

        XPathExpression authorExpr = xpath.compile("//contrib-group/contrib[@contrib-type='author']");
        XPathExpression surNameExpr = xpath.compile("//name/surname");
        XPathExpression givenNameExpr = xpath.compile("//name/given-names");
        XPathExpression affExpr = xpath.compile("//xref[@ref-type='aff']");

        NodeList authorList = (NodeList) authorExpr.evaluate(doc, XPathConstants.NODESET);

        for (int i = 0; i < authorList.getLength(); i++) {
            Node cnode = authorList.item(i);
            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(cnode);
            Node sNode = (Node) surNameExpr.evaluate(df, XPathConstants.NODE);
            Node gNode = (Node) givenNameExpr.evaluate(df, XPathConstants.NODE);

            // Either surname or givenName can be blank
            String surname = (sNode == null) ? "" : sNode.getTextContent();
            String givenName = (gNode == null) ? "" : gNode.getTextContent();
            // If both are null then don't bother to add
            if ((sNode != null) || (gNode != null)) {
                NodeList affList = (NodeList) affExpr.evaluate(df, XPathConstants.NODESET);
                ArrayList<String> affiliations = new ArrayList<String>();

                // Build a list of affiliations for this author
                for (int j = 0; j < affList.getLength(); j++) {
                    Node anode = affList.item(j);
                    String affId = anode.getAttributes().getNamedItem("rid").getTextContent();
                    affiliations.add(affiliateMap.get(affId));
                }

                AuthorExtra authorEx = new AuthorExtra();
                authorEx.setAuthorName(surname, givenName);
                authorEx.setAffiliations(affiliations);
                list.add(authorEx);
            }
        }
    } catch (Exception e) {
        log.error("Error occurred while gathering the author affiliations.", e);
    }

    return list;
}

From source file:com.photon.phresco.impl.ConfigManagerImpl.java

private Node getNode(String xpath) throws ConfigurationException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath newXPath = xPathFactory.newXPath();
    XPathExpression xPathExpression;
    Node xpathNode = null;/*  w ww  . j  a va  2s.  c o  m*/
    try {
        xPathExpression = newXPath.compile(xpath);
        xpathNode = (Node) xPathExpression.evaluate(document, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new ConfigurationException(e);
    }
    return xpathNode;
}

From source file:com.photon.phresco.impl.ConfigManagerImpl.java

private NodeList getNodeList(String xpath) throws ConfigurationException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath newXPath = xPathFactory.newXPath();
    XPathExpression xPathExpression;
    NodeList xpathNodes = null;/*  w  ww  . j  a  v a2s .c o m*/
    try {
        xPathExpression = newXPath.compile(xpath);
        xpathNodes = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new ConfigurationException(e);
    }
    return xpathNodes;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderXPath.java

@Override
public void initialize(UimaContext arg0) throws ResourceInitializationException {
    super.initialize(arg0);

    fileIterator = getFileSetIterator();
    XPath xpath = XPathFactory.newInstance().newXPath();
    nodes = new ArrayDeque<Node>();

    if (StringUtils.isWhitespace(rootXPath)) {
        throw new IllegalArgumentException("Illegal root XPath expression. Please provide a valid one.");
    }/*w w w.j  a va2s. c om*/
    try {
        compiledRootXPath = xpath.compile(rootXPath);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Illegal root XPath expression. Please provide a valid one.");
    }

    if (docIdTag != null) {
        if (StringUtils.isWhitespace(docIdTag)) {
            throw new IllegalArgumentException("Illegal ID XPath expression. Please provide a valid one.");
        }
        try {
            compiledIdXPath = xpath.compile(docIdTag);
        } catch (XPathExpressionException e) {
            throw new IllegalArgumentException("Illegal ID XPath expression. Please provide a valid one.");
        }
    }

    // Substitution
    if (substituteTags != null && substituteTags.length > 0) {
        if (substituteTags.length % 2 != 0) {
            throw new IllegalArgumentException("Parameter substitute tags must "
                    + "be given in an array of even number of elements, in 'before, after' order");
        }

        useSubstitution = true;
        substitution = new HashMap<String, String>(substituteTags.length);
        for (int i = 0; i < substituteTags.length; i += 2) {
            substitution.put(substituteTags[i], substituteTags[i + 1]);
        }
    }

    processNextFile();
}

From source file:org.codice.ddf.admin.sources.opensearch.OpenSearchSourceUtils.java

public UrlAvailability getUrlAvailability(String url, String un, String pw) {
    UrlAvailability result = new UrlAvailability(url);
    boolean queryResponse;
    int status;//from  ww  w.  ja v  a2  s. co  m
    String contentType;
    HttpGet request = new HttpGet(url + SIMPLE_QUERY_PARAMS);
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;

    if (url.startsWith("https") && un != null && pw != null) {
        byte[] auth = Base64.encodeBase64((un + ":" + pw).getBytes());
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    try {
        client = getCloseableHttpClient(false);
        response = client.execute(request);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document responseXml = builder.parse(response.getEntity().getContent());
        queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                XPathConstants.BOOLEAN);
        status = response.getStatusLine().getStatusCode();
        contentType = response.getEntity().getContentType().getValue();
        if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
            return result.trustedCertAuthority(true).certError(false).available(true);
        } else {
            return result.trustedCertAuthority(true).certError(false).available(false);
        }
    } catch (SSLPeerUnverifiedException e) {
        // This is the hostname != cert name case - if this occurs, the URL's SSL cert configuration
        // is incorrect, or a serious network security issue has occurred.
        return result.trustedCertAuthority(false).certError(true).available(false);
    } catch (Exception e) {
        try {
            closeClientAndResponse(client, response);
            client = getCloseableHttpClient(true);
            response = client.execute(request);
            status = response.getStatusLine().getStatusCode();
            contentType = response.getEntity().getContentType().getValue();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document responseXml = builder.parse(response.getEntity().getContent());
            queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                    XPathConstants.BOOLEAN);
            if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
                return result.trustedCertAuthority(false).certError(false).available(true);
            }
        } catch (Exception e1) {
            return result.trustedCertAuthority(false).certError(false).available(false);
        }
    } finally {
        closeClientAndResponse(client, response);
    }
    return result;
}

From source file:com.rest4j.generator.Generator.java

List<ModelNode> computeModelGraph(Document xml) throws Exception {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    xpath.setNamespaceContext(new APINamespaceContext());
    XPathExpression refsExpr = xpath.compile(".//api:complex");
    HashMap<String, ModelNode> graph = new HashMap<String, ModelNode>();
    for (Node model : Util.it(xml.getDocumentElement().getElementsByTagName("model"))) {
        String name = ((Attr) model.getAttributes().getNamedItem("name")).getValue();
        graph.put(name, new ModelNode(model));
    }/*from  w  w w  .j ava 2s.  co m*/
    for (ModelNode node : graph.values()) {
        for (Node complex : Util.it((NodeList) refsExpr.evaluate(node.model, XPathConstants.NODESET))) {
            Ref ref = new Ref();
            String type = complex.getAttributes().getNamedItem("type").getTextContent();
            ModelNode referenced = graph.get(type);
            if (referenced == null)
                throw new IllegalArgumentException("Wrong reference from "
                        + node.model.getAttributes().getNamedItem("name").getTextContent() + "."
                        + complex.getAttributes().getNamedItem("name").getTextContent() + " to " + type);
            ref.referencedModel = referenced;
            if (complex.getAttributes().getNamedItem("collection").getTextContent().equals("array")) {
                ref.array = true;
            }
            node.references.add(ref);
        }
    }
    return new ArrayList<ModelNode>(graph.values());
}

From source file:de.codesourcery.jasm16.ide.ProjectConfiguration.java

private void parseXML(Document doc) throws XPathExpressionException {
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();

    final XPathExpression nameExpr = xpath.compile("/project/name");
    final XPathExpression outputFolderExpr = xpath.compile("/project/outputFolder");
    final XPathExpression executableNameExpr = xpath.compile("/project/executableName");
    final XPathExpression srcFoldersExpr = xpath.compile("/project/sourceFolders/sourceFolder");
    final XPathExpression emulationOptionsExpr = xpath.compile("/project/emulationOptions");
    final XPathExpression buildOptionsExpr = xpath.compile("/project/buildOptions");
    final XPathExpression srcFilePatternsExpr = xpath
            .compile("/project/sourceFilenamePatterns/sourceFilenamePattern");
    final XPathExpression compilationRootExpr = xpath.compile("/project/compilationRoot");
    final XPathExpression debuggerOptionsExpr = xpath.compile("/project/debuggerOptions");

    this.outputFolder = getValue(outputFolderExpr, doc);
    this.projectName = getValue(nameExpr, doc);
    this.executableName = getValue(executableNameExpr, doc);
    this.sourceFolders.clear();
    this.sourceFolders.addAll(getValues(srcFoldersExpr, doc));

    // compilation root
    final List<String> roots = getValues(compilationRootExpr, doc);
    if (!roots.isEmpty()) {
        if (roots.size() > 1) {
            throw new RuntimeException("Parse error, more than one compilation root in project config XML ?");
        }/*from   ww w.j  a va 2s. c om*/
        setCompilationRoot(new File(roots.get(0)));
    }

    // parse srcfile name patterns
    final List<String> patterns = getValues(srcFilePatternsExpr, doc);
    if (!patterns.isEmpty()) {
        setSourceFilenamePatterns(new HashSet<>(patterns));
    }

    // parse emulation options
    Element element = getElement(emulationOptionsExpr, doc);
    if (element == null) {
        this.emulationOptions = new EmulationOptions();
    } else {
        this.emulationOptions = EmulationOptions.loadEmulationOptions(element);
    }

    // parse build options
    element = getElement(buildOptionsExpr, doc);
    if (element == null) {
        this.buildOptions = new BuildOptions();
    } else {
        this.buildOptions = BuildOptions.loadBuildOptions(element);
    }

    // parse build options
    element = getElement(debuggerOptionsExpr, doc);
    if (element == null) {
        this.debuggerOptions.reset();
    } else {
        this.debuggerOptions.loadDebuggerOptions(element);
    }
}

From source file:org.ala.harvester.FlickrHarvester.java

/**
 * Retrieves a map of licences.//  ww w .  ja  v a 2 s. c o m
 * 
 * @return
 */
private Map<String, Licence> getLicencesMap() throws Exception {

    final String flickrMethodUri = "flickr.photos.licenses.getInfo";
    String urlToSearch = this.flickrRestBaseUrl + "/" + "?method=" + flickrMethodUri + "&api_key="
            + this.flickrApiKey;

    logger.info(urlToSearch);
    logger.debug("URL to search is: " + "`" + urlToSearch + "`" + "\n");

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(urlToSearch);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    method.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "UTF-8");
    method.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8");

    try {
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            String errMsg = "HTTP GET to " + "`" + urlToSearch + "`"
                    + " returned non HTTP OK code.  Returned code " + statusCode + " and message "
                    + method.getStatusLine() + "\n";
            method.releaseConnection();
            throw new Exception(errMsg);
        }

        //parse the response
        InputStream responseStream = method.getResponseBodyAsStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(responseStream);
        XPathFactory xfactory = XPathFactory.newInstance();
        XPath xpath = xfactory.newXPath();

        XPathExpression xe = xpath.compile("/rsp/licenses/license");
        NodeList nodeSet = (NodeList) xe.evaluate(doc, XPathConstants.NODESET);

        Map<String, Licence> licencesMap = new HashMap<String, Licence>();

        for (int i = 0; i < nodeSet.getLength(); i++) {
            NamedNodeMap map = nodeSet.item(i).getAttributes();
            String id = map.getNamedItem("id").getNodeValue();
            Licence licence = new Licence();
            licence.setName(map.getNamedItem("name").getNodeValue());
            licence.setUrl(map.getNamedItem("url").getNodeValue());
            licencesMap.put(id, licence);
        }
        return licencesMap;

    } catch (Exception httpErr) {
        String errMsg = "HTTP GET to `" + urlToSearch + "` returned HTTP error.";
        throw new Exception(errMsg, httpErr);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:com.alvexcore.repo.masterdata.getConstraintWork.java

protected List<Map<String, String>> getRestXmlMasterData(NodeRef source) throws Exception {
    NodeService nodeService = serviceRegistry.getNodeService();
    String url = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_URL);
    String rootXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_ROOT_QUERY);
    String labelXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_LABEL);
    String valueXPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_XPATH_VALUE);
    String caching = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_REST_CACHE_MODE);

    // Standard of reading a XML file
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);// ww  w. j  ava2s.  c  om
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(url);

    // Create a XPathFactory
    XPathFactory xFactory = XPathFactory.newInstance();

    // Create a XPath object
    XPath xpath = xFactory.newXPath();

    // Compile the XPath expression
    XPathExpression setExpr = xpath.compile(rootXPath);
    XPathExpression valueExpr = xpath.compile(valueXPath);
    XPathExpression labelExpr = xpath.compile(labelXPath);

    // Run the query and get a nodeset
    Object result = setExpr.evaluate(doc, XPathConstants.NODESET);

    // Cast the result to a list
    NodeList nodes = (NodeList) result;
    List<Map<String, String>> res = new ArrayList<Map<String, String>>();
    for (int i = 0; i < nodes.getLength(); i++) {
        String value = (String) valueExpr.evaluate(nodes.item(i), XPathConstants.STRING);
        String label = (String) labelExpr.evaluate(nodes.item(i), XPathConstants.STRING);
        HashMap<String, String> resItem = new HashMap<String, String>();
        resItem.put("ref", "");
        resItem.put("value", value);
        resItem.put("label", label);
        res.add(resItem);
    }
    return res;
}

From source file:eu.forgetit.middleware.component.Extractor.java

private String parseUserID(String inputFile) {

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {//from   www . ja va 2s.c  om
        builder = builderFactory.newDocumentBuilder();

        Document document = builder.parse(new File(inputFile));

        XPathFactory xpathFactory = XPathFactory.newInstance();

        XPath xpath = xpathFactory.newXPath();

        XPathExpression expr = xpath.compile("/Image_analysis_methods/@userID");

        String userID = (String) expr.evaluate(document, XPathConstants.STRING);

        System.out.println("userID: " + userID);

        return userID;

    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
        e.printStackTrace();
    }

    return null;

}