Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.BcrExperimentFieldValidator.java

/**
 * checks all tags in a file/*from   www.  ja  va  2s  .  c  om*/
 *  @param xmlFile to check for XSDElements
 */

private boolean checkXmlFile(final File xmlFile, final QcContext context, List<String> clinicalElementList)
        throws ProcessorException {
    NodeList nodes = null;
    try {
        final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
        final XPath xpath = XPathFactory.newInstance().newXPath();
        nodes = (NodeList) xpath.evaluate(PATIENT_XPATH, document, XPathConstants.NODESET);
    } catch (XPathException e) {
        throw new ProcessorException("Unable to evaluate " + PATIENT_XPATH + " expression ", e);
    } catch (Exception e) {
        // same handling no matter what is thrown by parser
        throw new ProcessorException("Unable to parse file: " + xmlFile.getName(), e);
    }

    if (nodes.getLength() == 0) {
        throw new ProcessorException("No patient node found in file " + xmlFile.getName());
    }
    if (nodes.getLength() > 1) {
        throw new ProcessorException("More than one patient node found in file " + xmlFile.getName());
    }

    return parse(nodes.item(0), context, clinicalElementList, xmlFile.getName());

}

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

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

    // initialize connection
    // adapt proxies and settings to fit your server environment
    initializeConnection("www-proxy.cs.tcd.ie", 8080);
    String translation = null;/*from w ww . j  a v a  2  s  .  co 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();
    }

    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();
    }

    shutDownConnection();
    return translation;
}

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;/* www  .j av  a2s .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:de.dplatz.padersprinter.control.TripService.java

Optional<List<Leg>> parseLegs(Node node) {
    XPath xpath = XPathFactory.newInstance().newXPath();

    try {//from  w w w  .  j  ava2  s. c o m
        NodeList legNodes = (NodeList) xpath.evaluate(".//table[contains(@class, 'legTable')]", node,
                XPathConstants.NODESET);

        final List<Leg> legs = new LinkedList<>();

        logger.debug("Number of legs indentified: " + legNodes.getLength());
        for (int i = 0; i < legNodes.getLength(); i++) {
            Optional<Leg> leg = parseLeg(legNodes.item(i), xpath);

            if (!leg.isPresent()) {
                logger.info("At least one leg could not be parsed. Ignoring trip.");
                return Optional.empty();
            }

            legs.add(leg.get());
        }
        return Optional.of(legs);
    } catch (Exception ex) {
        logger.log(Level.ERROR, null, ex);
        return Optional.empty();
    }
}

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>.
 * /*w w  w.j  a v a 2s. c om*/
 * @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:dk.statsbiblioteket.doms.iprolemapper.webservice.IPRangesConfigReader.java

/**
 * This method produces an <code>IPRangeRoles</code> instance from the
 * information stored in the <code>Node</code> specified by
 * <code>ipRangeNode</code>.
 * /*from  w  ww . j a va 2 s  .c  o  m*/
 * @param ipRangeNode
 *            a <code>Document Node</code> containing information about an
 *            IP range and its associated roles.
 * @return an <code>IPRangeRoles</code> instance created from the
 *         information contained in <code>ipRangeNode</code>.
 * @throws XPathExpressionException
 *             if any errors are encountered while reading range roles from
 *             <code>ipRangeNode</code>.
 * @throws UnknownHostException
 *             if the begin or end address of <code>ipRangeNode</code> is
 *             either an unknown host name or an illegal IP address.
 * @throws IllegalArgumentException
 *             if the begin address and end address of the range is not of
 *             the same type. I.e. if they are not both IPv4 or IPv6
 *             addresses, or if <code>beginAddress</code> is higher/after
 *             <code>endAddress</code>.
 */
private IPRangeRoles produceIPRangeInstance(Node ipRangeNode)
        throws XPathExpressionException, IllegalArgumentException, UnknownHostException {

    if (log.isTraceEnabled()) {

        String ipRangeNodeXMLString = "Malformed XML";
        try {
            ipRangeNodeXMLString = DOM.domToString(ipRangeNode);
        } catch (TransformerException transformerException) {
            // Just ignore for now and log. The code will break later...
        }

        log.trace("produceIPRangeInstance(): Called with XML node: " + ipRangeNodeXMLString);
    }

    final NamedNodeMap attributes = ipRangeNode.getAttributes();
    final String beginAddress = attributes.getNamedItem("begin").getNodeValue();
    final String endAddress = attributes.getNamedItem("end").getNodeValue();

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

    final NodeList ipRangeRoleNodes = (NodeList) xPath.evaluate("role", ipRangeNode, XPathConstants.NODESET);

    final List<String> ipRangeRoles = new LinkedList<String>();
    for (int nodeIdx = 0; nodeIdx < ipRangeRoleNodes.getLength(); nodeIdx++) {
        ipRangeRoles.add(ipRangeRoleNodes.item(nodeIdx).getTextContent().trim());
    }

    final IPRangeRoles rangeRoles = new IPRangeRoles(InetAddress.getByName(beginAddress),
            InetAddress.getByName(endAddress), ipRangeRoles);

    if (log.isTraceEnabled()) {
        log.trace("produceIPRangeInstance(): Returning IPRangeRoles " + "instance: " + rangeRoles);
    }
    return rangeRoles;
}

