Example usage for javax.xml.xpath XPathConstants NODE

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

Introduction

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

Prototype

QName NODE

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

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:org.ambraproject.search.service.DummySOLRMessageSender.java

private Node XPathSingleNodeQuery(Document dom, String statement) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile(statement);

    return (Node) expr.evaluate(dom, XPathConstants.NODE);
}

From source file:com.esri.gpt.catalog.search.SearchFilterSpatial.java

/**
 * Instantiates a new search filter spatial.
 *///from   w  w w .  j a v  a 2  s.c  o m
public SearchFilterSpatial() {
    super();
    reset();

    // Load a fioel with predefined extents (bookmarks)
    Document domFe;
    XPath xpathFe;
    try {
        String sPredefinedExtents = PREDEFINED_EXTENTS_FILE;
        LogUtil.getLogger().log(Level.FINE, "Loading Predefined extents file: {0}", sPredefinedExtents);
        domFe = DomUtil.makeDomFromResourcePath(sPredefinedExtents, false);
        xpathFe = XPathFactory.newInstance().newXPath();
    } catch (Exception e) {
        LogUtil.getLogger().log(Level.FINE, "No predefined extents file");
        domFe = null;
        xpathFe = null;
    }
    // predefined extent file root
    Node rootFe = null;
    try {
        if (domFe != null)
            rootFe = (Node) xpathFe.evaluate("/extents", domFe, XPathConstants.NODE);
    } catch (Exception e) {
        rootFe = null;
        LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file");
    }
    /**
     * Reads Bookmarks and load an array
     */
    NodeList extents;
    ArrayList extentsList = new ArrayList();
    if (rootFe != null) {
        try {
            extents = (NodeList) xpathFe.evaluate("extent", rootFe, XPathConstants.NODESET);
            for (Node extent : new NodeListAdapter(extents)) {
                String extPlace = (String) xpathFe.evaluate("@place", extent, XPathConstants.STRING);
                String extValue = (String) xpathFe.evaluate("@ext", extent, XPathConstants.STRING);
                LogUtil.getLogger().log(Level.FINE, "Element added:" + extPlace + "," + extValue);
                SelectItem extElement = new SelectItem(extValue, extPlace);
                extentsList.add(extElement);
            }
        } catch (Exception e) {
            extentsList = null;
            LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file");
        }
    } else
        extentsList = null;

    this._predefinedExtents = extentsList;
}

From source file:com.esri.gpt.server.openls.provider.services.reversegeocode.ReverseGeocodeProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * @param context the operation context//from ww w . j a v  a  2  s  .c om
 * @param root the root node
 * @param xpath an XPath to enable queries (properly configured with name spaces)
* @throws Exception 
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize
    LOGGER.finer("Handling ReverseGeocodeRequest request XML...");

    // find ReverseGeocodeRequest node
    String locator = "xls:ReverseGeocodeRequest";
    Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndReq != null) {
        GeocodedAddress addr = null;
        parseRequest(context, ndReq, xpath);
        try {
            addr = executeRequest(context);

        } catch (Throwable e) {
            e.printStackTrace();
        }
        context.getRequestOptions().getReverseGeocodeOptions().setgAddr(addr);
    }

    // generate the response
    generateResponse(context);
}

From source file:org.jboss.seam.forge.shell.util.PluginUtil.java

