Example usage for javax.xml.xpath XPathConstants STRING

List of usage examples for javax.xml.xpath XPathConstants STRING

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants STRING.

Prototype

QName STRING

To view the source code for javax.xml.xpath XPathConstants STRING.

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:ch.entwine.weblounge.bridge.oaipmh.harvester.OaiPmhResponse.java

public static String xpathString(XPath xpaht, Node context, String expr) {
    try {//w w  w  . j  a v  a2  s.  co  m
        return ((String) xpaht.evaluate(expr, context, XPathConstants.STRING)).trim();
    } catch (XPathExpressionException e) {
        throw new RuntimeException("malformed xpath expression " + expr, e);
    }
}

From source file:Main.java

/** Evaluates an XPath returning null if not found. <br>
 *  <br>//  w  w w. ja v a  2 s .com
 *  This is intended for use with pre-defined XPaths stored as constants,
 *  where runtime exceptions should not be possible.
 *  @param expression The XPath expression to evaluate.
 *  @param item       The {@link Node} or other item to evaluate the XPath on.
 *  @param type       The type to return, this must be one of the following:
 *                    {@link String}, {@link CharSequence}, {@link Boolean},
 *                    {@link Node}, {@link NodeList}, {@link Double}, or
 *                    {@link Number}.
 *  @throws AssertionError If the nested call to <tt>XPath.newInstance(path)</tt>
 *                         throws an {@link XPathExpressionException}.
 */
public static <T> T evalXPath(String expression, Object item, Class<T> type) {
    Object val;

    if (type == String.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == CharSequence.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == Boolean.class)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Boolean.TYPE)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Node.class)
        val = evalXPath(expression, item, XPathConstants.NODE);
    else if (type == NodeList.class)
        val = evalXPath(expression, item, XPathConstants.NODESET);
    else if (type == Double.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Double.TYPE)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Number.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else
        throw new IllegalArgumentException("Invalid type given " + type);

    return type.cast(val);
}

From source file:com.rackspace.api.clients.veracode.responses.UploadResponse.java

public String getBuildId(int buildVersion) {
    Formatter formatter = new Formatter();
    String buildId = null;/*from w w w .  ja  v a 2s .co  m*/

    try {
        buildId = (String) xpath.evaluate(formatter.format(XPATH_EXPRESSION, buildVersion).toString(), doc,
                XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }

    return buildId;
}

From source file:org.opencastproject.remotetest.util.CaptureUtils.java

/**
 * Returns <code>true</code> if the capture agent with id <code>captureAgentId</code> is currently capturing. If the
 * agent is not online, an {@link IllegalStateException} is thrown.
 * /*from w  ww .  j a v  a  2s .  c  o  m*/
 * @param captureAgentId
 *          the capture agent
 * @return <code>true</code> if the agent is capturing
 * @throws IllegalStateException
 *           if the agent is not online
 * @throws Exception
 *           if the response can't be parsed
 */
public static boolean isCapturing(String captureAgentId) throws IllegalStateException, Exception {
    HttpGet request = new HttpGet(BASE_URL + "/capture-admin/agents/" + captureAgentId);
    HttpResponse response = Main.getClient().execute(request);
    if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode())
        throw new IllegalStateException("Capture agent '" + captureAgentId + "' is unexpectedly offline");
    String responseBody = EntityUtils.toString(response.getEntity());
    return "capturing".equalsIgnoreCase(
            (String) Utils.xpath(responseBody, "/*[local-name() = 'state']", XPathConstants.STRING));
}

From source file:org.jboss.windup.decorator.archive.PomDescriptionDecorator.java

protected String extractStringValue(XPathExpression expression, Document doc) throws XPathExpressionException {
    return (String) expression.evaluate(doc, XPathConstants.STRING);
}

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

/**
 * @see com.cordys.coe.ac.httpconnector.samples.JIRAResponseHandler#buildXMLResponse(int,org.apache.commons.httpclient.HttpMethod,
 *      org.w3c.dom.Document, com.eibus.xml.nom.Document)
 *///w  w w .  j a  v  a  2s .c o m
@Override
protected void buildXMLResponse(int resNode, HttpMethod httpMethod, org.w3c.dom.Document document, Document doc)
        throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate("//table[@class='grid']/tr[@class='vcard']", document,
            XPathConstants.NODESET);

    int nrOfUsers = nodeList.getLength();

    if (nrOfUsers > 0) {
        for (int count = 0; count < nrOfUsers; count++) {
            Node userNode = nodeList.item(count);

            int tuple = doc.createElementWithParentNS("tuple", null, resNode);

            int old = doc.createElementWithParentNS("old", null, tuple);
            int user = doc.createElementWithParentNS("user", null, old);

            // Get the name
            String username = (String) xpath.evaluate(".//span[@class='username']/text()", userNode,
                    XPathConstants.STRING);

            doc.createElementWithParentNS("username", username, user);

            // Get the email address
            String emailAddress = (String) xpath.evaluate(".//span[@class='email']/text()", userNode,
                    XPathConstants.STRING);

            doc.createElementWithParentNS("email", emailAddress, user);

            // Get the full name
            String fn = (String) xpath.evaluate(".//span[@class='fn']/text()", userNode, XPathConstants.STRING);

            doc.createElementWithParentNS("fullname", fn, user);

            // Get the groups for this user
            NodeList nl = (NodeList) xpath.evaluate(".//td/a[../br]/text()", userNode, XPathConstants.NODESET);
            int groups = doc.createElementWithParentNS("groups", null, user);

            for (int groupsCount = 0; groupsCount < nl.getLength(); groupsCount++) {
                String group = nl.item(groupsCount).getNodeValue();
                doc.createElementWithParentNS("group", group, groups);
            }
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("No users found");
    }
}