From source file:org.fedoracommons.funapi.pmh.AbstractPmhResolver.java

/**
 * {@inheritDoc}//from  w  ww  . j av a  2  s .co  m
 */
public UnapiObject getObject(String id, String format) throws UnapiException {
    try {
        String record = getRecord(id, format);
        XPath xpath = getXPath();
        Node pmh = (Node) xpath.evaluate("//oai:OAI-PMH", new InputSource(new StringReader(record)),
                XPathConstants.NODE);

        Node metadata = (Node) xpath.evaluate("//oai:metadata/*", pmh, XPathConstants.NODE);

        if (metadata == null) {
            String error = xpath.evaluate("//oai:error/@code", pmh);
            if (error.equalsIgnoreCase("idDoesNotExist")) {
                throw new IdentifierException(error);
            } else if (error.equalsIgnoreCase("cannotDisseminateFormat")) {
                throw new FormatException(error);
            } else {
                throw new UnapiException(error);
            }
        }

        TransformerFactory xformFactory = TransformerFactory.newInstance();
        Transformer transformer = xformFactory.newTransformer();

        Source source = new DOMSource(metadata);
        StringWriter sw = new StringWriter();
        transformer.transform(source, new StreamResult(sw));
        InputStream in = new ByteArrayInputStream(sw.toString().getBytes("UTF-8"));
        return new UnapiObject(in, "application/xml");
    } catch (XPathExpressionException e) {
        throw new UnapiException(e.getMessage(), e);
    } catch (TransformerException e) {
        throw new UnapiException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnapiException(e.getMessage(), e);
    }
}

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   ww w  . j a  va  2s . 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.persistent.cloudninja.service.impl.RunningInstancesJSONDataServiceImpl.java

/**
 * Parse the response from deployment monitoring and get role name, instance name and instance status.
 * @param response The XML response of deployment monitoring task.
 * @return List of InstanceHealthRoleInstanceEntity
 * @throws ParserConfigurationException//  w ww.  java 2s  . c  o m
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
private List<InstanceHealthRoleInstanceEntity> parseResponse(StringBuffer response)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilder documentBuilder = null;
    Document document = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();
    document = documentBuilder.parse(new InputSource(new StringReader(response.toString())));

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    NodeList roleNameList = (NodeList) xPath.evaluate("/Deployment/RoleInstanceList/RoleInstance/RoleName",
            document, XPathConstants.NODESET);
    NodeList instanceNameList = (NodeList) xPath.evaluate(
            "/Deployment/RoleInstanceList/RoleInstance/InstanceName", document, XPathConstants.NODESET);
    NodeList instanceStatusList = (NodeList) xPath.evaluate(
            "/Deployment/RoleInstanceList/RoleInstance/InstanceStatus", document, XPathConstants.NODESET);

    List<InstanceHealthRoleInstanceEntity> list = new ArrayList<InstanceHealthRoleInstanceEntity>();
    for (int index = 0; index < roleNameList.getLength(); index++) {
        Element roleElement = (Element) roleNameList.item(index);
        Element instanceElement = (Element) instanceNameList.item(index);
        Element statusElement = (Element) instanceStatusList.item(index);

        InstanceHealthRoleInstanceEntity roleInstanceEntity = new InstanceHealthRoleInstanceEntity();
        roleInstanceEntity.setRoleName(roleElement.getTextContent());
        roleInstanceEntity.setInstanceName(instanceElement.getTextContent());
        roleInstanceEntity.setInstanceStatus(statusElement.getTextContent());
        list.add(roleInstanceEntity);
    }
    return list;
}

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

/**
 * Get the String nodes through the reader
 * @return list of string nodes//from  w ww.  jav  a  2 s .  c  o m
* @throws XPathExpressionException 
 */
private NodeList getStringNodes(InputSource source) throws XPathExpressionException {
    XPath xpath = createXPathForInspectCode();
    NodeList nodes = new EmptyNodeList();
    nodes = (NodeList) xpath.evaluate("//s:String", source, XPathConstants.NODESET);
    return nodes;
}