Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:com.freedomotic.helpers.HttpHelper.java

public HttpHelper() {
    try {/* w  w  w . j a v  a 2s.  c  o  m*/
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        LOG.error(ex.getMessage());
    }
    XPathFactory xpathFactory = XPathFactory.newInstance();
    xPath = xpathFactory.newXPath();
    setConnectionTimeout(DEFAULT_TIMEOUT);
}

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

/**
 * create xpath and assign the namespace resolver for InspectCode namespace
 * @return xpath//from www .  ja v  a2s.co m
 */
private XPath createXPathForInspectCode() {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    NamespaceContext inspectCodeNamespaceResolver = new InspectCodeNamespaceResolver();
    xpath.setNamespaceContext(inspectCodeNamespaceResolver);
    return xpath;
}

From source file:cz.strmik.cmmitool.cmmi.DefaultRatingScalesProvider.java

private List<RatingScale> readScales(String id, String lang) {
    List<RatingScale> scales = new ArrayList<RatingScale>();
    try {//  w ww . j a v  a 2s . c  o m
        Document document = getScalesDocument();

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

        SimpleNamespaceContext ns = new SimpleNamespaceContext();
        ns.bindNamespaceUri("s", SCALES_XML_NS);
        xPath.setNamespaceContext(ns);

        XPathExpression exprScales = xPath.compile("/s:ratings/s:rating[@id='" + id + "']/s:scale");
        XPathExpression exprName = xPath.compile("s:name[@lang='" + lang + "']");
        XPathExpression exprColor = xPath.compile("s:color[@type='html']");

        NodeList nodes = (NodeList) exprScales.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            int score = Integer.parseInt(node.getAttributes().getNamedItem("score").getTextContent());

            String name = exprName.evaluate(node);
            String color = exprColor.evaluate(node);
            RatingScale rs = new RatingScale(name, i, score, color);
            if (i == 0) {
                rs.setDefaultRating(true);
            }
            scales.add(rs);
        }
    } catch (Exception ex) {
        _log.warn(
                "Unable to load default scales for id=" + id + ",lang=" + lang + " ratings from " + SCALES_XML,
                ex);
    }
    return scales;
}

From source file:at.sti2.spark.handler.ImpactoriumHandler.java

public String extractInfoObjectIdentifier(String infoObjectResponse) {

    String reportId = null;/* w w  w.j  av a 2 s  . com*/

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //dbf.setNamespaceAware(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8")));

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//info-object");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;
        Node item = nodes.item(0);
        if (item != null) {
            NamedNodeMap attributesMap = item.getAttributes();
            Node idAttribute = attributesMap.getNamedItem("id");
            reportId = idAttribute.getNodeValue();
        }

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

    return reportId;
}

From source file:io.hakbot.providers.appspider.AppSpiderProvider.java

private String getScanName(String decodedScanConfig) {
    final XPathFactory xpathFactory = XPathFactory.newInstance();
    final XPath xpath = xpathFactory.newXPath();
    final InputSource source = new InputSource(new StringReader(decodedScanConfig));
    String scanName = null;/*from w ww .j a  v  a 2 s .c o m*/
    try {
        scanName = xpath.evaluate("/ScanConfig/Name", source);
    } catch (XPathExpressionException e) {
        LOGGER.error("Error processing scan file: " + e.getMessage());
    }
    return scanName;
}

From source file:com.intel.hadoop.graphbuilder.demoapps.wikipedia.docwordgraph.WordCountGraphTokenizer.java

public void parse(String s) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from w  w w .j  a  v  a2s  . co m
    DocumentBuilder builder;
    counts = new HashMap<String, Integer>();
    try {
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(s)));
        XPathFactory xfactory = XPathFactory.newInstance();
        XPath xpath = xfactory.newXPath();
        title = xpath.evaluate("//page/title/text()", doc);
        title = title.replaceAll("\\s", "_");
        // title = title.replaceAll("^[^a-zA-Z0-9]", "#");
        // title = title.replaceAll("[^a-zA-Z0-9.]", "_");
        id = xpath.evaluate("//page/id/text()", doc);
        String text = xpath.evaluate("//page/revision/text/text()", doc);

        if (!text.isEmpty()) {
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
            TokenStream stream = analyzer.tokenStream(null, new StringReader(text));
            while (stream.incrementToken()) {
                String token = stream.getAttribute(TermAttribute.class).term();

                if (dictionary != null && !dictionary.contains(token))
                    continue;

                if (counts.containsKey(token))
                    counts.put(token, counts.get(token) + 1);
                else
                    counts.put(token, 1);
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}

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);/*  w  w  w .  ja  v  a2  s. com*/
    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:it.jnrpe.plugin.tomcat.TomcatDataProvider.java

