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:de.dplatz.padersprinter.control.TripService.java

static boolean isNodePresent(Node node, String expr, XPath xpath) throws XPathExpressionException {
    return xpath.evaluate(expr, node, XPathConstants.NODE) != null;
}

From source file:de.dplatz.padersprinter.control.TripService.java

static Node getNode(Node node, String expr, XPath xpath) throws XPathExpressionException {
    return (Node) xpath.evaluate(expr, node, XPathConstants.NODE);
}

From source file:Pathway2Rdf.java

public static void addPathway2Rdf(String wpIdentifier, String wpRevision, String gpml)
        throws DOMException, XPathExpressionException, ServiceException, ConverterException,
        ParserConfigurationException, SAXException, IOException, ParseException, NullPointerException {

    Model model = ModelFactory.createDefaultModel();
    // Declare the Prefixes

    // Model wikipathways level into RDF
    Resource wikipathwaysResource = model.createResource(WpNamespaces.nsWikipathways);

    Property xCoordinate = model.createProperty(WpNamespaces.nsWikipathways + "GPML/xCoordinate");
    Property yCoordinate = model.createProperty(WpNamespaces.nsWikipathways + "GPML/yCoordinate");
    Property color = model.createProperty(WpNamespaces.nsWikipathways + "GPML/color");
    Property width = model.createProperty(WpNamespaces.nsWikipathways + "GPML/width");
    Property height = model.createProperty(WpNamespaces.nsWikipathways + "GPML/height");

    Resource wikiPathwaysPaperResource = model.createResource("http://www.ncbi.nlm.nih.gov/pubmed/18651794");
    wikipathwaysResource.addProperty(DCTerms.bibliographicCitation, wikiPathwaysPaperResource);
    Resource wikiPathwaysSparqlEndpointResource = model
            .createResource("http://semantics.bigcat.unimaas.nl:8000/sparql");
    wikipathwaysResource.addProperty(Void.sparqlEndpoint, wikiPathwaysSparqlEndpointResource);
    wikipathwaysResource.addProperty(RDF.type, Void.Dataset);

    String DefinitionURI = WpNamespaces.nsWikipathways + "Definition/";
    Resource wikipathwaysGroupDefinitionResource = model.createResource(DefinitionURI + "Group/");

    // State that GeneProduct can either be a Protein or DNA
    RDFNode[] geneProductelems = new RDFNode[] { Biopax_level3.Dna, Biopax_level3.Protein };
    RDFList geneProductRDFNode = model.createList(geneProductelems);

    String pathwayURI = WpNamespaces.nsWikipathways + "Pathway/" + wpIdentifier + "/";
    //System.out.println();
    //System.out.print(wpIdentifier);
    Resource abstractPathwayResource = model.createResource(pathwayURI);
    //System.out.print(wpRevision);
    String pathwayResourceURI = pathwayURI + wpRevision + "/";
    Resource centralPathwayResource = model.createResource(pathwayResourceURI);
    abstractPathwayResource.addProperty(DCTerms.hasVersion, centralPathwayResource);
    Resource pathwayResource = model.createResource(pathwayResourceURI);

    // A Pathway in Wikipathways is identified by its WP identifier and
    // its revision number;
    Resource pathwayIdentifierResource = model.createResource(
            WpNamespaces.nsIdentifiers + "/WikiPathways/" + wpIdentifier + "/" + wpRevision + "/");
    pathwayIdentifierResource.addProperty(RDFS.label, wpIdentifier);
    pathwayResource.addProperty(DC.identifier, pathwayIdentifierResource);
    pathwayResource.addProperty(RDFS.label, wpIdentifier);

    // PARSE GPML
    if (!gpml.startsWith("{{deleted|") && isValidXML(gpml, wpIdentifier, wpRevision)) {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        StringReader reader = new StringReader(gpml);
        InputSource inputSource = new InputSource(reader);
        Document doc = docBuilder.parse(inputSource);
        reader.close();//w w  w  .j a v a2  s.  c om
        doc.getDocumentElement().normalize();
        try {
            // Get the Pathway Nodes
            XPath xPath = XPathFactory.newInstance().newXPath();

            Node pathwayLicense = ((Node) xPath.evaluate("/Pathway/@License", doc, XPathConstants.NODE));
            Node pathwayName = ((Node) xPath.evaluate("/Pathway/@Name", doc, XPathConstants.NODE));
            Node pathwayOrganism = ((Node) xPath.evaluate("/Pathway/@Organism", doc, XPathConstants.NODE));

            // Map the organism to DbPedia
            if (pathwayOrganism != null) {
                Resource dbPediaSpeciesResource = model.createResource(
                        "http://dbpedia.org/page/" + pathwayOrganism.getNodeValue().replace(" ", "_"));
                wikipathwaysResource.addProperty(DC.coverage, dbPediaSpeciesResource);
            }

            // Add pathway level details to the RDF model
            if (pathwayName != null)
                pathwayResource.addProperty(RDFS.label, pathwayName.getNodeValue());
            if (pathwayIdentifierResource != null)
                pathwayResource.addProperty(DC.identifier, pathwayIdentifierResource);
            if (pathwayLicense != null)
                pathwayResource.addProperty(DCTerms.license, pathwayLicense.getNodeValue());
            pathwayResource.addProperty(RDF.type, Biopax_level3.Pathway);
            pathwayResource.addProperty(DCTerms.isPartOf, wikipathwaysResource);

            // Get the Group References by calling the getGroupIds from
            // the
            // wikipathways webservices
            NodeList groupIdsNL = doc.getElementsByTagName("Group");
            Set<String> groupIdsSet = new TreeSet<String>();
            for (int t = 0; t < groupIdsNL.getLength(); t++) {
                groupIdsSet.add(groupIdsNL.item(t).getAttributes().getNamedItem("GroupId").getTextContent());
                // System.out.println(groupIdsNL.item(t).getAttributes()
                // .getNamedItem("GroupId").getTextContent());
            }

            for (String groupRef : groupIdsSet) {
                Resource groupResource = model.createResource(pathwayResourceURI + "Group/" + groupRef);
                groupResource.addProperty(RDF.type, wikipathwaysGroupDefinitionResource);
            }

            // Add pathwayElements to the RDF model
            NodeList dataNodeNL = doc.getElementsByTagName("DataNode");

            // for (PathwayElement pwElm : pathway.getDataObjects()) {
            for (int dnlint = 0; dnlint < dataNodeNL.getLength(); dnlint++) {
                // Only take elements with type DATANODE (genes,
                // proteins,
                // metabolites)
                String datanodeType = null;
                if (dataNodeNL.item(dnlint).getAttributes().getNamedItem("Type") != null) {
                    datanodeType = dataNodeNL.item(dnlint).getAttributes().getNamedItem("Type")
                            .getTextContent();
                }
                String datanodeTextLabel = dataNodeNL.item(dnlint).getAttributes().getNamedItem("TextLabel")
                        .getTextContent();
                String datanodeGraphId = dataNodeNL.item(dnlint).getAttributes().getNamedItem("GraphId")
                        .getTextContent();
                String datanodeGroupRef = null;
                if (dataNodeNL.item(dnlint).getAttributes().getNamedItem("GroupRef") != null) {
                    datanodeGroupRef = dataNodeNL.item(dnlint).getAttributes().getNamedItem("GroupRef")
                            .getTextContent();
                }
                NodeList datanodeChilds = dataNodeNL.item(dnlint).getChildNodes();
                // Get ChildNodes Xref, Graphics

                String datanodeXrefId = null;
                String datanodeXrefDatabase = null;
                String dataNodeGraphicsColor = null;
                Float dataNodeGraphicsCenterX = null;
                Float dataNodeGraphicsCenterY = null;
                Float dataNodeGraphicsWidth = null;
                Float dataNodeGraphicsHeight = null;
                for (int dnchildint = 0; dnchildint < datanodeChilds.getLength(); dnchildint++) {
                    // Xref
                    if (datanodeChilds.item(dnchildint).getNodeName().equals("Xref")) {
                        datanodeXrefId = datanodeChilds.item(dnchildint).getAttributes().getNamedItem("ID")
                                .getTextContent();
                        datanodeXrefDatabase = datanodeChilds.item(dnchildint).getAttributes()
                                .getNamedItem("Database").getTextContent();
                    }
                    //Graphics
                    if (datanodeChilds.item(dnchildint).getNodeName().equals("Graphics")) {
                        if (datanodeChilds.item(dnchildint).getAttributes().getNamedItem("Color") != null) {
                            dataNodeGraphicsColor = datanodeChilds.item(dnchildint).getAttributes()
                                    .getNamedItem("Color").getTextContent();
                        }
                        dataNodeGraphicsCenterX = Float.valueOf(datanodeChilds.item(dnchildint).getAttributes()
                                .getNamedItem("CenterX").getTextContent());
                        dataNodeGraphicsCenterY = Float.valueOf(datanodeChilds.item(dnchildint).getAttributes()
                                .getNamedItem("CenterY").getTextContent());
                        dataNodeGraphicsWidth = Float.valueOf(datanodeChilds.item(dnchildint).getAttributes()
                                .getNamedItem("Width").getTextContent());
                        dataNodeGraphicsHeight = Float.valueOf(datanodeChilds.item(dnchildint).getAttributes()
                                .getNamedItem("Height").getTextContent());
                    }
                }

                // if (pwElm.getObjectType() == ObjectType.DATANODE) {
                Resource pathwayEntity = model
                        .createResource(pathwayResourceURI + "Datanode/" + datanodeGraphId);
                pathwayEntity.addProperty(DCTerms.isPartOf, pathwayResource);
                pathwayEntity.addProperty(RDF.type, Spatial.Feature);
                pathwayEntity.addLiteral(xCoordinate, dataNodeGraphicsCenterX);
                pathwayEntity.addLiteral(yCoordinate, dataNodeGraphicsCenterX);
                if (dataNodeGraphicsColor != null) {
                    pathwayEntity.addLiteral(color, dataNodeGraphicsColor);
                }
                pathwayEntity.addLiteral(width, dataNodeGraphicsWidth);
                pathwayEntity.addLiteral(height, dataNodeGraphicsHeight);

                pathwayEntity.addProperty(RDFS.label, datanodeTextLabel);
                // System.out.println(pwElm.getDataNodeType().toString());
                if (datanodeType != null) {
                    if (datanodeType.equals("Metabolite")) {
                        pathwayEntity.addProperty(RDF.type, Biopax_level3.SmallMolecule);
                    } else if (datanodeType.equals("Gene")) {
                        pathwayEntity.addProperty(RDF.type, Biopax_level3.Dna);
                    } else if (datanodeType.equals("Protein")) {
                        pathwayEntity.addProperty(RDF.type, Biopax_level3.Protein);
                    } else if (datanodeType.equals("GeneProduct")) {
                        pathwayEntity.addProperty(RDF.type, OWL.equivalentClass); // See
                        // for
                        // details:
                        // http://answers.semanticweb.com/questions/12177/how-do-you-map-an-object-to-be-either-a-or-b-but-nothing-else-in-rdf
                        pathwayEntity.addProperty(OWL.unionOf, geneProductRDFNode);
                    } else if (datanodeType.equals("Pathway")) {
                        Resource interactingPathwayResource = model
                                .createResource(pathwayResourceURI + "Interaction/" + datanodeGraphId);
                        interactingPathwayResource.addProperty(RDF.type, Biopax_level3.Interaction);
                        interactingPathwayResource.addProperty(RDF.subject, pathwayResource);
                        interactingPathwayResource.addProperty(RDF.object, model
                                .createResource(WpNamespaces.nsWikipathways + "Pathway/" + datanodeXrefId));
                    } else if (datanodeType.equals("Pathway")) {
                        pathwayEntity.addProperty(RDF.type, Biopax_level3.Pathway);
                    } else if (datanodeType.equals("Complex")) {
                        pathwayEntity.addProperty(RDF.type, Biopax_level3.Complex);
                    } else {
                        pathwayEntity.addProperty(RDF.type, Biopax_level3.Entity);
                    }
                }

                if (datanodeXrefDatabase != null) {
                    String xRefDataSource = datanodeXrefDatabase.toString().replace(" ", "_");
                    Resource pwElmIdentifierResource = model.createResource(WpNamespaces.nsIdentifiers
                            + "WikiPathways/" + xRefDataSource + "/" + datanodeXrefId);
                    pwElmIdentifierResource.addProperty(RDFS.label, datanodeXrefId);
                    Resource pwElmSourceResource = model
                            .createResource(WpNamespaces.nsIdentifiers + "WikiPathways/" + xRefDataSource);
                    pwElmSourceResource.addProperty(RDFS.label, xRefDataSource);
                    pathwayEntity.addProperty(DC.identifier, pwElmIdentifierResource);
                    pathwayEntity.addProperty(DC.source, pwElmSourceResource);
                }

                if (datanodeGroupRef != null) { // Element is part of a
                    // group
                    pathwayEntity.addProperty(DCTerms.isPartOf,
                            model.getResource(pathwayResourceURI + "Group/" + datanodeGroupRef));
                }
            }

            NodeList lineNL = doc.getElementsByTagName("Line");
            for (int llint = 0; llint < lineNL.getLength(); llint++) {
                // Only take elements with type DATANODE (genes,
                // proteins,
                // metabolites)
                if (lineNL.item(llint).getAttributes().getNamedItem("GraphId") != null) {
                    String lineGraphId = lineNL.item(llint).getAttributes().getNamedItem("GraphId")
                            .getTextContent();

                    // Xref
                    Element LineGraphElement = (Element) lineNL.item(llint);
                    NodeList pointGraphrefs = ((NodeList) xPath.evaluate("//Point/@GraphRef", LineGraphElement,
                            XPathConstants.NODESET));
                    String leftLineGraphRefs = null;
                    String rightLineGraphRefs = null;

                    if ((pointGraphrefs.item(0) != null) && ((pointGraphrefs.item(1) != null))) {
                        leftLineGraphRefs = pointGraphrefs.item(0).getTextContent();
                        rightLineGraphRefs = pointGraphrefs.item(1).getTextContent();
                    }
                    if ((leftLineGraphRefs != null) && (rightLineGraphRefs != null)) {

                        String startGroupOrDatanode;
                        String endGroupOrDatanode;

                        // if
                        // (pwElm.getObjectType().equals(ObjectType.LINE)) {
                        Resource pathwayLine = model
                                .createResource(pathwayResourceURI + "Interaction/" + lineGraphId);
                        pathwayLine.addProperty(RDF.type, Biopax_level3.Interaction);
                        if (groupIdsSet.contains(leftLineGraphRefs)) {
                            startGroupOrDatanode = "Group/";
                        } else {
                            startGroupOrDatanode = "Datanode/";
                        }
                        if (groupIdsSet.contains(rightLineGraphRefs)) {
                            endGroupOrDatanode = "Group/";
                        } else {
                            endGroupOrDatanode = "Datanode/";
                        }
                        pathwayLine.addProperty(RDF.predicate, model
                                .getResource(pathwayResourceURI + startGroupOrDatanode + leftLineGraphRefs));
                        pathwayLine.addProperty(RDF.predicate, model
                                .getResource(pathwayResourceURI + endGroupOrDatanode + rightLineGraphRefs));
                    }
                }
            }
            // TODO Seek a pathway with a state
            /*
             * if (pwElm.getObjectType() == ObjectType.STATE) { Resource
             * pathwayEntity = model .createResource(pathwayResourceURI +
             * "State/" + pwElm.getGraphId()); pathwayEntity
             * .addProperty(DCTerms.isPartOf, pathwayResource);
             * pathwayEntity.addProperty(RDFS.label, pwElm.getTextLabel());
             * } }
             */

            // Get the Biopax References
            NodeList bpRef = doc.getElementsByTagName("BiopaxRef");
            HashMap<String, String> bpRefmap = new HashMap<String, String>();
            if (bpRef != null && bpRef.getLength() > 0) {

                for (int j = 0; j < bpRef.getLength(); j++) {
                    if (bpRef.item(j).getParentNode().getNodeName().equals("DataNode")) {
                        bpRefmap.put(bpRef.item(j).getTextContent(),
                                pathwayResourceURI + "Datanode/" + bpRef.item(j).getParentNode().getAttributes()
                                        .getNamedItem("GraphId").getNodeValue());
                    }

                    if (bpRef.item(j).getParentNode().getNodeName().equals("Pathway")) {
                        bpRefmap.put(bpRef.item(j).getTextContent(), pathwayResourceURI);
                    }
                    if (bpRef.item(j).getParentNode().getNodeName().equals("Line")) {
                        // TODO make sure every entity has a graphId
                        if (bpRef.item(j).getParentNode().getAttributes().getNamedItem("GraphId") != null)
                            bpRefmap.put(bpRef.item(j).getTextContent(),
                                    pathwayResourceURI + "Line/" + bpRef.item(j).getParentNode().getAttributes()
                                            .getNamedItem("GraphId").getNodeValue());
                    }
                    if (bpRef.item(j).getParentNode().getNodeName().equals("State")) {
                        bpRefmap.put(bpRef.item(j).getTextContent(),
                                pathwayResourceURI + "State/" + bpRef.item(j).getParentNode().getAttributes()
                                        .getNamedItem("GraphId").getNodeValue());
                    }
                    if (bpRef.item(j).getParentNode().getNodeName().equals("Group")) {
                        bpRefmap.put(bpRef.item(j).getTextContent(),
                                pathwayResourceURI + "Group/" + bpRef.item(j).getParentNode().getAttributes()
                                        .getNamedItem("GroupId").getNodeValue());
                    }
                }
            }

            NodeList cv = doc.getElementsByTagName("bp:openControlledVocabulary");
            if (cv != null && cv.getLength() > 0) {
                for (int a = 0; a < cv.getLength(); a++) {
                    NodeList cvList = cv.item(a).getChildNodes();
                    String OntologyName = cvList.item(2).getTextContent();
                    String OntologyId = cvList.item(1).getTextContent();
                    if (OntologyName.equals("Pathway Ontology")) {
                        Resource ontologyResource = model
                                .createResource("http://purl.org/obo/owl/PW#" + OntologyId.replace(":", "_"));

                        pathwayResource.addProperty(RDF.type, ontologyResource);
                    }

                    System.out.println(OntologyName + ": " + OntologyId);

                }
            }
            NodeList nl = doc.getElementsByTagName("bp:PublicationXRef");
            System.out.println("test" + nl.getLength());
            if (nl != null && nl.getLength() > 0) {
                System.out.println("test");
                for (int k = 0; k < nl.getLength(); k++) {
                    NodeList refId = nl.item(k).getChildNodes();
                    if (refId.getLength() > 3) {
                        if (refId.item(3).getTextContent().equals("PubMed")
                                && (refId.item(1).getTextContent() != null)) {
                            Resource pubmedEntity = model.createResource(
                                    "http://www.ncbi.nlm.nih.gov/pubmed/" + refId.item(1).getTextContent());
                            pubmedEntity.addProperty(RDF.type, Biopax_level3.Evidence);
                            pubmedEntity.addProperty(DCTerms.identifier, refId.item(1).getTextContent());
                            if (bpRefmap.get(nl.item(k).getAttributes().item(0).getNodeValue()) != null) {

                                Resource tempItem = model.getResource(bpRefmap
                                        .get(nl.item(k).getAttributes().item(0).getNodeValue()).toString());
                                tempItem.addProperty(DCTerms.bibliographicCitation, pubmedEntity);
                            }

                        }
                    } else {
                        System.out.println("PROBLEM with: " + wpIdentifier);
                    }
                }
            }
            nl = doc.getElementsByTagName("bp:PublicationXref");
            System.out.println("test" + nl.getLength());
            if (nl != null && nl.getLength() > 0) {
                System.out.println("test");
                for (int k = 0; k < nl.getLength(); k++) {
                    NodeList refId = nl.item(k).getChildNodes();
                    if (refId.getLength() > 3) {
                        if (refId.item(3).getTextContent().equals("PubMed")
                                && (refId.item(1).getTextContent() != null)) {
                            Resource pubmedEntity = model.createResource(
                                    "http://www.ncbi.nlm.nih.gov/pubmed/" + refId.item(1).getTextContent());
                            pubmedEntity.addProperty(RDF.type, Biopax_level3.Evidence);
                            pubmedEntity.addProperty(DCTerms.identifier, refId.item(1).getTextContent());
                            if (bpRefmap.get(nl.item(k).getAttributes().item(0).getNodeValue()) != null) {

                                Resource tempItem = model.getResource(bpRefmap
                                        .get(nl.item(k).getAttributes().item(0).getNodeValue()).toString());
                                tempItem.addProperty(DCTerms.bibliographicCitation, pubmedEntity);
                            }

                        }
                    } else {
                        System.out.println("PROBLEM with: " + wpIdentifier);
                    }
                }
            }
            nl = doc.getElementsByTagName("bp:publicationXref");
            System.out.println("test" + nl.getLength());
            if (nl != null && nl.getLength() > 0) {
                System.out.println("test");
                for (int k = 0; k < nl.getLength(); k++) {
                    NodeList refId = nl.item(k).getChildNodes();
                    if (refId.getLength() > 3) {
                        if (refId.item(3).getTextContent().equals("PubMed")
                                && (refId.item(1).getTextContent() != null)) {
                            Resource pubmedEntity = model.createResource(
                                    "http://www.ncbi.nlm.nih.gov/pubmed/" + refId.item(1).getTextContent());
                            pubmedEntity.addProperty(RDF.type, Biopax_level3.Evidence);
                            pubmedEntity.addProperty(DCTerms.identifier, refId.item(1).getTextContent());
                            if (bpRefmap.get(nl.item(k).getAttributes().item(0).getNodeValue()) != null) {

                                Resource tempItem = model.getResource(bpRefmap
                                        .get(nl.item(k).getAttributes().item(0).getNodeValue()).toString());
                                tempItem.addProperty(DCTerms.bibliographicCitation, pubmedEntity);
                            }

                        }
                    } else {
                        System.out.println("PROBLEM with: " + wpIdentifier);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    FileOutputStream fout;
    fout = new FileOutputStream("/tmp/WpRDF/" + wpIdentifier + "_" + wpRevision + ".nt");
    model.write(fout, "N-TRIPLE");

}

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

private void parse(Document doc) throws AdapterException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {/*  w w w  .j  a  v  a 2s . c om*/
        Element e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_ENDPOINTS, doc, XPathConstants.NODE);
        if (e != null) {
            NodeList nlList = e.getElementsByTagName(AdapterConstants.CONNECTOR_SH_ENDPOINT);
            if (nlList != null && nlList.item(0) != null) {
                for (int i = 0; i < nlList.getLength(); i++) {
                    Element elem = (Element) nlList.item(i);
                    connEndpoints.put(elem.getAttribute(AdapterConstants.CONNECTOR_SE_NAME),
                            elem.getTextContent());
                    log.debug(elem.getAttribute(AdapterConstants.CONNECTOR_SE_NAME) + ": "
                            + elem.getTextContent());
                }
            }
        }
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(403,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
    try {
        parseCallbacks((Element) xpath.evaluate(AdapterConstants.XPATH_CALLBACKS, doc, XPathConstants.NODE));
    } catch (AdapterException ae) {
        throw ae;
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(404,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
}

From source file:com.alvexcore.share.ShareExtensionRegistry.java

public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes,
        String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion,
        String licenseId) throws Exception {
    // search for extension
    DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
    xmlFact.setNamespaceAware(true);/*  ww  w.  ja  v  a  2  s .  c o m*/
    xmlBuilder = xmlFact.newDocumentBuilder();

    // build query
    Document queryXML = xmlBuilder.newDocument();
    Element rootElement = queryXML.createElement("extension");
    queryXML.appendChild(rootElement);
    Element el = queryXML.createElement("license-id");
    el.appendChild(queryXML.createTextNode(licenseId));
    rootElement.appendChild(el);
    el = queryXML.createElement("id");
    el.appendChild(queryXML.createTextNode(extensionId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-version");
    el.appendChild(queryXML.createTextNode(shareVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-version");
    el.appendChild(queryXML.createTextNode(repoVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-id");
    el.appendChild(queryXML.createTextNode(shareId));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-id");
    el.appendChild(queryXML.createTextNode(repoId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-files");
    rootElement.appendChild(el);
    for (String fileName : shareHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", shareHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    el = queryXML.createElement("repo-files");
    rootElement.appendChild(el);
    for (String fileName : repoHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", repoHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    // query server
    try {
        URL url = new URL(
                "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        // disable host verification
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML),
                new StreamResult(wr));
        wr.close();
        // get response
        Document responseXML = xmlBuilder.parse(conn.getInputStream());
        XPath xpath = XPathFactory.newInstance().newXPath();

        // get version
        String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML,
                XPathConstants.NODESET);
        Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            repoFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET);
        Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            shareFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE))
                .getNodeValue();
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion,
                shareLatestVersion, repoFiles, shareFiles, motd);
    } catch (Exception e) {
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "",
                new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), "");
    }
}

From source file:com.photon.phresco.framework.impl.ConfigurationWriter.java

private Node getNode(String xpath) throws XPathExpressionException {
    XPathExpression xPathExpression = getXPath().compile(xpath);
    return (Node) xPathExpression.evaluate(reader.getDocument(), XPathConstants.NODE);
}

From source file:de.avanux.livetracker.statistics.TrackingStatistics.java

private void setCountryCode(float lat, float lon) {
    Document doc = null;//from  www .  jav  a  2  s. com
    HttpMethod method = null;
    InputStream responseBodyStream = null;
    String responseBodyString = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        String uri = "http://www.geoplugin.net/extras/location.gp?lat=" + lat + "&long=" + lon + "&format=xml";
        log.debug("Retrieving country from " + uri);

        HttpClient client = new HttpClient();
        method = new GetMethod(uri);
        client.executeMethod(method);
        byte[] responseBodyBytes = method.getResponseBody();

        responseBodyString = new String(responseBodyBytes);
        log.debug("Content retrieved: " + responseBodyString);

        // the content is declared as UTF-8 but it seems to be iso-8859-1
        responseBodyString = new String(responseBodyBytes, "iso-8859-1");

        responseBodyStream = new StringBufferInputStream(responseBodyString);
        doc = builder.parse(responseBodyStream);

        XPath xpath = XPathFactory.newInstance().newXPath();
        this.countryCode = ((Node) xpath.evaluate("/geoPlugin/geoplugin_countryCode/text()", doc,
                XPathConstants.NODE)).getNodeValue();
        log.debug("countryCode=" + this.countryCode);
    } catch (Exception e) {
        if (responseBodyString != null) {
            log.error("unparsed xml=" + responseBodyString);
        }
        if (doc != null) {
            log.error("parsed xml=" + getDocumentAsString(doc));
        }
        log.error("Error getting country code.", e);
    } finally {
        try {
            if (responseBodyStream != null) {
                responseBodyStream.close();
            }
            if (method != null) {
                method.releaseConnection();
            }
        } catch (IOException e) {
            log.error("Error releasing resources: ", e);
        }
    }
}

From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java

@Override
public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject) throws Exception {
    logger.debug("----Inside getObjects");

    /* Get user from session manager */
    final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager
            .getSessionInfo(cADCommandObject.getCrmUserId());

    PostMethod postMethod = null;/* www  .  ja v  a2s  .  c om*/
    try {

        /* Get CRM information from user */
        final String serviceURL = user.getScribeMetaObject().getCrmServiceURL();
        final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol();
        final String sessionId = user.getScribeMetaObject().getCrmSessionId();

        /* Create Zoho URL */
        final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/"
                + cADCommandObject.getObjectType() + "s/getRecords";

        logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId);

        /* Instantiate post method */
        postMethod = new PostMethod(zohoURL);

        /* Set request parameters */
        postMethod.setParameter("authtoken", sessionId.trim());
        postMethod.setParameter("scope", "crmapi");

        final HttpClient httpclient = new HttpClient();

        /* Execute method */
        int result = httpclient.executeMethod(postMethod);
        logger.debug("----Inside getObjects response code: " + result + " & body: "
                + postMethod.getResponseBodyAsString());

        /* Check if response if SUCCESS */
        if (result == HttpStatus.SC_OK) {

            /* Create XML document from response */
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(postMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing all nodes value */
            final XPathExpression expr = xpath
                    .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row");

            /* Get node list from response document */
            final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

            /* Check if records founds */
            if (nodeList != null && nodeList.getLength() == 0) {

                /* XPath Query for showing error message */
                XPathExpression errorExpression = xpath.compile("/response/error/message");

                /* Get erroe message from response document */
                Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                /* Check if error message is found */
                if (errorMessage != null) {

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                            + errorMessage.getTextContent());
                } else {

                    /* XPath Query for showing error message */
                    errorExpression = xpath.compile("/response/nodata/message");

                    /* Get erroe message from response document */
                    errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                            + errorMessage.getTextContent());
                }
            } else {

                /* Create new Scribe object list */
                final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

                /* Iterate over node list */
                for (int i = 0; i < nodeList.getLength(); i++) {

                    /* Create list of elements */
                    final List<Element> elementList = new ArrayList<Element>();

                    /* Get node from node list */
                    final Node node = nodeList.item(i);

                    /* Create new Scribe object */
                    final ScribeObject cADbject = new ScribeObject();

                    /* Check if node has child nodes */
                    if (node.hasChildNodes()) {

                        final NodeList subNodeList = node.getChildNodes();

                        /* Create new map for attributes */
                        final Map<String, String> attributeMap = new HashMap<String, String>();

                        /* Iterate over sub node list and create elements */
                        for (int j = 0; j < subNodeList.getLength(); j++) {

                            final Node subNode = subNodeList.item(j);

                            /* This trick is to avoid empty nodes */
                            if (!subNode.getNodeName().contains("#text")) {

                                /* Create element from response */
                                final Element element = (Element) subNode;

                                /* Populate label map */
                                attributeMap.put("label", element.getAttribute("val"));

                                /* Get node name */
                                final String nodeName = element.getAttribute("val").replace(" ",
                                        spaceCharReplacement);

                                /* Validate the node name */
                                if (XMLChar.isValidName(nodeName)) {

                                    /* Add element in list */
                                    elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName,
                                            element.getTextContent(), attributeMap));
                                } else {
                                    logger.debug(
                                            "----Inside getObjects, found invalid XML node; ignoring field: "
                                                    + element.getAttribute("val"));
                                }
                            }
                        }
                    }
                    /* Add all CRM fields */
                    cADbject.setXmlContent(elementList);

                    /* Set type information in object */
                    cADbject.setObjectType(cADCommandObject.getObjectType());

                    /* Add Scribe object in list */
                    cADbjectList.add(cADbject);
                }

                /* Check if no record found */
                if (cADbjectList.size() == 0) {
                    throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM");
                }

                /* Set the final object in command object */
                cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
            }
        } else if (result == HttpStatus.SC_FORBIDDEN) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM");
        } else if (result == HttpStatus.SC_BAD_REQUEST) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
        } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

            /* Create XML document from response */
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(postMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing error message */
            final XPathExpression errorExpression = xpath.compile("/response/error/message");

            /* Get erroe message from response document */
            final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

            if (errorMessage != null) {

                /* Send user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM : "
                        + errorMessage.getTextContent());
            } else {

                /* Send user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
            }
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM");
    } finally {
        /* Release connection socket */
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.FetchResourceTests.java

@Test
public void getValidResourceUsingCOMPACT()
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    String body = getValidResourceUsingContentType(OSLCConstants.CT_COMPACT);

    Document doc = OSLCUtils.createXMLDocFromResponseBody(body);

    Node compactNode = (Node) OSLCUtils.getXPath().evaluate("/*/oslc_v2:Compact", doc, XPathConstants.NODE);
    assertNotNull(compactNode);//from w ww  .  jav a2s .  c o m

    // Everything is optional in the oslc:Compact representation.

    NodeList nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./dc:title", compactNode,
            XPathConstants.NODESET);
    int numNodes = nodeList.getLength();
    assertTrue("Expected number of dcterms:titles to be <=1 but was: " + numNodes, numNodes <= 1);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:shortTitle", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:shortTitles to be <=1 but was: " + numNodes, numNodes <= 1);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:icon", compactNode, XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:icon to be <=1 but was: " + numNodes, numNodes <= 1);

    String iconUrl = null;
    if (numNodes == 1) {
        Node rdfAbout = nodeList.item(0).getAttributes().getNamedItemNS(OSLCConstants.RDF, "resource");
        assertNotNull("oslc:icon in oslc:Compact missing rdf:about attribute", rdfAbout);
        iconUrl = rdfAbout.getTextContent();

        HttpResponse response = OSLCUtils.getResponseFromUrl(iconUrl, iconUrl, creds, "*/*", headers);
        int statusCode = response.getStatusLine().getStatusCode();
        EntityUtils.consume(response.getEntity());
        assertTrue(
                "Fetching icon from " + iconUrl + " did not respond with expected code, received " + statusCode,
                200 <= statusCode && statusCode < 400);
    }

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:smallPreview", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:smallPreview is 0 or 1 but was: " + numNodes, numNodes <= 1);
    if (numNodes == 1)
        validateCompactPreview(nodeList);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:largePreview", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:largePreview is 0 or 1 but was: " + numNodes, numNodes <= 1);
    if (numNodes == 1)
        validateCompactPreview(nodeList);
}

From source file:org.opencastproject.remotetest.server.YoutubeDistributionRestEndpointTest.java

private String getJobStatus(String jobXML) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/* www.  j av a  2 s .c  o m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(jobXML, "UTF-8"));
    return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
            .getAttribute("status");
}