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:se.vgregion.usdservice.USDServiceImpl.java

protected static List<Issue> parseIssues(String xml, String fallbackType, String associated)
        throws RuntimeException {
    List<Issue> issueList = new ArrayList<Issue>();
    try {//  ww  w. j a v  a  2  s  .  c om
        // Parse the XML to get a DOM to query
        Document doc = parseXml(xml);

        // Extract USDObject's
        String xPath = "/UDSObjectList/UDSObject";
        NodeList udsObjects = evaluate(xPath, doc, XPathConstants.NODESET);

        // Iterate over USDObject's to create Issue's
        for (int i = 1; i < udsObjects.getLength() + 1; i++) {
            // Get ref_num
            String refNum = null;
            if (TYPE_CHANGE_ORDER.equals(fallbackType)) {
                refNum = extractAttribute(i, "chg_ref_num", XPathConstants.STRING, doc);
            } else {
                refNum = extractAttribute(i, "ref_num", XPathConstants.STRING, doc);
            }

            // A Issue has to have refNum to be valid
            if (StringUtils.isEmpty(refNum)) {
                continue;
            }

            Issue issue = resolveIssue(refNum, i, fallbackType, associated, doc);

            // Add Issue object to list
            issueList.add(issue);
        }

        return issueList;
    } catch (Exception e) {
        log.error("Error when trying to parse issue list from XML", e);
        throw new RuntimeException("Error when trying to parse issue list from XML", e);
    }
}

From source file:com.espertech.esper.regression.event.TestNoSchemaXMLEvent.java

public void testEventXML() throws Exception {
    Configuration configuration = SupportConfigFactory.getConfiguration();
    ConfigurationEventTypeXMLDOM desc = new ConfigurationEventTypeXMLDOM();
    desc.addXPathProperty("event.type", "/event/@type", XPathConstants.STRING);
    desc.addXPathProperty("event.uid", "/event/@uid", XPathConstants.STRING);
    desc.setRootElementName("event");
    configuration.addEventType("MyEvent", desc);

    epService = EPServiceProviderManager.getDefaultProvider(configuration);
    epService.initialize();/*from   w w  w.  j a  va2  s  . c om*/
    updateListener = new SupportUpdateListener();

    String stmt = "select event.type as type, event.uid as uid from MyEvent";
    EPStatement joinView = epService.getEPAdministrator().createEPL(stmt);
    joinView.addListener(updateListener);

    sendXMLEvent(
            "<event type=\"a-f-G\" uid=\"terminal.55\" time=\"2007-04-19T13:05:20.22Z\" version=\"2.0\"></event>");
    EventBean theEvent = updateListener.assertOneGetNewAndReset();
    assertEquals("a-f-G", theEvent.get("type"));
    assertEquals("terminal.55", theEvent.get("uid"));
}

From source file:se.vgregion.usdservice.USDServiceImpl.java

private static Issue resolveIssue(String refNum, int i, String fallbackType, String associated, Document doc)
        throws XPathExpressionException {
    Issue issue = new Issue();
    issue.setRefNum(refNum);/*  w w  w  .  j  a  v a 2s . co m*/

    // Get summary
    String summary = extractAttribute(i, "summary", XPathConstants.STRING, doc);
    issue.setSummary(summary);

    // Get description
    String description = extractAttribute(i, "description", XPathConstants.STRING, doc);
    issue.setDescription(description);

    // Get status
    String statusSym = extractAttribute(i, "status.sym", XPathConstants.STRING, doc);
    issue.setStatus(statusSym);

    // Get web_url
    String webUrl = extractAttribute(i, "web_url", XPathConstants.STRING, doc);
    webUrl = webUrl.replaceFirst("vgms0005", "vgrusd.vgregion.se");
    issue.setUrl(webUrl);

    // Get type
    String type = extractAttribute(i, "type", XPathConstants.STRING, doc);
    if (StringUtils.isEmpty(type)) {
        type = fallbackType;
    }
    issue.setType(type);

    issue.setAssociated(associated);

    return issue;
}

From source file:eu.forgetit.middleware.component.Extractor.java

private String parseUserID(String inputFile) {

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {/*from w  w w. ja  v  a 2 s  .  c o  m*/
        builder = builderFactory.newDocumentBuilder();

        Document document = builder.parse(new File(inputFile));

        XPathFactory xpathFactory = XPathFactory.newInstance();

        XPath xpath = xpathFactory.newXPath();

        XPathExpression expr = xpath.compile("/Image_analysis_methods/@userID");

        String userID = (String) expr.evaluate(document, XPathConstants.STRING);

        System.out.println("userID: " + userID);

        return userID;

    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
        e.printStackTrace();
    }

    return null;

}

