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:com.synclio.hawk.TutorialRouteBuilder.java

@Override
public void configure() throws Exception {
    from("ghttp:///weather").process(new RequestProcessor()).marshal().serialization().to("gtask://default")
            .unmarshal().serialization().process(new ResponseProcessor());

    from("gtask://default").unmarshal().serialization().process(new Processor() {
        @Override/*from w ww  . j  a v a2 s . c om*/
        public void process(Exchange exchange) throws Exception {
            ReportData data = exchange.getIn().getBody(ReportData.class);

            URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
            HTTPRequest req = new HTTPRequest(new URL("http://where.yahooapis.com/v1/places.q(" + data.getCity()
                    + ")?appid=0b4twNzV34GzaTHevW1SzEcnzG4Nyuhq6pvnSKZS.28kCqUw31jPRApe6_niElSL_waLc2M-"),
                    HTTPMethod.GET);
            HTTPResponse resp = urlFetch.fetch(req);

            Document doc = toDocument(IOUtils.toInputStream(new String(resp.getContent())));
            XPathFactory xpfactory = XPathFactory.newInstance();
            XPath xpath = xpfactory.newXPath();
            try {
                System.out.print(xpath.evaluate("//places/place[1]/woeid/text()", doc));
                System.out.print(new String(resp.getContent()));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });
    //         .setHeader(Exchange.HTTP_METHOD,constant("GET"))
    //         .enrich("ghttp://where.yahooapis.com/v1/places.q(Chennai)?appid=0b4twNzV34GzaTHevW1SzEcnzG4Nyuhq6pvnSKZS.28kCqUw31jPRApe6_niElSL_waLc2M-")         .setHeader(GMailBinding.GMAIL_SUBJECT, constant("Weather report"))
    //         .setHeader(GMailBinding.GMAIL_SENDER, ReportData.requestor())
    //         .setHeader(GMailBinding.GMAIL_TO, ReportData.recipient())
    //         .process(new ReportGenerator())
    //         .to("gmail://default");
}

From source file:com.mediaworx.xmlutils.XmlHelper.java

/**
 * Creates and initializes a new XmlHelper instance.
 * @throws ParserConfigurationException if for some reason the DocumentBuilder used to parse the XML can't be
 *                                      initialized
 *//*  www .  j a v  a 2  s  .  c  o  m*/
public XmlHelper() throws ParserConfigurationException {
    builder = getNonValidatingDocumentBuilder();
    xPathfactory = XPathFactory.newInstance();
}

From source file:org.joy.config.Configuration.java

public void loadConfiguration() {
    try {/*w  ww .  j a v a 2  s .c  o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(configurationFile);

        XPathFactory f = XPathFactory.newInstance();
        XPath path = f.newXPath();

        parseClassPathEntry(doc, path);
        parseConnections(doc, path);
        parseTemplates(doc, path);

        tagertProject = path.evaluate("/configuration/tagertProject/text()", doc);
        basePackage = path.evaluate("/configuration/basePackage/text()", doc);
        moduleName = path.evaluate("/configuration/moduleName/text()", doc);
    } catch (Exception e) {
        throw new Wrong(e);
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.toolbox.XPointerResourceResolver.java

public XPointerResourceResolver(Node baseNode) {

    this.xPathFactory = XPathFactory.newInstance();
    this.baseNode = baseNode;
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionNamespaceContextHelperTest.java

@Test
public void testReturnNamespaceMapFromNode() throws Exception {
    //Retrieve ER xpath context
    XPath xpath;//w  ww.j  av a2 s  . c  o m
    xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new EntityResolutionNamespaceContext());

    //Get the test attribute parameters configuration
    InputStream attributeParametersStream = getClass().getResourceAsStream("/xml/TestAttributeParameters.xml");
    assertNotNull(attributeParametersStream);

    //Convert to DOM document
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);

    Document attributeParametersDocument = converter.toDOMDocument(attributeParametersStream);

    NodeList parameterNodes = null;

    //Perform Xpath to retrieve attribute parameters
    parameterNodes = (NodeList) xpath.evaluate("er-ext:AttributeParameter",
            attributeParametersDocument.getDocumentElement(), XPathConstants.NODESET);

    //Loop through attribute parameters to retrieve namespace map associated with attribute xpath
    for (int i = 0; i < parameterNodes.getLength(); i++) {
        Node node = parameterNodes.item(i);

        String attributeXpathValue = xpath.evaluate("er-ext:AttributeXPath", node);
        Map<String, String> namespaceMap = EntityResolutionNamespaceContextHelpers
                .returnNamespaceMapFromNode(attributeXpathValue, node);

        for (Map.Entry<String, String> entry : namespaceMap.entrySet()) {
            LOG.debug("Namespace Map Entry, Prefix : " + entry.getKey() + " Namespace : " + entry.getValue());
        }

        if (attributeXpathValue.equals("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName")) {
            assertEquals("http://niem.gov/niem/niem-core/2.0", namespaceMap.get("nc"));
            assertEquals("http://local.org/IEPD/Extensions/PersonSearchResults/1.0", namespaceMap.get("ext"));
        }

        if (attributeXpathValue.equals("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName")) {
            assertEquals("http://niem.gov/niem/niem-core/2.0", namespaceMap.get("nc"));
            assertEquals("http://local.org/IEPD/Extensions/PersonSearchResults/1.0", namespaceMap.get("ext"));
        }

    }
}

From source file:au.edu.rmit.GalagoSearchClient.java

protected Document runSnippet(String id, List<String> terms)
        throws ParserConfigurationException, UnsupportedEncodingException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    XPath xpath = XPathFactory.newInstance().newXPath();

    String baseURI = "http://" + this.host + ":" + Integer.toString(this.port) + "/snippet";
    String uri = baseURI + "?identifier=" + id;
    for (String term : terms)
        uri += "&term=" + URLEncoder.encode(term, "UTF-8");

    Document result;/*from w  w  w. j  a  va2s  .  com*/

    try {
        result = builder.parse(uri);
    } catch (Exception e) {
        e.printStackTrace();
        result = builder.newDocument();
    }

    return result;
}

From source file:com.oracle.tutorial.jdbc.ProductInformationTable.java

public void populateTable(String fileName)
        throws SQLException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    // factory.setNamespaceAware(true);
    factory.setNamespaceAware(true);/*from   www.  j  a  v a 2 s  .  c  o m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    NodeList nodes = (NodeList) xPath.evaluate("/coffee-product-information/item[coffee = 'Columbian']", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node currentNode = nodes.item(i);
        // Retrieve the description element

        currentNode.normalize();

        if (currentNode == null) {
            System.out.println("Current node is null");
        }

        //      System.out.println(currentNode.getTextContent());

        Node descriptionNode = (Node) xPath.evaluate("description", currentNode, XPathConstants.NODE);

        if (descriptionNode == null) {
            System.out.println("DescriptionNode is null");
        } else {

            System.out.println(descriptionNode.getTextContent());

            NodeList descriptionNodeChildren = descriptionNode.getChildNodes();
            System.out.println("Description node has " + descriptionNodeChildren.getLength() + " child nodes");
            Node descNodeChild = descriptionNode.getFirstChild();
            System.out.println("Only child node type: " + descNodeChild.getNodeType());
        }

        //      System.out.println("Description: " + descriptionNode.getNodeValue());

        // System.out.println(nodes.item(i).getNodeValue());
    }

}

From source file:org.apache.solr.kelvin.responseanalyzers.XmlDoclistExtractorResponseAnalyzer.java

public void configure(JsonNode config) throws Exception {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    expr = xpath.compile("/response/result/doc");

}

From source file:org.trustedanalytics.hadoop.admin.tools.HadoopClientParamsImporter.java

static Optional<Map<String, String>> scanConfigZipArchive(InputStream source)
        throws IOException, XPathExpressionException {

    InputStream zipInputStream = new ZipInputStream(new BufferedInputStream(source));
    ZipEntry zipFileEntry;/* ww  w  .ja  v  a2  s.c  o  m*/
    Map<String, String> ret = new HashMap<>();
    while ((zipFileEntry = ((ZipInputStream) zipInputStream).getNextEntry()) != null) {
        if (!zipFileEntry.getName().endsWith("-site.xml")) {
            continue;
        }
        byte[] bytes = IOUtils.toByteArray(zipInputStream);
        InputSource is = new InputSource(new ByteArrayInputStream(bytes));
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate(CONF_PROPERTY_XPATH, is, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node propNode = nodeList.item(i);
            String key = (String) xPath.evaluate("name/text()", propNode, XPathConstants.STRING);
            String value = (String) xPath.evaluate("value/text()", propNode, XPathConstants.STRING);
            ret.put(key, value);
        }
    }
    return Optional.of(ret);
}

From source file:dk.dma.msinm.web.rest.LocationRestService.java

/**
 * Parses the KML and returns a JSON list of locations.
 *
 * TDOD: Handle MultiGeometry.//from  w w w.  ja va2 s  .  c o  m
 * Example: http://www.microformats.dk/2008/11/02/kommunegrnserne-til-de-98-danske-kommuner/
 *
 * @param kml the KML to parse
 * @return the corresponding list of locations
 */
@POST
@Path("/parse-kml")
@Produces("application/json")
public List<LocationVo> parseKml(String kml) throws UnsupportedEncodingException {

    // Strip BOM from UTF-8 with BOM
    if (kml.startsWith("\uFEFF")) {
        kml = kml.replace("\uFEFF", "");
    }

    // Extract the default namespace
    String namespace = extractDefaultNamespace(kml);

    List<LocationVo> result = new ArrayList<>();
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new KmlNamespaceContext(namespace));
    InputSource inputSource = new InputSource(new StringReader(kml));

    try {
        // Fetch all "Placemark" elements
        NodeList placemarks = (NodeList) xpath.evaluate("//kml:Placemark", inputSource, XPathConstants.NODESET);

        for (int i = 0; i < placemarks.getLength(); i++) {

            // Fetch all "Point" coordinates
            NodeList coordinates = (NodeList) xpath.evaluate("//kml:Point/kml:coordinates", placemarks.item(i),
                    XPathConstants.NODESET);
            extractLocations(result, coordinates, Location.LocationType.POINT);

            // Fetch all "Polyline" coordinates
            coordinates = (NodeList) xpath.evaluate("//kml:LineString/kml:coordinates", placemarks.item(i),
                    XPathConstants.NODESET);
            extractLocations(result, coordinates, Location.LocationType.POLYLINE);

            // Fetch all "Polygon" coordinates
            coordinates = (NodeList) xpath.evaluate(
                    "//kml:Polygon/kml:outerBoundaryIs/kml:LinearRing/kml:coordinates", placemarks.item(i),
                    XPathConstants.NODESET);
            extractLocations(result, coordinates, Location.LocationType.POLYGON);
        }

    } catch (Exception e) {
        log.error("Error parsing kml", e);
    }

    return result;
}