Example usage for javax.xml.xpath XPathFactory newInstance

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

Introduction

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

Prototype

public static XPathFactory newInstance() 

Source Link

Document

Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.

This method is functionally equivalent to:

 newInstance(DEFAULT_OBJECT_MODEL_URI) 

Since the implementation for the W3C DOM is always available, this method will never fail.

Usage

From source file:nl.opengeogroep.filesetsync.client.plugin.SetFileXpathToHttpRequestHeaderPlugin.java

private void updateHeader(String header) {
    String file = null, xpathString = null, lastModified = null, lastValue = null;
    try {//from   ww  w. ja  v  a  2 s  .  c  o  m
        Properties props = headers.get(header);
        if (props == null || !props.containsKey("file") || !props.containsKey("xpath")) {
            log.warn("Invalid configuration for header " + header + ", ignoring");
            return;
        }
        file = props.getProperty("file");
        xpathString = props.getProperty("xpath");
        lastModified = props.getProperty("lastModified");
        lastValue = props.getProperty("lastValue");

        File f = new File(file);
        if (!f.exists() || !f.canRead()) {
            log.warn(String.format("Cannot read value for header \"%s\" from file \"%s\"", header, file));
            return;
        }

        if (lastModified != null && lastModified.equals(f.lastModified() + "")) {
            log.trace("File for header value " + header + " was not modified, keeping value " + lastValue);
            return;
        }

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);
        XPath xpath = XPathFactory.newInstance().newXPath();
        String value = xpath.evaluate(xpathString, doc);

        log.info(String.format("Value extracted from file \"%s\" using xpath \"%s\": %s", file, xpathString,
                value));

        props.put("lastValue", value);
        props.put("lastModified", f.lastModified() + "");

    } catch (Exception e) {
        log.error(String.format(
                "Error updating header %s, file=%s, xpathString=%s, lastModified=%s, lastValue=%s", header,
                file, xpathString, lastModified, lastValue), e);
    }
}

From source file:com.hotwire.test.steps.application.IosApplication.java

public String getExpectedAnalytics(String analyticsParams) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/* w  w w .j  a  v  a 2s  .  c  om*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("vertical");
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    String paramsToPath = "//" + (analyticsParams.replaceAll(":", "/")) + "/node()";
    XPathExpression expr = xpath.compile(paramsToPath);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < nodes.getLength(); i++) {
        sb.append((nodes.item(i).getNodeName() + "=" + nodes.item(i).getTextContent()).trim());
    }
    String expectedParams = sb.toString().replaceAll("#text=", ";");

    return expectedParams;
}

From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java

/**
 * Return the hits coming from the response of an OS-Interface.
 * /*from ww  w  . j av a2  s  . c om*/
 * @param doc
 *            is the converted response into a document structure
 * @param plugId
 * @param totalResults
 * @param groupedBy
 * @return
 * @throws XPathExpressionException
 */
private IngridHit[] getHits(Document doc, String plugId, int totalResults, String groupedBy)
        throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate("/rss/channel/item", doc, XPathConstants.NODESET);
    IngridHit[] hits = new IngridHit[nodes.getLength()];

    for (int i = 0; i < nodes.getLength(); i++) {
        IngridHit hit = new IngridHit(plugId, "0", 0, (float) 1.0);
        Node node = nodes.item(i);
        hit.put("title", getTitle(node));
        hit.put("url", getLink(node));
        hit.put("abstract", getAbstract(node));
        hit.put("no_of_hits", String.valueOf(totalResults));
        hit.setScore(getScore(node));

        // ingrid specific data
        setIngridHitDetail(hit, node, groupedBy);

        hits[i] = hit;
    }

    // now we have all original hits, let's manipulate the score
    normalizeRanking(hits);

    return hits;
}

From source file:com.norconex.committer.gsa.XmlOutputTest.java

@Test
public void testWriteMultipleRecords() throws Exception {

    File file = tempFolder.newFile();
    FileOutputStream out = new FileOutputStream(file);
    XmlOutput xmlOutput = new XmlOutput(out);

    Properties metadata1 = new Properties();
    metadata1.addString("url", "http://www.corp.enterprise.com/hello01");
    metadata1.addString("mimetype", "text/plain");
    metadata1.addString("collector.content-type", "text/plain");
    metadata1.addString("last-modified", "Tue, 6 Nov 2007 12:45:26 GMT");
    metadata1.addString("Date", "Tue, 6 Nov 2007 12:45:26 GMT");
    String content1 = "This is hello01";

    Properties metadata2 = new Properties();
    metadata2.addString("url", "http://www.corp.enterprise.com/hello02");
    metadata2.addString("mimetype", "text/plain");
    metadata2.addString("collector.content-type", "text/plain");
    metadata2.addString("last-modified", "Tue, 6 Nov 2009 22:45:26 GMT");
    metadata2.addString("Date", "Tue, 6 Nov 2009 22:45:26 GMT");
    String content2 = "This is hello02";

    xmlOutput.write(Arrays.asList(buildMockAddOperation(metadata1, content1),
            buildMockAddOperation(metadata2, content2)));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document doc = dbf.newDocumentBuilder().parse(file);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate("/gsafeed/group/record", doc, XPathConstants.NODESET);
    assertEquals(2, nodes.getLength());/*from ww w  .  jav a 2s . c  o m*/
}

From source file:br.com.insula.spring.security.janrain.JanrainService.java

private XPath createXPath() {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    return xPathFactory.newXPath();
}

From source file:edu.cornell.mannlib.vitro.utilities.containerneutral.CheckContainerNeutrality.java

