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: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}//ww  w . ja  va 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:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Return the child of the node selected by the xPath.
 * /*from  w w  w  . j  a  v  a  2s  .  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:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Return the list of children of the node selected by the xPath.
 * /*  w  w w.  j  a  va  2 s  .co  m*/
 * @param node The node.
 * @param xpathExpression The xPath.
 * @return The list of children of the node selected by the xPath.
 * @throws TransformerException If anything fails.
 */
public static NodeList selectNodeList(final Node node, final String xpathExpression)
        throws TransformerException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        return (NodeList) xPath.evaluate(xpathExpression, node, XPathConstants.NODESET);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

/**
 * Parses the response received by making call to REST API.
 * It parses and gets the total no. roles and their instances.
 * //ww  w  .  j a  va2s  .c  o  m
 * @param roleInfo
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 * @throws ParseException
 */
private void parseRoleInfo(StringBuffer roleInfo) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, ParseException {
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    docBuilder = docBuilderFactory.newDocumentBuilder();
    doc = docBuilder.parse(new InputSource(new StringReader(roleInfo.toString())));

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    NodeList roleList = (NodeList) xPath.evaluate("/Deployment/RoleList/Role/RoleName", doc,
            XPathConstants.NODESET);
    //get all the roles
    String roleName = null;
    List<String> listRoleNames = new ArrayList<String>();
    for (int i = 0; i < roleList.getLength(); i++) {
        Element element = (Element) roleList.item(i);
        roleName = element.getTextContent();
        RoleEntity roleEntity = roleDao.findByRoleName(roleName);
        if (roleEntity == null) {
            roleEntity = new RoleEntity();
            roleEntity.setName(roleName);
            roleDao.add(roleEntity);
        }
        listRoleNames.add(roleName);
    }

    xPathFactory = XPathFactory.newInstance();
    xPath = xPathFactory.newXPath();
    RoleInstancesEntity roleInstancesEntity = null;
    RoleInstancesId roleInstancesId = null;
    for (String name : listRoleNames) {
        roleList = (NodeList) xPath.evaluate(
                "/Deployment/RoleInstanceList/RoleInstance[RoleName='" + name + "']", doc,
                XPathConstants.NODESET);
        //get no. of instances for WorkerRole
        int noOfInstances = roleList.getLength();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        String date = dateFormat.format(calendar.getTime());
        roleInstancesId = new RoleInstancesId(dateFormat.parse(date), name);
        roleInstancesEntity = new RoleInstancesEntity(roleInstancesId, noOfInstances, "UPDATE");
        roleInstancesDao.add(roleInstancesEntity);
    }

}

From source file:au.csiro.casda.sodalint.ValidateCapabilities.java

/**
 * One or more of the sync and async SODA endpoints should be listed in the capabilities document.
 * /*from   w ww .j a va  2s.c o  m*/
 * @param reporter
 *            validation message destination
 * @param document
 *            The capabilities XML document
 * @param sodaService
 *            The service being tested.
 * @throws XPathExpressionException
 *             If ther eis acoding error in the xpath expression.
 */
