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:aurelienribon.gdxsetupui.ProjectUpdate.java

private void writeGwtDefinition(File gwtDefitionFile, List<GwtModule> modules) {
    try {// ww  w  . j av a2  s.  co m
        Document doc = XmlUtils.createParser().parse(gwtDefitionFile);
        Node root = (Node) XmlUtils.xpath("module", doc, XPathConstants.NODE);
        NodeList nodes = (NodeList) XmlUtils.xpath("module/inherits", doc, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            root.removeChild(nodes.item(i));
        }

        for (GwtModule module : modules) {
            Element elem = doc.createElement("inherits");
            root.appendChild(elem);

            elem.setAttribute("name", module.name);
        }

        XmlUtils.clean(doc);
        String str = XmlUtils.transform(doc);
        FileUtils.writeStringToFile(gwtDefitionFile, str);

    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (TransformerException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.vimeo.VimeoUploadClient.java

@SuppressWarnings("serial")
public void run() {
    // get a upload ticket

    try {/* w w w. j  a  v a  2 s  .co m*/
        ResponseWrapper response = call("vimeo.videos.upload.getTicket", new HashMap<String, String>() {
            {
                put("upload_method", "streaming");
            }
        });
        NamedNodeMap nodeMap = ((Node) path(response.getResponse().getBody(), "//ticket", XPathConstants.NODE))
                .getAttributes();
        final String ticketId = nodeMap.getNamedItem("id").getNodeValue();
        String endpoint = nodeMap.getNamedItem("endpoint").getNodeValue();
        System.out.printf("%-30S: %s\n", "Ticket ID", ticketId);
        System.out.printf("%-30S: %s\n", "Endpoint", endpoint);

        // check ticket
        response = call("vimeo.videos.upload.checkTicket", new HashMap<String, String>() {
            {
                put("ticket_id", ticketId);
            }
        });
        NamedNodeMap nodeMap1 = ((Node) path(response.getResponse().getBody(), "//ticket", XPathConstants.NODE))
                .getAttributes();
        System.out.printf("%-30S: %s\n", "Ticket VALID", nodeMap1.getNamedItem("valid").getNodeValue());

        // TODO: send video
        doPut(endpoint);

        HashMap<String, String> hm = new HashMap<String, String>();
        hm.put("filename", videoFile.getName());
        hm.put("ticket_id", ticketId);

        // Complete the upload process.
        response = call("vimeo.videos.upload.complete", hm);

        NamedNodeMap nodeMap2 = ((Node) path(response.getResponse().getBody(), "//ticket", XPathConstants.NODE))
                .getAttributes();
        final String videoId = nodeMap2.getNamedItem("video_id").getNodeValue();
        System.out.printf("%-30S: %s\n", "Video ID", videoId);

        // TODO: set title

        hm = new HashMap<String, String>();
        hm.put("video_id", videoId);
        hm.put("title", videoTitle);

        response = call("vimeo.videos.setTitle", hm);
        NamedNodeMap nodeMap3 = ((Node) path(response.getResponse().getBody(), "//rsp", XPathConstants.NODE))
                .getAttributes();
        String stat = nodeMap3.getNamedItem("stat").getNodeValue();
        System.out.printf("%-30S: %s\n", "set Title status", stat);

        // TODO: set description

        hm = new HashMap<String, String>();
        hm.put("video_id", videoId);
        hm.put("description", description);

        response = call("vimeo.videos.setDescription", hm);
        NamedNodeMap nodeMap4 = ((Node) path(response.getResponse().getBody(), "//rsp", XPathConstants.NODE))
                .getAttributes();
        String stat2 = nodeMap4.getNamedItem("stat").getNodeValue();
        System.out.printf("%-30S: %s\n", "set Description status", stat2);

        // TODO: set description

        hm = new HashMap<String, String>();
        hm.put("video_id", videoId);
        hm.put("tags", keywords);

        response = call("vimeo.videos.addTags", hm);
        NamedNodeMap nodeMap5 = ((Node) path(response.getResponse().getBody(), "//rsp", XPathConstants.NODE))
                .getAttributes();
        String stat3 = nodeMap5.getNamedItem("stat").getNodeValue();
        System.out.printf("%-30S: %s\n", "set Tags status", stat3);

        // TODO: set

        System.out.printf("DONE.\n\n");
    } catch (APIException e) {
        System.out.println("Fail uploading " + videoTitle);
        e.setStackTrace(null);
    }

    uploading = false;
}

From source file:de.codesourcery.eve.apiclient.utils.XMLParseHelper.java

public static Node selectNode(Document doc, XPathExpression expr, boolean isRequired) {

    final Node result;
    try {/*from  w w w . j  a  va 2s.  c o m*/
        result = (Node) expr.evaluate(doc, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Internal error while evaluating XPath expression " + expr, e);
    }

    if (result == null) {
        if (isRequired) {
            throw new UnparseableResponseException(
                    "Unexpected response XML," + " XPath expression returned nothing: " + expr);
        }
        return null;
    }

    return result;
}

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

@Test
public void catalogRootIsServiceProviderCatalog() throws XPathException {
    //Make sure our root element is a ServiceProviderCatalog
    Node rootNode = (Node) OSLCUtils.getXPath().evaluate("/oslc_disc:ServiceProviderCatalog", doc,
            XPathConstants.NODE);
    assertNotNull(rootNode);//from w  w w. j ava  2 s  . c  o  m
}

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

private long getJobId(String jobXML) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from   w  ww.  j  a  v  a  2  s .c o m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(jobXML, "UTF-8"));
    return Long.parseLong(
            ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
                    .getAttribute("id"));
}

From source file:com.laex.j2objc.AntDelegate.java

/**
 * Append exclude pattern to xml./*from   w ww .  ja  v  a2s .c o  m*/
 * 
 * @param path
 *            the path
 * @param pats
 *            the pats
 * @throws ParserConfigurationException
 *             the parser configuration exception
 * @throws SAXException
 *             the SAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws XPathExpressionException
 *             the x path expression exception
 * @throws CoreException
 *             the core exception
 * @throws TransformerException
 *             the transformer exception
 */
private void appendExcludePatternToXML(IFile path, String[] pats) throws ParserConfigurationException,
        SAXException, IOException, XPathExpressionException, CoreException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(path.getContents());

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr = xpath.compile("project/target/move/fileset");

    Node node = (Node) expr.evaluate(dom, XPathConstants.NODE);
    NodeList children = node.getChildNodes();

    // don't why the last node in the xml should be indexed by length - 2
    Node excludeCopy = children.item(children.getLength() - 2).cloneNode(true);
    for (String pattern : pats) {
        if (StringUtils.isNotEmpty(pattern.trim())) {
            Node newnode = excludeCopy.cloneNode(true);
            newnode.getAttributes().getNamedItem("name").setNodeValue(pattern);
            node.appendChild(newnode);
        }
    }

    // Setup transformers
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(dom), new StreamResult(sw));
    String output = sw.getBuffer().toString();

    // save the ouput
    ByteArrayInputStream bis = new ByteArrayInputStream(output.getBytes("utf-8"));
    path.setContents(bis, 0, null);
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilderTest.java

@Test
public void testCreateCejshXml_TitleVolume() throws Exception {
    CejshConfig conf = new CejshConfig();
    CejshBuilder cb = new CejshBuilder(conf);
    Document articleDoc = cb.getDocumentBuilder()
            .parse(CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
    // issn must match some cejsh_journals.xml/cejsh/journal[@issn=$issn]
    final String pkgIssn = "0231-5955";
    Title title = new Title();
    title.setIssn(pkgIssn);/*from  w  ww  . j  a  va2  s . co m*/
    Volume volume = new Volume();
    volume.setVolumeId("uuid-volume");
    volume.setVolumeNumber("volume1");
    volume.setYear("1985");
    Article article = new Article(null, articleDoc.getDocumentElement(), null);
    cb.setTitle(title);
    cb.setVolume(volume);

    Document articleCollectionDoc = cb.mergeElements(Collections.singletonList(article));
    DOMSource cejshSource = new DOMSource(articleCollectionDoc);
    DOMResult cejshResult = new DOMResult();
    //        dump(cejshSource);

    TransformErrorListener xslError = cb.createCejshXml(cejshSource, cejshResult);
    assertEquals(Collections.emptyList(), xslError.getErrors());
    final Node cejshRootNode = cejshResult.getNode();
    //        dump(new DOMSource(cejshRootNode));

    List<String> errors = cb.validateCejshXml(new DOMSource(cejshRootNode));
    assertEquals(Collections.emptyList(), errors);

    XPath xpath = ProarcXmlUtils.defaultXPathFactory().newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("b", CejshBuilder.NS_BWMETA105));
    assertNotNull(
            xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.ebfd7bf2-169d-476e-a230-0cc39f01764c']",
                    cejshRootNode, XPathConstants.NODE));
    assertEquals("volume1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-volume']/b:name",
            cejshRootNode, XPathConstants.STRING));
    //        assertEquals("issue1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-issue']/b:name", cejshRootNode, XPathConstants.STRING));
    assertEquals("1985", xpath.evaluate(
            "/b:bwmeta/b:element[@id='bwmeta1.element.9358223b-b135-388f-a71e-24ac2c8422c7-1985']/b:name",
            cejshRootNode, XPathConstants.STRING));
}

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