From source file:net.firejack.platform.installation.processor.OFRInstallProcessor.java

private Module getModule(File ofr) throws IOException, XPathExpressionException {
    XPath xpath = factory.newXPath();
    InputStream file = ArchiveUtils.getFile(ofr, PackageFileType.PACKAGE_XML.getOfrFileName());
    Object evaluate = xpath.evaluate("/package", new InputSource(file), XPathConstants.NODE);
    String path = (String) xpath.evaluate("@path", evaluate, XPathConstants.STRING);
    String name = (String) xpath.evaluate("@name", evaluate, XPathConstants.STRING);
    String version = (String) xpath.evaluate("@version", evaluate, XPathConstants.STRING);
    String dependencies = (String) xpath.evaluate("@dependencies", evaluate, XPathConstants.STRING);
    IOUtils.closeQuietly(file);//from w  w w.  j  a va 2 s . co  m

    String lookup = path + "." + name;
    Integer ver = VersionUtils.convertToNumber(version);

    return new Module(ofr, lookup, ver, dependencies);
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private boolean login(String username, String password) throws ExecutionException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("type", "keygen");
    params.put("user", username);
    params.put("password", password);

    String keygenBody;//w  ww  .  j  a v a  2 s . c  o m
    try {
        keygenBody = request(PaloAltoMethod.GET, params);
    } catch (ExecutionException e) {
        return false;
    }
    Document keygen_doc = getDocument(keygenBody);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']/result/key/text()");
        _key = (String) expr.evaluate(keygen_doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }
    if (_key != null) {
        return true;
    }
    return false;
}

From source file:de.mpg.escidoc.services.syndication.Utils.java

public static String xpathString(String expr, Document doc) throws Exception {
    return (String) xpath.evaluate(expr, doc, XPathConstants.STRING);
}

From source file:com.espertech.esper.client.ConfigurationParser.java