@BeforeClass
public static void createXPath() {
    xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new StupidNamespaceContext());
}

From source file:com.streak.logging.analysis.AnalysisUtility.java

public static List<String> fetchCloudStorageUris(String bucketName, String startKey, String endKey,
        HttpRequestFactory requestFactory) throws IOException {
    List<String> result = new ArrayList<String>();

    String bucketUri = "http://commondatastorage.googleapis.com/" + bucketName;
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(bucketUri + "?marker=" + startKey));
    HttpResponse response = request.execute();

    try {//from  w  w w .  j  a v  a 2  s . c o m
        Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getContent());
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key/text()", responseDoc,
                XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            String key = nodes.item(i).getNodeValue();
            if (key.compareTo(endKey) >= 0) {
                break;
            }
            if (key.endsWith(".schema.json")) {
                continue;
            }
            result.add("gs://" + bucketName + "/" + key);
        }
    } catch (SAXException e) {
        throw new IOException("Error parsing cloud storage response", e);
    } catch (ParserConfigurationException e) {
        throw new IOException("Error configuring cloud storage parser", e);
    } catch (XPathExpressionException e) {
        throw new IOException("Error finding keys", e);
    }

    return result;
}

From source file:com.cisco.dvbu.ps.common.adapters.config.AdapterConfig.java

private void parseAdapterCommon(Document doc) throws AdapterException {
    log.debug("Root element :" + doc.getDocumentElement().getNodeName());
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {/* w  w w  .j  a  v a 2s  . co m*/
        Attr a = (Attr) xpath.evaluate(AdapterConstants.XPATH_CONFIG_VERSION, doc, XPathConstants.NODE);
        log.debug(a.getName() + ": " + a.getValue());
        Element e = (Element) xpath.evaluate(AdapterConstants.XPATH_NAME, doc, XPathConstants.NODE);
        name = e.getTextContent();
        log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_DESC, doc, XPathConstants.NODE);
        desc = e.getTextContent();
        log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CIS_VERSION, doc, XPathConstants.NODE);
        cisVersion = e.getTextContent();
        log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_RETRYATTMPTS, doc, XPathConstants.NODE);
        retryAttempts = (e != null && e.getTextContent() != null) ? Integer.parseInt(e.getTextContent()) : -1;
        log.debug("retryAttempts: " + retryAttempts);
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_MAXCLIENTS, doc, XPathConstants.NODE);
        maxClients = (e != null && e.getTextContent() != null) ? Integer.parseInt(e.getTextContent()) : -1;
        log.debug("maxclients: " + maxClients);
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_MINCLIENTS, doc, XPathConstants.NODE);
        minClients = (e != null && e.getTextContent() != null) ? Integer.parseInt(e.getTextContent()) : -1;
        log.debug("minclients: " + minClients);
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(302,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
}

From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java

AbstractTwitterPath(TwitterProvider twitterProvider, String path) throws Exception {
    this.path = path;
    this.provider = twitterProvider;

    domFac = DocumentBuilderFactory.newInstance();
    factory = XPathFactory.newInstance();
    xpath = factory.newXPath();//from ww w  .  ja va  2  s  .c o  m
    transformer = TransformerFactory.newInstance().newTransformer();
}

From source file:com.cordys.coe.ac.httpconnector.samples.JIRAResponseHandler.java

/**
 * This method checks the HTML for errors during processing.
 * //from   w  w w  .  j  ava2s. c o m
 * @param document
 *            The HTML document.
 * @param httpMethod
 *            The actual HTTP method that was executed.
 * 
 * @throws HandlerException
 *             In case the response contains any functional errors.
 * @throws XPathExpressionException
 *             In case one of the XPaths fail.
 */
protected void checkErrors(org.w3c.dom.Document document, HttpMethod httpMethod)
        throws HandlerException, XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate("//span[@class='errMsg']/text()", document,
            XPathConstants.NODESET);
    int length = nodeList.getLength();

    if (length != 0) {
        // The first error message found will be used.
        HandlerException he = new HandlerException(
                HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML,
                nodeList.item(0).getNodeValue());

        for (int i = 0; i < length; i++) {
            Node node = nodeList.item(i);
            he.addAdditionalErrorMessage(node.getNodeValue());
        }
        throw he;
    }

    // There is another possibility of which errors might be returned. There
    // is a td with
    // class formErrors. And it that holds the errors as list items.
    nodeList = (NodeList) xpath.evaluate("//td[@class='formErrors']/div[@class='errorArea']/ul/li/text()",
            document, XPathConstants.NODESET);
    length = nodeList.getLength();

    if (length != 0) {
        // The first error message found will be used.
        HandlerException he = new HandlerException(
                HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML,
                nodeList.item(0).getNodeValue());

        for (int i = 0; i < length; i++) {
            Node node = nodeList.item(i);
            he.addAdditionalErrorMessage(node.getNodeValue());
        }
        throw he;
    }

    if (httpMethod.getStatusCode() == 500) {
        // Find the short description
        Node n = (Node) xpath.evaluate("//b[.='Cause: ']", document, XPathConstants.NODE);
        String shortError = n.getNextSibling().getNextSibling().getNodeValue().trim();

        // The first error message found will be used.
        HandlerException he = new HandlerException(
                HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML,
                "System Error: " + shortError);

        // Find the stacktrace if available.
        he.addAdditionalErrorMessage(
                (String) xpath.evaluate("//pre[@id='stacktrace']/text()", document, XPathConstants.STRING));

        throw he;
    }
}