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:ru.cti.gosuslugi.service.client.OffenceInfoServiceClient.java

private OffenceInfoForProgrammaticSystems getOffenceInfoList(String response)
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException,
        TransformerFactoryConfigurationError, TransformerException, JAXBException {
    Document responseDocument = buildXmlDocumentFromString(response);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate("//Body/*", responseDocument, XPathConstants.NODESET);

    StringWriter sw = new StringWriter();

    if (serializer == null)
        serializer = TransformerFactory.newInstance().newTransformer();

    serializer.transform(new DOMSource(nodeList.item(0)), new StreamResult(sw));
    String res = sw.toString();/*from  w  ww .j a  v a  2  s  . co m*/

    logger.debug("offence body: {}", res);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    return (OffenceInfoForProgrammaticSystems) unmarshaller
            .unmarshal(new ByteArrayInputStream(res.getBytes("UTF-8")));

}

From source file:com.webwoz.wizard.server.components.MToutMicrosoft.java

public String translate(String inputText, String srcLang, String trgLang) {

    // initialize connection
    // adapt proxy and settings to fit your server environments
    initializeConnection("www-proxy.cs.tcd.ie", 8080);
    String translation = null;/*from  w  w w  .ja  v  a  2s .c o m*/
    String query = inputText;
    String MICROSOFT_TRANSLATION_BASE_URL = "http://api.microsofttranslator.com/V2/Http.svc/Translate?";
    String appID = "226846CE16BC2542B7916B05CE9284CF4075B843";

    try {
        // encode text
        query = URLEncoder.encode(query, "UTF-8");
        // exchange + for space
        query = query.replace("+", "%20");
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
        System.out.println(ex);
    }

    String requestURL = MICROSOFT_TRANSLATION_BASE_URL + "appid=" + appID + "&from=" + srcLang + "&to="
            + trgLang + "&text=" + query;

    HttpGet getRequest = new HttpGet(requestURL);

    try {
        HttpResponse response = httpClient.execute(getRequest);
        HttpEntity responseEntity = response.getEntity();

        InputStream inputStream = responseEntity.getContent();

        Document myDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);

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

        translation = (String) xPath.evaluate("/string", myDocument, XPathConstants.STRING);

        inputStream.close();

        translation = translation.trim();

        // if the original string did not have a dot at the end, then
        // remove the dot that Microsoft Translator sometimes places at the
        // end!! (not so sure it still happens anyway!)
        if (!inputText.endsWith(".") && (translation.endsWith("."))) {
            translation = translation.substring(0, translation.length() - 1);
        }

        setUttText(translation);

    } catch (Exception ex) {
        ex.printStackTrace();
        translation = ex.toString();
        setUttText(translation);
        System.out.println(translation);
    }

    shutDownConnection();
    return translation;
}

From source file:com.photon.phresco.framework.impl.ConfigurationWriter.java

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

From source file:dk.statsbiblioteket.doms.iprolemapper.webservice.IPRangesConfigReader.java

/**
 * Produce a <code>List</code> of <code>IPRangeRoles</code> instances
 * constructed from the information read from the XML configuration
 * specified by <code>rangesConfigFile</code>.
 * /*from w  w w .  j  a va2s  .  co m*/
 * @param rangesConfigFile
 *            a <code>File</code> instance configured with the path to the
 *            XML configuration file to read.
 * @return a list of <code>IPRangeRoles</code> instances, produced from the
 *         contents of the configuration file.
 * @throws IOException
 *             if any errors are encountered while reading the configuration
 *             file.
 */