@Test
public void serviceDescriptionHasTitle() throws XPathException {
    //Verify that the ServiceDescription has a dc:title child element
    Node title = (Node) OSLCUtils.getXPath().evaluate("/oslc_cm:ServiceDescriptor/dc:title", doc,
            XPathConstants.NODE);
    assertNotNull(title);//from www.  j a  v  a  2 s . c  om
    assertFalse(title.getTextContent().isEmpty());

    //Verify that the dc:title child element has no children
    NodeList children = (NodeList) OSLCUtils.getXPath().evaluate("/oslc_cm:ServiceDescriptor/dc:title/*", doc,
            XPathConstants.NODESET);
    assertTrue(children.getLength() == 0);
}

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

@Test
public void catalogRootAboutElementPointsToSelf() throws XPathException, IOException {
    //Make sure that we our root element has an rdf:about that points the same server provider catalog
    Node aboutRoot = (Node) OSLCUtils.getXPath().evaluate("/oslc_disc:ServiceProviderCatalog/@rdf:about", doc,
            XPathConstants.NODE);
    assertNotNull(aboutRoot);/*from ww  w  .j ava  2  s .  c o  m*/
    HttpResponse resp = OSLCUtils.getResponseFromUrl(baseUrl, aboutRoot.getNodeValue(), basicCreds, "*/*");
    //Verify the catalogs we get are identical (ie: the same resource)
    assertTrue(responseBody.equals(EntityUtils.toString(resp.getEntity())));
}