private void parseMemoryData() throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(tomcatXML));

    Document doc = builder.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    //Element root = (Element) xpath.compile("//status").evaluate(doc.getDocumentElement(), XPathConstants.NODE);
    Element memory = (Element) xpath.compile("//status/jvm/memory").evaluate(doc.getDocumentElement(),
            XPathConstants.NODE);

    long freeMem = Long.parseLong(memory.getAttribute("free"));
    long totalMem = Long.parseLong(memory.getAttribute("total"));
    long maxMem = Long.parseLong(memory.getAttribute("max"));

    jvmMemoryUsage = new MemoryData(freeMem, maxMem, totalMem);
}

From source file:org.jasig.portlet.proxy.search.GsaSearchStrategy.java

@Override
public List<SearchResult> search(SearchRequest searchQuery, EventRequest request,
        org.jsoup.nodes.Document ignore) {

    List<SearchResult> searchResults = new ArrayList<SearchResult>();

    String searchBaseURL = this.buildGsaUrl(searchQuery, request);
    HttpClient client = new DecompressingHttpClient(new DefaultHttpClient());
    HttpGet get = new HttpGet(searchBaseURL);

    try {//w  w w  . j  a va2 s . com

        HttpResponse httpResponse = client.execute(get);
        log.debug("STATUS CODE :: " + httpResponse.getStatusLine().getStatusCode());

        InputStream in = httpResponse.getEntity().getContent();

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = docFactory.newDocumentBuilder();

        Document doc = builder.parse(in);

        log.debug(("GOT InputSource"));
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();

        Integer maxCount = Integer.parseInt(xPath.evaluate("count(/GSP/RES/R)", doc));

        final String[] whitelistRegexes = request.getPreferences().getValues("gsaWhitelistRegex",
                new String[] {});

        log.debug(maxCount + " -- Results");
        for (int count = 1; count <= maxCount; count++) {
            String u = xPath.evaluate("/GSP/RES/R[" + count + "]/U/text()", doc);
            String t = xPath.evaluate("/GSP/RES/R[" + count + "]/T/text()", doc);
            String s = xPath.evaluate("/GSP/RES/R[" + count + "]/S/text()", doc);

            log.debug("title: [" + t + "]");
            SearchResult result = new SearchResult();
            result.setTitle(t);
            result.setSummary(s);

            PortletUrl pUrl = new PortletUrl();
            pUrl.setPortletMode(PortletMode.VIEW.toString());
            pUrl.setType(PortletUrlType.RENDER);
            pUrl.setWindowState(WindowState.MAXIMIZED.toString());
            PortletUrlParameter param = new PortletUrlParameter();
            param.setName("proxy.url");
            param.getValue().add(u);
            pUrl.getParam().add(param);
            result.setPortletUrl(pUrl);

            new SearchUtil().updateUrls(u, request, whitelistRegexes);
            searchResults.add(result);
        }

    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
    } catch (XPathExpressionException ex) {
        log.error(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        log.error(ex.getMessage(), ex);
    } catch (SAXException ex) {
        log.error(ex.getMessage(), ex);
    }

    return searchResults;

}

From source file:it.jnrpe.plugin.tomcat.TomcatDataProvider.java

private void parseMemoryPools() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(tomcatXML));

    Document doc = builder.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();

    NodeList memoryPoolList = (NodeList) xpath.compile("//status/jvm/memorypool")
            .evaluate(doc.getDocumentElement(), XPathConstants.NODESET);

    for (int i = 0; i < memoryPoolList.getLength(); i++) {
        Node poolNode = memoryPoolList.item(i);
        NamedNodeMap atts = poolNode.getAttributes();
        final String poolName = atts.getNamedItem("name").getNodeValue();
        long usageInit = Long.parseLong(atts.getNamedItem("usageInit").getNodeValue());
        long usageCommitted = Long.parseLong(atts.getNamedItem("usageCommitted").getNodeValue());
        long usageMax = Long.parseLong(atts.getNamedItem("usageMax").getNodeValue());
        long usageUsed = Long.parseLong(atts.getNamedItem("usageUsed").getNodeValue());

        memoryPoolData.put(poolName,//  w w  w.j a v a  2 s . c o m
                new MemoryPoolData(poolName, usageInit, usageCommitted, usageMax, usageUsed));
    }
}