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: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;/*w w w  . ja  v  a  2  s  .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();
    }

    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;//from w w w.j  a  va2s .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();
        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.egore911.versioning.deployer.Main.java

private static void perform(String arg, CommandLine line) throws IOException {
    URL url;/*from   ww w . j  av a 2  s. com*/
    try {
        url = new URL(arg);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        System.exit(1);
        return;
    }

    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();
        if (response != HttpURLConnection.HTTP_OK) {
            LOG.error("Could not download {}", url);
            connection.disconnect();
            System.exit(1);
            return;
        }
    } catch (ConnectException e) {
        LOG.error("Error during download from URI {}: {}", url, e.getMessage());
        System.exit(1);
        return;
    }

    XmlHolder xmlHolder = XmlHolder.getInstance();
    DocumentBuilder documentBuilder = xmlHolder.documentBuilder;
    XPath xPath = xmlHolder.xPath;

    try {

        XPathExpression serverNameXpath = xPath.compile("/server/name/text()");
        XPathExpression serverTargetdirXpath = xPath.compile("/server/targetdir/text()");
        XPathExpression serverDeploymentsDeploymentXpath = xPath.compile("/server/deployments/deployment");

        Document doc = documentBuilder.parse(connection.getInputStream());
        connection.disconnect();

        String serverName = (String) serverNameXpath.evaluate(doc, XPathConstants.STRING);
        LOG.info("Deploying {}", serverName);

        boolean shouldPerformCopy = !line.hasOption('r');
        PerformCopy performCopy = new PerformCopy(xPath);
        boolean shouldPerformExtraction = !line.hasOption('r');
        PerformExtraction performExtraction = new PerformExtraction(xPath);
        boolean shouldPerformCheckout = !line.hasOption('r');
        PerformCheckout performCheckout = new PerformCheckout(xPath);
        boolean shouldPerformReplacement = true;
        PerformReplacement performReplacement = new PerformReplacement(xPath);

        String targetdir = (String) serverTargetdirXpath.evaluate(doc, XPathConstants.STRING);
        FileUtils.forceMkdir(new File(targetdir));

        NodeList serverDeploymentsDeploymentNodes = (NodeList) serverDeploymentsDeploymentXpath.evaluate(doc,
                XPathConstants.NODESET);
        int max = serverDeploymentsDeploymentNodes.getLength();
        for (int i = 0; i < serverDeploymentsDeploymentNodes.getLength(); i++) {
            Node serverDeploymentsDeploymentNode = serverDeploymentsDeploymentNodes.item(i);

            // Copy
            if (shouldPerformCopy) {
                performCopy.perform(serverDeploymentsDeploymentNode);
            }

            // Extraction
            if (shouldPerformExtraction) {
                performExtraction.perform(serverDeploymentsDeploymentNode);
            }

            // Checkout
            if (shouldPerformCheckout) {
                performCheckout.perform(serverDeploymentsDeploymentNode);
            }

            // Replacement
            if (shouldPerformReplacement) {
                performReplacement.perform(serverDeploymentsDeploymentNode);
            }

            logPercent(i + 1, max);
        }

        // validate that "${versioning:" is not present
        Collection<File> files = FileUtils.listFiles(new File(targetdir), TrueFileFilter.TRUE,
                TrueFileFilter.INSTANCE);
        for (File file : files) {
            String content;
            try {
                content = FileUtils.readFileToString(file);
            } catch (IOException e) {
                continue;
            }
            if (content.contains("${versioning:")) {
                LOG.error("{} contains placeholders even after applying the replacements",
                        file.getAbsolutePath());
            }
        }

        LOG.info("Done deploying {}", serverName);

    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Error performing deployment: {}", e.getMessage(), e);
    }
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.aspect.AspectLexiconFactory.java