From source file:com.espertech.esper.event.xml.SchemaXMLPropertyParser.java

private static Pair<String, QName> makeElementProperty(SchemaElement schemaElement, Tree child,
        XPathNamespaceContext ctx, boolean isAlone, boolean isDynamic, String defaultNamespacePrefix) {
    QName type;/*w ww. j av a2 s .  co m*/
    if (isDynamic) {
        type = XPathConstants.NODE;
    } else if (schemaElement instanceof SchemaElementSimple) {
        type = SchemaUtil.simpleTypeToQName(((SchemaElementSimple) schemaElement).getXsSimpleType());
    } else {
        SchemaElementComplex complex = (SchemaElementComplex) schemaElement;
        if (complex.getOptionalSimpleType() != null) {
            type = SchemaUtil.simpleTypeToQName(complex.getOptionalSimpleType());
        } else {
            // The result is a node
            type = XPathConstants.NODE;
        }
    }

    String prefix;
    if (!isDynamic) {
        prefix = ctx.getPrefix(schemaElement.getNamespace());
    } else {
        prefix = defaultNamespacePrefix;
    }
    if (prefix == null) {
        prefix = "";
    } else {
        prefix += ':';
    }

    switch (child.getType()) {
    case EsperEPL2GrammarParser.EVENT_PROP_SIMPLE:
    case EsperEPL2GrammarParser.EVENT_PROP_DYNAMIC_SIMPLE:
        if (!isDynamic && schemaElement.isArray() && !isAlone) {
            throw new PropertyAccessException(
                    "Simple property not allowed in repeating elements at '" + schemaElement.getName() + "'");
        }
        return new Pair<String, QName>('/' + prefix + child.getChild(0).getText(), type);

    case EsperEPL2GrammarParser.EVENT_PROP_MAPPED:
    case EsperEPL2GrammarParser.EVENT_PROP_DYNAMIC_MAPPED:
        if (!isDynamic && !schemaElement.isArray()) {
            throw new PropertyAccessException("Element " + child.getChild(0).getText()
                    + " is not a collection, cannot be used as mapped property");
        }
        String key = StringValue.parseString(child.getChild(1).getText());
        return new Pair<String, QName>('/' + prefix + child.getChild(0).getText() + "[@id='" + key + "']",
                type);

    case EsperEPL2GrammarParser.EVENT_PROP_INDEXED:
    case EsperEPL2GrammarParser.EVENT_PROP_DYNAMIC_INDEXED:
        if (!isDynamic && !schemaElement.isArray()) {
            throw new PropertyAccessException("Element " + child.getChild(0).getText()
                    + " is not a collection, cannot be used as mapped property");
        }
        int index = IntValue.parseString(child.getChild(1).getText());
        int xPathPosition = index + 1;
        return new Pair<String, QName>(
                '/' + prefix + child.getChild(0).getText() + "[position() = " + xPathPosition + ']', type);

    default:
        throw new IllegalStateException("Event property AST node not recognized, type=" + child.getType());
    }
}