private static void handleXMLDOM(String name, Configuration configuration, Element xmldomElement) {
    String rootElementName = getRequiredAttribute(xmldomElement, "root-element-name");
    String rootElementNamespace = getOptionalAttribute(xmldomElement, "root-element-namespace");
    String schemaResource = getOptionalAttribute(xmldomElement, "schema-resource");
    String schemaText = getOptionalAttribute(xmldomElement, "schema-text");
    String defaultNamespace = getOptionalAttribute(xmldomElement, "default-namespace");
    String resolvePropertiesAbsoluteStr = getOptionalAttribute(xmldomElement,
            "xpath-resolve-properties-absolute");
    String propertyExprXPathStr = getOptionalAttribute(xmldomElement, "xpath-property-expr");
    String eventSenderChecksRootStr = getOptionalAttribute(xmldomElement, "event-sender-validates-root");
    String xpathFunctionResolverClass = getOptionalAttribute(xmldomElement, "xpath-function-resolver");
    String xpathVariableResolverClass = getOptionalAttribute(xmldomElement, "xpath-variable-resolver");
    String autoFragmentStr = getOptionalAttribute(xmldomElement, "auto-fragment");
    String startTimestampProperty = getOptionalAttribute(xmldomElement, "start-timestamp-property-name");
    String endTimestampProperty = getOptionalAttribute(xmldomElement, "end-timestamp-property-name");

    ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName(rootElementName);
    xmlDOMEventTypeDesc.setSchemaResource(schemaResource);
    xmlDOMEventTypeDesc.setSchemaText(schemaText);
    xmlDOMEventTypeDesc.setRootElementNamespace(rootElementNamespace);
    xmlDOMEventTypeDesc.setDefaultNamespace(defaultNamespace);
    xmlDOMEventTypeDesc.setXPathFunctionResolver(xpathFunctionResolverClass);
    xmlDOMEventTypeDesc.setXPathVariableResolver(xpathVariableResolverClass);
    xmlDOMEventTypeDesc.setStartTimestampPropertyName(startTimestampProperty);
    xmlDOMEventTypeDesc.setEndTimestampPropertyName(endTimestampProperty);
    if (resolvePropertiesAbsoluteStr != null) {
        xmlDOMEventTypeDesc//  w w w.ja  v  a2  s . c  o m
                .setXPathResolvePropertiesAbsolute(Boolean.parseBoolean(resolvePropertiesAbsoluteStr));
    }
    if (propertyExprXPathStr != null) {
        xmlDOMEventTypeDesc.setXPathPropertyExpr(Boolean.parseBoolean(propertyExprXPathStr));
    }
    if (eventSenderChecksRootStr != null) {
        xmlDOMEventTypeDesc.setEventSenderValidatesRoot(Boolean.parseBoolean(eventSenderChecksRootStr));
    }
    if (autoFragmentStr != null) {
        xmlDOMEventTypeDesc.setAutoFragment(Boolean.parseBoolean(autoFragmentStr));
    }
    configuration.addEventType(name, xmlDOMEventTypeDesc);

    DOMElementIterator propertyNodeIterator = new DOMElementIterator(xmldomElement.getChildNodes());
    while (propertyNodeIterator.hasNext()) {
        Element propertyElement = propertyNodeIterator.next();
        if (propertyElement.getNodeName().equals("namespace-prefix")) {
            String prefix = getRequiredAttribute(propertyElement, "prefix");
            String namespace = getRequiredAttribute(propertyElement, "namespace");
            xmlDOMEventTypeDesc.addNamespacePrefix(prefix, namespace);
        }
        if (propertyElement.getNodeName().equals("xpath-property")) {
            String propertyName = getRequiredAttribute(propertyElement, "property-name");
            String xPath = getRequiredAttribute(propertyElement, "xpath");
            String propertyType = getRequiredAttribute(propertyElement, "type");
            QName xpathConstantType;
            if (propertyType.toUpperCase().equals("NUMBER")) {
                xpathConstantType = XPathConstants.NUMBER;
            } else if (propertyType.toUpperCase().equals("STRING")) {
                xpathConstantType = XPathConstants.STRING;
            } else if (propertyType.toUpperCase().equals("BOOLEAN")) {
                xpathConstantType = XPathConstants.BOOLEAN;
            } else if (propertyType.toUpperCase().equals("NODE")) {
                xpathConstantType = XPathConstants.NODE;
            } else if (propertyType.toUpperCase().equals("NODESET")) {
                xpathConstantType = XPathConstants.NODESET;
            } else {
                throw new IllegalArgumentException("Invalid xpath property type for property '" + propertyName
                        + "' and type '" + propertyType + '\'');
            }

            String castToClass = null;
            if (propertyElement.getAttributes().getNamedItem("cast") != null) {
                castToClass = propertyElement.getAttributes().getNamedItem("cast").getTextContent();
            }

            String optionaleventTypeName = null;
            if (propertyElement.getAttributes().getNamedItem("event-type-name") != null) {
                optionaleventTypeName = propertyElement.getAttributes().getNamedItem("event-type-name")
                        .getTextContent();
            }

            if (optionaleventTypeName != null) {
                xmlDOMEventTypeDesc.addXPathPropertyFragment(propertyName, xPath, xpathConstantType,
                        optionaleventTypeName);
            } else {
                xmlDOMEventTypeDesc.addXPathProperty(propertyName, xPath, xpathConstantType, castToClass);
            }
        }
    }
}

From source file:com.espertech.esper.regression.event.TestNoSchemaXMLEvent.java

public void testElementNode() throws Exception {
    // test for Esper-129
    Configuration configuration = SupportConfigFactory.getConfiguration();
    ConfigurationEventTypeXMLDOM desc = new ConfigurationEventTypeXMLDOM();
    desc.addXPathProperty("event.type", "//event/@type", XPathConstants.STRING);
    desc.addXPathProperty("event.uid", "//event/@uid", XPathConstants.STRING);
    desc.setRootElementName("batch-event");
    configuration.addEventType("MyEvent", desc);

    epService = EPServiceProviderManager.getDefaultProvider(configuration);
    epService.initialize();//  w w w  . ja v  a 2  s  .  co m
    updateListener = new SupportUpdateListener();

    String stmt = "select event.type as type, event.uid as uid from MyEvent";
    EPStatement joinView = epService.getEPAdministrator().createEPL(stmt);
    joinView.addListener(updateListener);

    String xml = "<batch-event>"
            + "<event type=\"a-f-G\" uid=\"terminal.55\" time=\"2007-04-19T13:05:20.22Z\" version=\"2.0\"/>"
            + "</batch-event>";
    StringReader reader = new StringReader(xml);
    InputSource source = new InputSource(reader);
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    Document doc = builderFactory.newDocumentBuilder().parse(source);
    Element topElement = doc.getDocumentElement();

    epService.getEPRuntime().sendEvent(topElement);
    EventBean theEvent = updateListener.assertOneGetNewAndReset();
    assertEquals("a-f-G", theEvent.get("type"));
    assertEquals("terminal.55", theEvent.get("uid"));
}