From source file:de.slub.fedora.jms.MessageMapper.java

private static String extractDsId(String text)
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(IOUtils.toInputStream(text));

    return (String) xPath.evaluate("/entry/category[@scheme='fedora-types:dsID']/@term", document,
            XPathConstants.STRING);
}

From source file:Main.java

/**
 * Evaluates the XPath expression in the specified context and returns the found element as a String.
 *
 * @param node       the XML document to evaluate
 * @param expression the compiled XPath expression
 * @return the element if it was found, or null
 *//*  w  w w  .j  a  v a  2s  .  c  om*/
public static String getStringValue(Node node, XPathExpression expression) {
    try {
        return (String) expression.evaluate(node, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        return null;
    }
}

From source file:de.egore911.versioning.deployer.performer.PerformCheckout.java

public void perform(Node serverDeploymentsDeploymentNode) throws XPathExpressionException {
    NodeList checkoutOperations = (NodeList) checkoutXpath.evaluate(serverDeploymentsDeploymentNode,
            XPathConstants.NODESET);
    for (int j = 0; j < checkoutOperations.getLength(); j++) {
        Node checkoutOperation = checkoutOperations.item(j);
        String target = (String) targetXpath.evaluate(checkoutOperation, XPathConstants.STRING);
        String git = (String) gitXpath.evaluate(checkoutOperation, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(git)) {
            performGit(target, git);//from w w w  . j ava  2 s  .  co m
        } else {
            String svn = (String) svnXpath.evaluate(checkoutOperation, XPathConstants.STRING);
            if (StringUtils.isNotEmpty(svn)) {
                performSvn(target, svn);
            } else {
                LOG.warn("Neither SVN nor git used for server configuration");
            }
        }
    }
}

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parse(InputStream is) throws Exception {
    DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance();
    xmlfact.setNamespaceAware(true);/*from ww  w  .  j  a  v  a  2 s  .  c  o  m*/
    Document document = xmlfact.newDocumentBuilder().parse(is);

    NamespaceContext ctx = new NamespaceContext() {

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public String getNamespaceURI(String prefix) {

            String uri = null;

            /*
             *    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:smart="http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#"
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:contact="http://www.w3.org/2000/10/swap/pim/contact#"
            xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
            xmlns:time="http://www.w3.org/2006/time#"
            xml:base="http://www.ait.gr/ait_web_site/faculty/apne/report.xml"
                    
            *
            */

            if (prefix.equals("rdf")) {
                uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
            }
            if (prefix.equals("smart")) {
                uri = "http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#";
            }
            if (prefix.equals("dc")) {
                uri = "http://purl.org/dc/elements/1.1/#";
            }
            if (prefix.equals("geo")) {
                uri = "http://www.w3.org/2003/01/geo/wgs84_pos#";
            }
            if (prefix.equals("time")) {
                uri = "http://www.w3.org/2006/time#";
            }
            return uri;

        }
    };

    // find the node data

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

    String id = (String) xpath.compile("//smart:Node/@rdf:ID").evaluate(document, XPathConstants.STRING);
    String lat = (String) xpath.compile("//smart:Node/geo:lat/text()").evaluate(document,
            XPathConstants.STRING);
    String lon = (String) xpath.compile("//smart:Node/geo:long/text()").evaluate(document,
            XPathConstants.STRING);
    String fullName = (String) xpath.compile("//smart:Node/dc:fullName/text()").evaluate(document,
            XPathConstants.STRING);
    Node node = new Node(new Double(lat), new Double(lon), id, fullName);

    String time = (String) xpath.compile("//smart:Report/time:inXSDDateTime/text()").evaluate(document,
            XPathConstants.STRING);
    String reportId = (String) xpath.compile("//smart:Report/@rdf:ID").evaluate(document,
            XPathConstants.STRING);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    String density = (String) xpath.compile("//smart:Crowd/smart:density/text()").evaluate(document,
            XPathConstants.STRING);
    String cameraGain = (String) xpath.compile("//smart:Crowd/smart:cameraGain/text()").evaluate(document,
            XPathConstants.STRING);

    NodeList list = (NodeList) xpath.compile("//smart:Crowd/smart:colour").evaluate(document,
            XPathConstants.NODESET);
    double[] colors = new double[list.getLength()];
    for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node colorNode = list.item(i);
        String v = colorNode.getFirstChild().getTextContent();
        colors[i] = new Double(v);
    }

    CrowdReport crowdReport = new CrowdReport(reportId, new Double(density), new Double(cameraGain), colors);

    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(node, id, c, crowdReport);

    return snapShot;
}