Example usage for javax.xml.xpath XPathFactory newInstance

List of usage examples for javax.xml.xpath XPathFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newInstance.

Prototype

public static XPathFactory newInstance() 

Source Link

Document

Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.

This method is functionally equivalent to:

 newInstance(DEFAULT_OBJECT_MODEL_URI) 

Since the implementation for the W3C DOM is always available, this method will never fail.

Usage

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;/*  www  .  j av a  2 s.c o  m*/
    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:mupomat.utility.LongLatService.java

public String getXpathValue(Document doc, String strXpath) throws XPathExpressionException {
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile(strXpath);
    String resultData = null;/*from  w w  w . java2s  .c o m*/
    Object result4 = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result4;
    for (int i = 0; i < nodes.getLength(); i++) {
        resultData = nodes.item(i).getNodeValue();
    }
    return resultData;

}

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  w w .j  ava 2s .com*/
    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:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

public static void configurePackage(String env, File configFile) throws Exception {
    Transformer transformer = tltf.get();

    // get the list of files in proxies folder
    XMLFileListUtil listFileUtil = new XMLFileListUtil();

    ConfigTokens conf = FileReader.getBundleConfigs(configFile);

    Map<String, List<File>> filesToProcess = new HashMap<String, List<File>>();
    filesToProcess.put("proxy", listFileUtil.getProxyFiles(configFile));
    filesToProcess.put("policy", listFileUtil.getPolicyFiles(configFile));
    filesToProcess.put("target", listFileUtil.getTargetFiles(configFile));

    doTokenReplacement(env, conf, filesToProcess);

    // special case ...
    File proxyFile = listFileUtil.getAPIProxyFiles(configFile).get(0);
    Document xmlDoc = FileReader.getXMLDocument(proxyFile); // there would be only one file, at least one file

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expression = xpath.compile("/APIProxy/Description");

    NodeList nodes = (NodeList) expression.evaluate(xmlDoc, XPathConstants.NODESET);
    if (nodes.item(0).hasChildNodes()) {
        // sets the description to whatever is in the <proxyname>.xml file
        nodes.item(0).setTextContent(expression.evaluate(xmlDoc));
    } else {//  w w  w  .ja va2 s. c o  m
        // if Description is empty, then it reverts back to appending the username, git hash, etc
        nodes.item(0).setTextContent(getComment(proxyFile));
    }

    DOMSource source = new DOMSource(xmlDoc);
    StreamResult result = new StreamResult(proxyFile);
    transformer.transform(source, result);
}

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  a v a 2  s  .  co m*/
    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:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

public EntityResolutionMessageHandler() {
    entityResolutionService = new EntityResolutionService();
    xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new EntityResolutionNamespaceContext());

}

From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

/**
 * Create a new StageClient to handle communicating to a Nexus Pro server Staging suite.
 * //  w  w  w  .  jav  a 2 s .  c o  m
 * @param nexusURL the base URL for the Nexus server.
 * @param username user name to use with staging privileges.
 * @param password password for the user.
 */
public StageClient(URL nexusURL, String username, String password) {
    this.nexusURL = nexusURL;
    this.username = username;
    this.password = password;
    // XPathFactory is not thread safe.
    XPathFactory factory;
    synchronized (XPathFactory.class) {
        factory = XPathFactory.newInstance();
    }
    synchronized (factory) {
        xpath = factory.newXPath();
    }
}

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;/*ww w. j a  v  a2 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();
        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:org.codice.ddf.admin.sources.opensearch.OpenSearchSourceUtils.java

public UrlAvailability getUrlAvailability(String url, String un, String pw) {
    UrlAvailability result = new UrlAvailability(url);
    boolean queryResponse;
    int status;/*  ww  w  . ja va2 s  .  co m*/
    String contentType;
    HttpGet request = new HttpGet(url + SIMPLE_QUERY_PARAMS);
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;

    if (url.startsWith("https") && un != null && pw != null) {
        byte[] auth = Base64.encodeBase64((un + ":" + pw).getBytes());
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    try {
        client = getCloseableHttpClient(false);
        response = client.execute(request);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document responseXml = builder.parse(response.getEntity().getContent());
        queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                XPathConstants.BOOLEAN);
        status = response.getStatusLine().getStatusCode();
        contentType = response.getEntity().getContentType().getValue();
        if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
            return result.trustedCertAuthority(true).certError(false).available(true);
        } else {
            return result.trustedCertAuthority(true).certError(false).available(false);
        }
    } catch (SSLPeerUnverifiedException e) {
        // This is the hostname != cert name case - if this occurs, the URL's SSL cert configuration
        // is incorrect, or a serious network security issue has occurred.
        return result.trustedCertAuthority(false).certError(true).available(false);
    } catch (Exception e) {
        try {
            closeClientAndResponse(client, response);
            client = getCloseableHttpClient(true);
            response = client.execute(request);
            status = response.getStatusLine().getStatusCode();
            contentType = response.getEntity().getContentType().getValue();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document responseXml = builder.parse(response.getEntity().getContent());
            queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                    XPathConstants.BOOLEAN);
            if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
                return result.trustedCertAuthority(false).certError(false).available(true);
            }
        } catch (Exception e1) {
            return result.trustedCertAuthority(false).certError(false).available(false);
        }
    } finally {
        closeClientAndResponse(client, response);
    }
    return result;
}

From source file:org.fcrepo.kernel.impl.identifiers.HttpPidMinter.java

/**
 * Create a new HttpPidMinter./*from  w ww.  jav  a  2s .  co m*/
 * @param url The URL for the minter service.  This is the only required argument -- all
 *    other parameters can be blank.
 * @param method The HTTP method (POST, PUT or GET) used to generate a new PID (POST will
 *    be used if the method is blank.
 * @param username If not blank, use this username to connect to the minter service.
 * @param password If not blank, use this password used to connect to the minter service.
 * @param regex If not blank, use this regular expression used to remove unwanted text from the
 *    minter service response.  For example, if the response text is "/foo/bar:baz" and the
 *    desired identifier is "baz", then the regex would be ".*:".
 * @param xpath If not blank, use this XPath expression used to extract the desired identifier
 *    from an XML minter response.
**/
public HttpPidMinter(final String url, final String method, final String username, final String password,
        final String regex, final String xpath) {

    checkArgument(!isBlank(url), "Minter URL must be specified!");

    this.url = url;
    this.method = method;
    this.username = username;
    this.password = password;
    this.regex = regex;
    if (xpath != null) {
        try {
            this.xpath = XPathFactory.newInstance().newXPath().compile(xpath);
        } catch (XPathException ex) {
            log.warn("Error parsing xpath ({}): {}", xpath, ex);
        }
    }
    this.client = buildClient();
}