public static File downloadPlugin(final PluginRef ref, final PipeOut out, final String targetPath)
        throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    String[] artifactParts = ref.getArtifact().split(":");

    if (artifactParts.length != 3) {
        throw new RuntimeException("malformed artifact identifier "
                + "(format should be: <maven.group>:<maven.artifact>:<maven.version>) encountered: "
                + ref.getArtifact());//from w w w.ja v a 2  s  .com
    }

    String packageLocation = artifactParts[0].replaceAll("\\.", "/");
    String baseUrl;
    if (ref.getHomeRepo().endsWith("/")) {
        baseUrl = ref.getHomeRepo() + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    } else {
        baseUrl = ref.getHomeRepo() + "/" + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    }

    HttpGet httpGetManifest = new HttpGet(baseUrl + "/maven-metadata.xml");
    out.print("Retrieving artifact manifest ... ");

    HttpResponse response = client.execute(httpGetManifest);
    switch (response.getStatusLine().getStatusCode()) {
    case 200:
        out.println("done.");

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getEntity().getContent());

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression checkSnapshotExpr = xpath.compile("//versioning/snapshot");
        XPathExpression findJar = xpath.compile("//snapshotVersion[extension='jar']/value");

        NodeList list = (NodeList) checkSnapshotExpr.evaluate(document, XPathConstants.NODESET);

        out.print("Reading manifest ... ");

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

            Node n = (Node) findJar.evaluate(document, XPathConstants.NODE);

            if (n == null) {
                out.println("failed: could not determine where to find jar file.");
                return null;
            }

            String version = n.getFirstChild().getTextContent();

            // plugin definition points to a snapshot.
            out.println("good! (maven snapshot found): " + version);

            String fileName = artifactParts[1] + "-" + version + ".jar";

            HttpGet jarGet = new HttpGet(baseUrl + "/" + fileName);

            out.print("Downloading: " + baseUrl + "/" + fileName + " ... ");
            response = client.execute(jarGet);

            try {
                File file = saveFile(targetPath + "/" + fileName, response.getEntity().getContent());
                out.println("done.");
                return file;
            } catch (IOException e) {
                out.println("failed to download: " + e.getMessage());
                return null;
            }

            // do download of snapshot.
        } else {
            out.println("error! (maven snapshot not found)");
            return null;
        }

    case 404:
        String requestUrl = baseUrl + "/" + artifactParts[2] + ".pom";
        httpGetManifest = new HttpGet(requestUrl);
        response = client.execute(httpGetManifest);

        if (response.getStatusLine().getStatusCode() != 200) {
            printError(response.getStatusLine().getStatusCode(), requestUrl, out);
            return null;
        } else {

            // download regular POM here.

        }
        break;
    default:
        out.println("failed! (server returned status code: " + response.getStatusLine().getStatusCode());
        return null;
    }

    return null;

}

From source file:com.esri.gpt.server.openls.provider.services.poi.DirectoryProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * @param context the operation context/*from   ww  w .  j av  a2 s . com*/
 * @param root the root node
 * @param xpath an XPath to enable queries (properly configured with name spaces)
 * @throws Exception if a processing exception occurs
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize
    LOGGER.finer("Handling xls:Directory request XML...");
    String locator = "xls:DirectoryRequest";
    Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndReq != null) {
        parseRequest(context, ndReq, xpath);
    }
    try {
        executeRequest(context);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    generateResponse(context);
}

From source file:com.github.koraktor.steamcondenser.community.XMLData.java

/**
 * Returns the XML data for the element specified by the given XPath
 *
 * @param path The XPath to get the XML data for
 * @return The element with the given XPath
 *///from  www  .  j av a 2 s  .co  m
public XMLData getXPath(String path) {
    if (xpath == null) {
        xpath = XPathFactory.newInstance().newXPath();
    }

    try {
        return new XMLData((Element) xpath.evaluate(path, this.root, XPathConstants.NODE));
    } catch (XPathExpressionException e) {
        return null;
    }
}

From source file:com.jaeksoft.searchlib.util.XPathParser.java

public final Node getNode(Node parentNode, String query) throws XPathExpressionException {
    return (Node) xPath.evaluate(query, parentNode, XPathConstants.NODE);
}

From source file:com.cisco.dvbu.ps.common.adapters.config.AdapterConfig.java