public List<IPRangeRoles> readFromXMLConfigFile(File rangesConfigFile) throws IOException {

    if (log.isTraceEnabled()) {
        log.trace("readFromXMLConfigFile(): Called with file path: " + rangesConfigFile);
    }

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    NodeList ipRangeNodes = null;

    try {
        final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        final Document configuationDocument = documentBuilder.parse(rangesConfigFile);

        final XPathFactory xPathFactory = XPathFactory.newInstance();
        final XPath xPath = xPathFactory.newXPath();

        ipRangeNodes = (NodeList) xPath.evaluate("/ipranges/iprange", configuationDocument,
                XPathConstants.NODESET);
    } catch (ParserConfigurationException parserConfigException) {
        throw new IOException("Failed setting up parser", parserConfigException);
    } catch (SAXException saxException) {
        throw new IOException("Failed parsing configuration file '" + rangesConfigFile + "'", saxException);

    } catch (XPathExpressionException xPathExpressionException) {
        throw new IOException("Failed parsing (evaluating) configuration" + " file '" + rangesConfigFile + "'",
                xPathExpressionException);

    }
    final List<IPRangeRoles> ipRangeList = new LinkedList<IPRangeRoles>();
    for (int nodeIdx = 0; nodeIdx < ipRangeNodes.getLength(); nodeIdx++) {
        try {
            ipRangeList.add(produceIPRangeInstance(ipRangeNodes.item(nodeIdx)));
        } catch (Exception cause) {
            String ipRangeNodeXMLString = "Malformed IpRange.";
            try {
                ipRangeNodeXMLString = DOM.domToString(ipRangeNodes.item(nodeIdx));
            } catch (Exception eTwo) {
                // Exception being ignored
            }
            Logs.log(log, Logs.Level.WARN, "readFromXMLConfigFile() failed to read IPRange: ",
                    ipRangeNodeXMLString, cause);
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("readFromXMLConfigFile(): Returning IP address ranges: " + ipRangeList);
    }
    return ipRangeList;
}

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

/**
 * Harvest a document and update the repository.
 * /* w ww .  j  av  a2  s. c o m*/
 * @param infosourceId
 * @param url
 * @throws Exception
 */
private void harvestDoc(int infosourceId, String url) throws Exception {
    byte[] content = null;

    System.out.println("******** request: " + url);
    Object[] resp = restfulClient.restGet(url);
    if ((Integer) resp[0] == HttpStatus.SC_OK) {
        content = resp[1].toString().getBytes("UTF-8");
    }

    if (content != null) {
        List<String> ids = new ArrayList<String>();
        String keyUrl = connectionParams.get(KEY_END_POINT_ATTR_NAME);

        // Instantiates a DOM builder to create a DOM of the response.
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        // return a parsed Document
        Document doc = builder.parse(new ByteArrayInputStream(content));

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

        XPathExpression xe = xpath.compile("//keys/key[@id]");
        NodeList nodeSet = (NodeList) xe.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nodeSet.getLength(); i++) {
            NamedNodeMap map = nodeSet.item(i).getAttributes();
            ids.add(map.getNamedItem("id").getNodeValue());
        }

        for (int i = 0; i < ids.size(); i++) {
            Object[] res = restfulClient.restGet(keyUrl + "/" + ids.get(i));
            if ((Integer) res[0] == HttpStatus.SC_OK) {
                //map the document 
                List<ParsedDocument> pds = documentMapper.map(keyUrl + ids.get(i),
                        res[1].toString().getBytes());

                //store the results
                for (ParsedDocument pd : pds) {
                    //debugParsedDoc(pd);
                    repository.storeDocument(infosourceId, pd);
                    logger.debug("Parent guid for stored doc: " + pd.getParentGuid());
                }
            }
        }
    } else {
        logger.warn("Unable to process url: " + url);
    }
}

From source file:es.sistedes.handle.generator.Conversor.java

/**
 * Converts the XML data available in the <code>input</code>
 * {@link InputStream} and dumps the result in the <code>output</code>
 * {@link OutputStream}//from ww  w .jav a  2  s  . c  o m
 * 
 * @throws ConversionException
 *             If any error occurs, check
 *             {@link ConversionException#getCause()} to figure out the exact
 *             cause
 */