protected AspectLexiconFactory addXmlAspect(AspectLexicon lexicon, Node aspectNode)
        throws XPathExpressionException {

    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");
    Validate.notNull(aspectNode, CannedMessages.NULL_ARGUMENT, "node");

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

    // if the node is called "lexicon" then we're at the root, so we won't need to add an aspect and its expressions.
    AspectLexicon aspect = lexicon;/*ww w .ja  v  a 2 s .  c  om*/
    if (!"aspect-lexicon".equalsIgnoreCase(aspectNode.getLocalName())) {
        String title = Validate.notEmpty(
                (String) xpath.compile("./@title").evaluate(aspectNode, XPathConstants.STRING),
                CannedMessages.EMPTY_ARGUMENT, "./aspect/@title");
        ;

        // fetch or create aspect.
        aspect = lexicon.findAspect(title);
        if (aspect == null) {
            aspect = lexicon.addAspect(title);
        }

        // get all expressions or keywords, whatever they're called.
        NodeList expressionNodes = (NodeList) xpath.compile("./expressions/expression").evaluate(aspectNode,
                XPathConstants.NODESET);
        if (expressionNodes == null || expressionNodes.getLength() == 0) {
            expressionNodes = (NodeList) xpath.compile("./keywords/keyword").evaluate(aspectNode,
                    XPathConstants.NODESET);
        }

        // add each of them if they don't exist.
        if (expressionNodes != null) {
            for (int index = 0; index < expressionNodes.getLength(); index++) {
                String expression = expressionNodes.item(index).getTextContent().trim();
                if (!aspect.hasExpression(expression)) {
                    aspect.addExpression(expression);
                }
            }
        }
    }

    // get all sub-aspects and add them recursively.
    NodeList subAspectNodes = (NodeList) xpath.compile("./aspects/aspect").evaluate(aspectNode,
            XPathConstants.NODESET);
    if (subAspectNodes != null) {
        for (int index = 0; index < subAspectNodes.getLength(); index++) {
            this.addXmlAspect(aspect, subAspectNodes.item(index));
        }
    }

    return this;
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.DbpediaMapper.java

private boolean load(String query) throws EntityException, NoResultException {

    boolean success = true;

    label = "";//from ww  w  .  j av  a  2  s.  c om
    description = "";
    String queryUrl = produceQueryUrl(query);

    try {
        Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(queryUrl);

        if (response != null) {

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

            NodeList nodes = (NodeList) xPath.evaluate("/ArrayOfResult/Result", response,
                    XPathConstants.NODESET);

            if (nodes.getLength() != 0) {

                // WE TAKE THE FIRST ENTITY FROM DBPEDIA
                label = ((String) xPath.evaluate("Label", nodes.item(0), XPathConstants.STRING));

                description = ((String) xPath.evaluate("Description", nodes.item(0), XPathConstants.STRING))
                        .toLowerCase();

                NodeList classesList = (NodeList) xPath.evaluate("Classes/Class", nodes.item(0),
                        XPathConstants.NODESET);

                classes = new ArrayList<String>(classesList.getLength());
                for (int i = 0; i < classesList.getLength(); i++) {
                    Node n = classesList.item(i);
                    String clazz = (String) xPath.evaluate("Label", n, XPathConstants.STRING);
                    classes.add(clazz);
                }
            }
            if (label.isEmpty()) {
                success = false;
                label = query;
            }

        }
    } catch (Exception e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");

        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        success = false;

    } catch (Error e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");
        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                throw new EntityException("Error during the mapping of the query " + query + " on dbPedia ("
                        + e.toString() + ")");
            }
        }
        success = false;

    }

    if (!success) {
        throw new NoResultException("mapping to dbpedia failed for query " + query);
    }
    return success;
}

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

/**
 * Checks whether the given workflow is in the requested state.
 * /*from   w w w  .  j  ava 2s.co m*/
 * @param workflowId
 *          identifier of the workflow
 * @param state
 *          the state that the workflow is expected to be in
 * @return <code>true</code> if the workflow is in the expected state
 * @throws IllegalStateException
 *           if the specified workflow can't be found
 */
public static boolean isWorkflowInState(String workflowId, String state)
        throws IllegalStateException, Exception {
    HttpGet getWorkflowMethod = new HttpGet(BASE_URL + "/workflow/instance/" + workflowId + ".xml");
    TrustedHttpClient client = Main.getClient();
    HttpResponse response = client.execute(getWorkflowMethod);
    if (response.getStatusLine().getStatusCode() != 200)
        throw new IllegalStateException(EntityUtils.toString(response.getEntity()));
    String workflow = EntityUtils.toString(response.getEntity());
    String currentState = (String) Utils.xpath(workflow, "/*[local-name() = 'workflow']/@state",
            XPathConstants.STRING);
    Main.returnClient(client);
    return state.equalsIgnoreCase(currentState);
}

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