private void parseAdapterCommon(Document doc) throws AdapterException {
    log.debug("Root element :" + doc.getDocumentElement().getNodeName());
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {/*from   ww  w  . j a  v  a2  s.  com*/
        Attr a = (Attr) xpath.evaluate(AdapterConstants.XPATH_CONFIG_VERSION, doc, XPathConstants.NODE);
        log.debug(a.getName() + ": " + a.getValue());
        Element e = (Element) xpath.evaluate(AdapterConstants.XPATH_NAME, doc, XPathConstants.NODE);
        name = e.getTextContent();
        log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_DESC, doc, XPathConstants.NODE);
        desc = e.getTextContent();
        log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CIS_VERSION, doc, XPathConstants.NODE);
        cisVersion = e.getTextContent();
        log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_RETRYATTMPTS, doc, XPathConstants.NODE);
        retryAttempts = (e != null && e.getTextContent() != null) ? Integer.parseInt(e.getTextContent()) : -1;
        log.debug("retryAttempts: " + retryAttempts);
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_MAXCLIENTS, doc, XPathConstants.NODE);
        maxClients = (e != null && e.getTextContent() != null) ? Integer.parseInt(e.getTextContent()) : -1;
        log.debug("maxclients: " + maxClients);
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_MINCLIENTS, doc, XPathConstants.NODE);
        minClients = (e != null && e.getTextContent() != null) ? Integer.parseInt(e.getTextContent()) : -1;
        log.debug("minclients: " + minClients);
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(302,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.CreationAndUpdateTests.java

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription, find and add the factory service url
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));
        Node factoryUrl = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:factory/oslc_cm:url", baseDoc,
                XPathConstants.NODE);
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { factoryUrl.getTextContent() });
        return data;
    }//w w  w  .  j av a2  s. co  m

    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

    //ArrayList to contain the urls from all of the SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        Collection<Object[]> subCollection = getReferencedUrls(sDescs.item(i).getNodeValue());
        Iterator<Object[]> iter = subCollection.iterator();
        while (iter.hasNext()) {
            data.add(iter.next());
        }
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //simple query services from the eventual service description documents from them as well.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        if (!spcs.item(i).getNodeValue().equals(base)) {
            Collection<Object[]> subCollection = getReferencedUrls(spcs.item(i).getNodeValue());
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:de.bayern.gdi.services.CatalogService.java

/**
 * Constructor./*from  ww  w.j  av  a2s . c  om*/
 *
 * @param url      URL
 * @param userName Username
 * @param password Password
 * @throws URISyntaxException if URL is wrong
 * @throws IOException if something in IO is wrong
 */
public CatalogService(URL url, String userName, String password) throws URISyntaxException, IOException {
    this.catalogURL = url;
    this.userName = userName;
    this.password = password;
    this.context = new NamespaceContextMap("csw", CSW_NAMESPACE, "gmd", GMD_NAMESPACE, "ows", OWS_NAMESPACE,
            "srv", SRV_NAMESPACE, "gco", GCO_NAMESPACE);
    Document xml = XML.getDocument(this.catalogURL, this.userName, this.password);
    if (xml != null) {
        String getProviderExpr = "//ows:ServiceIdentification/ows:Title";
        Node providerNameNode = (Node) XML.xpath(xml, getProviderExpr, XPathConstants.NODE, context);
        this.providerName = providerNameNode.getTextContent();
        String getRecordsURLExpr = "//ows:OperationsMetadata" + "/ows:Operation[@name='GetRecords']"
                + "/ows:DCP" + "/ows:HTTP" + "/ows:Post";

        NodeList rL = (NodeList) XML.xpath(xml, getRecordsURLExpr, XPathConstants.NODESET, context);

        for (int i = 0; i < rL.getLength(); i++) {
            Node gruNode = rL.item(i);
            String getRecordsValueStr = (String) XML.xpath(gruNode, "ows:Constraint/ows:Value/text()",
                    XPathConstants.STRING, this.context);

            if (getRecordsValueStr == null || getRecordsValueStr.isEmpty()
                    || getRecordsValueStr.equals("XML")) {

                String getRecordsURLStr = (String) XML.xpath(gruNode, "@*[name()='xlink:href']",
                        XPathConstants.STRING, this.context);

                this.getRecordsURL = null;
                this.getRecordsURL = new URL(getRecordsURLStr);
                break;
            }
        }
    }
}