From source file:com.twentyn.patentExtractor.PatentDocument.java

public static PatentDocument patentDocumentFromXMLStream(InputStream iStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerException, XPathExpressionException {

    // Create XPath objects for validating that this document is actually a patent.
    XPath xpath = Util.getXPathFactory().newXPath();
    XPathExpression versionXPath = xpath.compile(PATH_DTD_VERSION);
    XPathExpression versionXPathApp = xpath.compile(PATH_DTD_VERSION_APP);

    DocumentBuilderFactory docFactory = Util.mkDocBuilderFactory();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(iStream);

    Util.DocumentType docType = Util.identifyDocType(doc);
    if (docType != Util.DocumentType.PATENT && docType != Util.DocumentType.APPLICATION) {
        LOGGER.warn("Found unexpected document type: " + docType);
        return null;
    }/*from  ww w  . j  av  a2 s. co m*/

    boolean isApplication = docType == Util.DocumentType.APPLICATION;
    // Yes this is in fact the way suggested by the XPath API.
    String version;
    if (!isApplication) {
        version = (String) versionXPath.evaluate(doc, XPathConstants.STRING);
    } else {
        version = (String) versionXPathApp.evaluate(doc, XPathConstants.STRING);
    }

    if (version == null || !VERSION_MAP.containsKey(version)) {
        LOGGER.warn(String.format("Unrecognized patent DTD version: %s", version));
        return null;
    }

    HashMap<String, String> paths = VERSION_MAP.get(version);

    /* Create XPath objects for extracting the fields of interest based on the version information.
     * TODO: extract these into some sharable, thread-safe place, maybe via dependency injection.
     */
    XPathExpression idXPath = xpath.compile(paths.get(PATH_KEY_FILE_ID));
    XPathExpression dateXPath = xpath.compile(paths.get(PATH_KEY_DATE));
    XPathExpression titleXPath = xpath.compile(paths.get(PATH_KEY_TITLE));
    XPathExpression classificationXPath = xpath.compile(paths.get(PATH_KEY_MAIN_CLASSIFICATION));
    XPathExpression furtherClassificationsXPath = xpath.compile(paths.get(PATH_KEY_FURTHER_CLASSIFICATIONS));
    XPathExpression searchedClassificationsXPath = xpath.compile(paths.get(PATH_KEY_SEARCHED_CLASSIFICATIONS));

    String fileId = (String) idXPath.evaluate(doc, XPathConstants.STRING);
    String date = (String) dateXPath.evaluate(doc, XPathConstants.STRING);
    NodeList titleNodes = (NodeList) titleXPath.evaluate(doc, XPathConstants.NODESET);
    String title = StringUtils.join(" ", extractTextFromHTML(docBuilder, titleNodes));
    String classification = (String) classificationXPath.evaluate(doc, XPathConstants.STRING);
    NodeList furtherClassificationNodes = (NodeList) furtherClassificationsXPath.evaluate(doc,
            XPathConstants.NODESET);
    ArrayList<String> furtherClassifications = null;
    if (furtherClassificationNodes != null) {
        furtherClassifications = new ArrayList<>(furtherClassificationNodes.getLength());
        for (int i = 0; i < furtherClassificationNodes.getLength(); i++) {
            Node n = furtherClassificationNodes.item(i);
            String txt = n.getTextContent();
            if (txt != null) {
                furtherClassifications.add(i, txt);
            }
        }
    } else {
        furtherClassifications = new ArrayList<>(0);
    }

    NodeList otherClassificationNodes = (NodeList) searchedClassificationsXPath.evaluate(doc,
            XPathConstants.NODESET);
    ArrayList<String> otherClassifications = null;
    if (otherClassificationNodes != null) {
        otherClassifications = new ArrayList<>(otherClassificationNodes.getLength());
        for (int i = 0; i < otherClassificationNodes.getLength(); i++) {
            Node n = otherClassificationNodes.item(i);
            String txt = n.getTextContent();
            if (txt != null) {
                otherClassifications.add(i, txt);
            }
        }
    } else {
        otherClassifications = new ArrayList<>(0);
    }

    // Extract text content for salient document paths.
    List<String> allTextList = getRelevantDocumentText(docBuilder, PATHS_TEXT, xpath, doc);
    List<String> claimsTextList = getRelevantDocumentText(docBuilder, new String[] { PATH_CLAIMS }, xpath, doc);

    return new PatentDocument(fileId, date, title, classification, furtherClassifications, otherClassifications,
            allTextList, claimsTextList, isApplication);
}