private void checkForSyncAsync(Reporter reporter, Document document, SodaService sodaService)
        throws XPathExpressionException {
    final String sodaStdIdPrefix = "ivo://ivoa.net/std/SODA";
    final String sodaStdIdSync = "ivo://ivoa.net/std/SODA#sync-1.0";
    final String sodaStdIdAsync = "ivo://ivoa.net/std/SODA#async-1.0";
    final String accessDataStdIdSync = "ivo://ivoa.net/std/AccessData#sync";
    final String accessDataStdIdAsync = "ivo://ivoa.net/std/AccessData#async";

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

    NodeList capNodeList = (NodeList) xpath.evaluate("capability", document.getDocumentElement(),
            XPathConstants.NODESET);
    boolean hasSoda = false;
    Node syncCapNode = null;
    Node asyncCapNode = null;

    for (int i = 0; i < capNodeList.getLength(); i++) {
        Node capNode = capNodeList.item(i);
        Node stdIdAttr = capNode.getAttributes().getNamedItem("standardID");

        if (stdIdAttr != null && StringUtils.isNotBlank(stdIdAttr.getNodeValue())) {
            String stdId = stdIdAttr.getNodeValue();
            if (stdId.startsWith(sodaStdIdPrefix)) {
                hasSoda = true;
            }
            if (stdId.equals(sodaStdIdSync)) {
                syncCapNode = capNode;
            } else if (stdId.equals(sodaStdIdAsync)) {
                asyncCapNode = capNode;
            } else if (stdId.equals(accessDataStdIdSync)) {
                reporter.report(SodaCode.E_CPEP, "SODA endpoint uses outdated AccessData id: " + stdId);
                syncCapNode = capNode;
            } else if (stdId.equals(accessDataStdIdAsync)) {
                reporter.report(SodaCode.E_CPEP, "SODA endpoint uses outdated AccessData id: " + stdId);
                asyncCapNode = capNode;
            }
        }
    }

    if (syncCapNode == null && asyncCapNode == null) {
        if (hasSoda) {
            reporter.report(SodaCode.E_CPEP,
                    "SODA endpoints found but they do not have v1.0 sync or async qualifiers");
        } else {
            reporter.report(SodaCode.E_CPEP, "SODA requires at least one of the sync and async endpoints");
        }
    }

    if (syncCapNode != null) {
        NodeList interfaces = (NodeList) xpath.evaluate("interface", syncCapNode, XPathConstants.NODESET);
        if (interfaces == null || interfaces.getLength() == 0) {
            reporter.report(SodaCode.E_CPIF, "SODA sync endpoint does not contain an interface");
        } else {
            sodaService.setSyncServiceNode(syncCapNode);
        }
    }
    if (asyncCapNode != null) {
        NodeList interfaces = (NodeList) xpath.evaluate("interface", asyncCapNode, XPathConstants.NODESET);
        if (interfaces == null || interfaces.getLength() == 0) {
            reporter.report(SodaCode.E_CPIF, "SODA async endpoint does not contain an interface");
        }
        sodaService.setAsyncServiceNode(asyncCapNode);
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 *
 * @param samlMsg the saml response as a string
 * @return a string representing the Assertion
 *//*from   w  w  w.j  a va  2s .c o  m*/
public static String extractAssertionAsString(String samlMsg) {
    String assertion = NO_ASSERTION;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(samlMsg)));

        XPath xPath = XPathFactory.newInstance().newXPath();
        Node node = (Node) xPath.evaluate(ASSERTION_XPATH, doc, XPathConstants.NODE);
        if (node != null) {
            assertion = domnodeToString(node);
        }
    } catch (ParserConfigurationException pce) {
        LOG.error("cannot parse response {}", pce);
    } catch (SAXException saxe) {
        LOG.error("cannot parse response {}", saxe);

    } catch (IOException ioe) {
        LOG.error("cannot parse response {}", ioe);

    } catch (XPathExpressionException xpathe) {
        LOG.error("cannot find the assertion {}", xpathe);

    } catch (TransformerException trfe) {
        LOG.error("cannot output the assertion {}", trfe);

    }

    return assertion;
}

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 a va 2 s .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;
    }
}

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

/**
 * {@inheritDoc}/*  ww w. ja va2 s.  co  m*/
 */
public UnapiFormats getFormats() throws UnapiException {
    String mdFormats = listMetadataFormats();
    UnapiFormats formats = new UnapiFormats(null);
    XPath xpath = getXPath();
    NodeList nodelist = null;
    try {
        nodelist = (NodeList) xpath.evaluate("//oai:metadataFormat",
                new InputSource(new StringReader(mdFormats)), XPathConstants.NODESET);
        for (int i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);
            String format = xpath.evaluate("oai:metadataPrefix", node);
            String docs = xpath.evaluate("oai:schema", node);
            UnapiFormat uFormat = new UnapiFormat(format, "application/xml", docs);
            formats.addFormat(uFormat);
        }
    } catch (XPathExpressionException e) {
        throw new UnapiException(e.getMessage(), e);
    }
    return formats;
}

From source file:au.csiro.casda.sodalint.ValidateServiceDescriptor.java

private void checkSodaAccessUrl(Reporter reporter, Node sodaSvcNode) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();

    NodeList accessUrlList = (NodeList) xpath.evaluate("*[local-name()='PARAM']", sodaSvcNode,
            XPathConstants.NODESET);

    if (accessUrlList == null || accessUrlList.getLength() == 0) {
        reporter.report(SodaCode.E_SDMP, "Service descriptor is missing accessURL PARAM.");
        return;/*from ww w . j a  v  a2 s.c o m*/
    }
    Node node = accessUrlList.item(0);
    if (node.getAttributes().getNamedItem("value") == null) {
        reporter.report(SodaCode.E_SDMP, "Service descriptor accessURL PARAM does not have a value.");
        return;
    }
}

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

private String getSingleXPathValue(Document currentResDom, String xpathAsString) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    return (String) xpath.evaluate(xpathAsString, currentResDom, XPathConstants.STRING);
}