public synchronized void generate() throws ConversionException {

    PrintWriter outputWriter = new PrintWriter(output);

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(input);

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

        NodeList list = (NodeList) xpath.evaluate(
                "//channel/item[link and guid and postmeta[meta_key/text()='handle']]", doc,
                XPathConstants.NODESET);

        Boolean useGuid = useGuid();
        Boolean addDelete = addDelete();

        Map<String, String> vars = new HashMap<String, String>();
        vars.put(HandleVariables.prefix.toString(), prefix);

        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            String handle = xpath.evaluate("postmeta[meta_key/text()='handle']/meta_value/text()", node);
            if (filter() != null) {
                // We use a regex in the Node instead of a XPath filter in
                // the NodeList because Java only supports XPath 1 and the
                // "matches" function has been introduced in XPath 2
                Pattern pattern = Pattern.compile(filter());
                if (!pattern.matcher(handle).matches()) {
                    continue;
                }
            }
            vars.put(HandleVariables.handle.toString(), handle);
            vars.put(HandleVariables.url.toString(),
                    useGuid ? xpath.evaluate("guid/text()", node) : xpath.evaluate("link/text()", node));

            if (addDelete) {
                outputWriter.println(StrSubstitutor.replace(commands.get("command.delete"), vars));
            }
            outputWriter.println(StrSubstitutor.replace(commands.get("command.create"), vars));
            outputWriter.println(StrSubstitutor.replace(commands.get("command.admin"), vars));
            outputWriter.println(StrSubstitutor.replace(commands.get("command.url"), vars));
            outputWriter.println();
        }
    } catch (Exception e) {
        throw new ConversionException(e);
    } finally {
        outputWriter.flush();
    }
}

From source file:com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase.java

private void parseCreateScriptConfigFile() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document configDoc = builder//from  w  w  w  . j  a v a  2  s .  c o  m
            .parse(MultiDBBaseTestCase.class.getClassLoader().getResourceAsStream(getCreateScriptConfigFile()));
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    NodeList databaseList = (NodeList) xpath.compile("/databases/database").evaluate(configDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < databaseList.getLength(); i++) {
        MultiCreateTableScriptEntry entry = new MultiCreateTableScriptEntry();
        Element ele = (Element) databaseList.item(i);
        entry.setDbName(ele.getAttribute("name"));
        NodeList tableList = (NodeList) xpath.compile("tables/table").evaluate(ele, XPathConstants.NODESET);
        Map<String, String> map = new HashMap<String, String>();
        for (int j = 0; j < tableList.getLength(); j++) {
            Element tableEle = (Element) tableList.item(j);
            map.put(tableEle.getAttribute("name"), tableEle.getTextContent());
        }
        entry.setTableNameScriptMapping(map);
        createdTableList.add(entry);
    }
}

From source file:com.provenance.cloudprovenance.policyhandler.ws.support.PolicyRequestProcessor.java

public String getIdforPolicyMatch(String responseContent, String xpathToDocumentId)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
        XPathFactoryConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from  w w w. ja  va 2  s. c  om
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(responseContent));
    Document doc = builder.parse(is);

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    xpath.setNamespaceContext(cProvMapper);

    XPathExpression xPathExpr;
    xPathExpr = xpath.compile(xpathToDocumentId);

    logger.debug("XpathExpression to match: " + xpathToDocumentId);
    logger.debug("Document to match is: " + responseContent);

    return (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Return the child of the node selected by the xPath.
 * //from w  ww .  ja v a 2  s . c  o m
 * @param node The node.
 * @param xpathExpression The XPath expression as string
 * 
 * @return The child of the node selected by the xPath
 * 
 * @throws TransformerException If anything fails.
 */
public static Node selectSingleNode(final Node node, final String xpathExpression) throws TransformerException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        return (Node) xPath.evaluate(xpathExpression, node, XPathConstants.NODE);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase.java

private List<DBDataEntry> parseDataFile() throws Exception {
    List<DBDataEntry> datas = new ArrayList<DBDataEntry>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document configDoc = builder/*w w w .j a  va2 s. c  om*/
            .parse(MultiDBBaseTestCase.class.getClassLoader().getResourceAsStream(getDataFile()));
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    NodeList databaseList = (NodeList) xpath.compile("/dataset/database").evaluate(configDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < databaseList.getLength(); i++) {
        DBDataEntry entry = new DBDataEntry();
        Element ele = (Element) databaseList.item(i);
        entry.setDbName(ele.getAttribute("name"));
        NodeList scriptNodeList = ele.getChildNodes();
        List<String> scripts = new ArrayList<String>();
        for (int j = 0; j < scriptNodeList.getLength(); j++) {
            scripts.add(scriptNodeList.item(j).getTextContent());
        }
        entry.setScripts(scripts);
        datas.add(entry);
    }

    return datas;

}