public void testSimpleXMLXPathProperties() throws Exception {
    Configuration configuration = SupportConfigFactory.getConfiguration();

    ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName("myevent");
    xmlDOMEventTypeDesc.addXPathProperty("xpathElement1", "/myevent/element1", XPathConstants.STRING);
    xmlDOMEventTypeDesc.addXPathProperty("xpathCountE21", "count(/myevent/element2/element21)",
            XPathConstants.NUMBER);
    xmlDOMEventTypeDesc.addXPathProperty("xpathAttrString", "/myevent/element3/@attrString",
            XPathConstants.STRING);
    xmlDOMEventTypeDesc.addXPathProperty("xpathAttrNum", "/myevent/element3/@attrNum", XPathConstants.NUMBER);
    xmlDOMEventTypeDesc.addXPathProperty("xpathAttrBool", "/myevent/element3/@attrBool",
            XPathConstants.BOOLEAN);
    xmlDOMEventTypeDesc.addXPathProperty("stringCastLong", "/myevent/element3/@attrNum", XPathConstants.STRING,
            "long");
    xmlDOMEventTypeDesc.addXPathProperty("stringCastDouble", "/myevent/element3/@attrNum",
            XPathConstants.STRING, "double");
    xmlDOMEventTypeDesc.addXPathProperty("numCastInt", "/myevent/element3/@attrNum", XPathConstants.NUMBER,
            "int");
    xmlDOMEventTypeDesc.setXPathFunctionResolver(SupportXPathFunctionResolver.class.getName());
    xmlDOMEventTypeDesc.setXPathVariableResolver(SupportXPathVariableResolver.class.getName());
    configuration.addEventType("TestXMLNoSchemaType", xmlDOMEventTypeDesc);

    xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName("my.event2");
    configuration.addEventType("TestXMLWithDots", xmlDOMEventTypeDesc);

    epService = EPServiceProviderManager.getProvider("TestNoSchemaXML", configuration);
    epService.initialize();/*  w w w  . java 2s .c o m*/
    updateListener = new SupportUpdateListener();

    // assert type metadata
    EventTypeSPI type = (EventTypeSPI) ((EPServiceProviderSPI) epService).getEventAdapterService()
            .getExistsTypeByName("TestXMLNoSchemaType");
    assertEquals(EventTypeMetadata.ApplicationType.XML, type.getMetadata().getOptionalApplicationType());
    assertEquals(null, type.getMetadata().getOptionalSecondaryNames());
    assertEquals("TestXMLNoSchemaType", type.getMetadata().getPrimaryName());
    assertEquals("TestXMLNoSchemaType", type.getMetadata().getPublicName());
    assertEquals("TestXMLNoSchemaType", type.getName());
    assertEquals(EventTypeMetadata.TypeClass.APPLICATION, type.getMetadata().getTypeClass());
    assertEquals(true, type.getMetadata().isApplicationConfigured());
    assertEquals(true, type.getMetadata().isApplicationPreConfigured());
    assertEquals(true, type.getMetadata().isApplicationPreConfiguredStatic());

    EPAssertionUtil.assertEqualsAnyOrder(new Object[] {
            new EventPropertyDescriptor("xpathElement1", String.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("xpathCountE21", Double.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("xpathAttrString", String.class, null, false, false, false, false,
                    false),
            new EventPropertyDescriptor("xpathAttrNum", Double.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("xpathAttrBool", Boolean.class, null, false, false, false, false,
                    false),
            new EventPropertyDescriptor("stringCastLong", Long.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("stringCastDouble", Double.class, null, false, false, false, false,
                    false),
            new EventPropertyDescriptor("numCastInt", Integer.class, null, false, false, false, false,
                    false), },
            type.getPropertyDescriptors());

    String stmt = "select xpathElement1, xpathCountE21, xpathAttrString, xpathAttrNum, xpathAttrBool,"
            + "stringCastLong," + "stringCastDouble," + "numCastInt "
            + "from TestXMLNoSchemaType.win:length(100)";

    EPStatement joinView = epService.getEPAdministrator().createEPL(stmt);
    joinView.addListener(updateListener);

    // Generate document with the specified in element1 to confirm we have independent events
    sendEvent("EventA");
    assertDataSimpleXPath("EventA");

    sendEvent("EventB");
    assertDataSimpleXPath("EventB");
}

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

public void testSchemaXMLWSchemaWithAll() throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    ConfigurationEventTypeXMLDOM eventTypeMeta = new ConfigurationEventTypeXMLDOM();
    eventTypeMeta.setRootElementName("event-page-visit");
    String schemaUri = TestSchemaXMLEvent.class.getClassLoader().getResource(CLASSLOADER_SCHEMA_WITH_ALL_URI)
            .toString();//from w  ww  . j av a2  s.co  m
    eventTypeMeta.setSchemaResource(schemaUri);
    eventTypeMeta.addNamespacePrefix("ss", "samples:schemas:simpleSchemaWithAll");
    eventTypeMeta.addXPathProperty("url", "/ss:event-page-visit/ss:url", XPathConstants.STRING);
    config.addEventType("PageVisitEvent", eventTypeMeta);

    epService = EPServiceProviderManager.getProvider("TestSchemaXML", config);
    epService.initialize();
    updateListener = new SupportUpdateListener();

    // url='page4'
    String text = "select a.url as sesja from pattern [ every a=PageVisitEvent(url='page1') ]";
    EPStatement stmt = epService.getEPAdministrator().createEPL(text);
    stmt.addListener(updateListener);

    SupportXML.sendEvent(epService.getEPRuntime(), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<event-page-visit xmlns=\"samples:schemas:simpleSchemaWithAll\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"samples:schemas:simpleSchemaWithAll simpleSchemaWithAll.xsd\">\n"
            + "<url>page1</url>" + "</event-page-visit>");
    EventBean theEvent = updateListener.getLastNewData()[0];
    assertEquals("page1", theEvent.get("sesja"));
    updateListener.reset();

    SupportXML.sendEvent(epService.getEPRuntime(), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<event-page-visit xmlns=\"samples:schemas:simpleSchemaWithAll\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"samples:schemas:simpleSchemaWithAll simpleSchemaWithAll.xsd\">\n"
            + "<url>page2</url>" + "</event-page-visit>");
    assertFalse(updateListener.isInvoked());

    EventType type = epService.getEPAdministrator().createEPL("select * from PageVisitEvent").getEventType();
    EPAssertionUtil.assertEqualsAnyOrder(new Object[] {
            new EventPropertyDescriptor("sessionId", Node.class, null, false, false, false, false, true),
            new EventPropertyDescriptor("customerId", Node.class, null, false, false, false, false, true),
            new EventPropertyDescriptor("url", String.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("method", Node.class, null, false, false, false, false, true), },
            type.getPropertyDescriptors());
}

From source file:com.esri.geoportal.harvester.migration.MigrationDataBuilder.java

private URI createBrokerUri(MigrationData data) throws URISyntaxException {
    MigrationHarvestSite site = data.siteuuid != null ? sites.get(data.siteuuid) : null;
    if (site != null) {
        String type = StringUtils.trimToEmpty(site.type).toUpperCase();
        switch (type) {
        case "WAF":
            return new URI("WAF", escapeUri(site.host), null);
        case "CKAN":
            return new URI("CKAN", escapeUri(site.host), null);
        case "ARCGIS": {
            int rsIdx = site.host.toLowerCase().indexOf("/rest/services");
            String host = rsIdx >= 0 ? site.host.substring(0, rsIdx) : site.host;
            return new URI("AGS", escapeUri(host), null);
        }/*from  ww  w. jav  a 2s  . c  o m*/
        case "CSW":
            try {
                Document doc = strToDom(site.protocol);
                XPath xPath = XPathFactory.newInstance().newXPath();
                String protocolId = (String) xPath.evaluate("/protocol[@type='CSW']/profile", doc,
                        XPathConstants.STRING);
                URL host = new URL(site.host);
                host = new URL(host.getProtocol(), host.getHost(), host.getPort(), host.getPath());
                return new URI("CSW", host.toExternalForm(), protocolId);
            } catch (Exception ex) {
            }
        }
    }
    return brokerUri;
}

From source file:gov.nih.nci.cabig.report2caaers.exchange.AdeersResponseProcessor.java

private String evaluateXPath(String xpathStr, String xmlStr) throws XPathExpressionException {
    XPath xpath = factory.newXPath();
    InputSource inputSource = new InputSource(new StringReader(xmlStr));
    return (String) xpath.evaluate(xpathStr, inputSource, XPathConstants.STRING);
}