Example usage for org.dom4j XPath selectNodes

List of usage examples for org.dom4j XPath selectNodes

Introduction

In this page you can find the example usage for org.dom4j XPath selectNodes.

Prototype

List<Node> selectNodes(Object context);

Source Link

Document

selectNodes performs this XPath expression on the given Node or List of Node s instances appending all the results together into a single list.

Usage

From source file:com.liferay.alloy.tools.builder.taglib.TagBuilder.java

License:Open Source License

protected Document mergeTlds(Document sourceDoc, Document targetDoc) {
    Element targetRoot = targetDoc.getRootElement();

    DocumentFactory factory = SAXReaderUtil.getDocumentFactory();

    XPath xpathTags = factory.createXPath("//tld:tag");

    Map<String, String> namespaceContextMap = new HashMap<String, String>();

    namespaceContextMap.put(_TLD_XPATH_PREFIX, _TLD_XPATH_URI);

    NamespaceContext namespaceContext = new AlloyGeneratorNamespaceContext(namespaceContextMap);

    xpathTags.setNamespaceContext(namespaceContext);

    List<Node> sources = xpathTags.selectNodes(sourceDoc);

    for (Node source : sources) {
        Element sourceElement = (Element) source;

        String sourceName = sourceElement.elementText("name");

        String xpathTagValue = "//tld:tag[tld:name='" + sourceName + "']";

        XPath xpathTag = factory.createXPath(xpathTagValue);

        xpathTag.setNamespaceContext(namespaceContext);

        List<Node> targets = xpathTag.selectNodes(targetDoc);

        if (targets.size() > 0) {
            Element targetElement = (Element) targets.get(0);

            XPath xpathAttributes = factory.createXPath(xpathTagValue + "//tld:attribute");

            Map<String, String> namespaces = new HashMap<String, String>();

            namespaces.put("tld", StringPool.EMPTY);

            xpathAttributes.setNamespaceURIs(namespaces);

            List<Node> sourceAttributes = xpathAttributes.selectNodes(source);

            for (Node sourceAttribute : sourceAttributes) {
                Element sourceAttributeElement = (Element) sourceAttribute;

                String attributeName = sourceAttributeElement.elementText("name");

                String xpathAttributeValue = "//tld:attribute[tld:name='" + attributeName + "']";

                XPath xpathAttribute = factory.createXPath(xpathTagValue + xpathAttributeValue);

                xpathAttribute.setNamespaceContext(namespaceContext);

                Node targetAttribute = xpathAttribute.selectSingleNode(targetElement);

                if (targetAttribute != null) {
                    targetAttribute.detach();
                }//  w  w w .ja v a 2s . co  m

                targetElement.add(sourceAttributeElement.createCopy());
            }

            Element dynamicAttrElement = targetElement.element("dynamic-attributes");

            if (dynamicAttrElement != null) {
                targetElement.add(dynamicAttrElement.detach());
            }
        } else {
            targetRoot.add(sourceElement.createCopy());
        }
    }

    return targetDoc;
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

License:Open Source License

private static void _readResourceActionModels(String implDir, InputStream inputStream,
        Set<String> resourceActionModels) throws Exception {

    SAXReader saxReader = _getSAXReader();

    Document document = saxReader.read(inputStream);

    Element rootElement = document.getRootElement();

    List<Element> resourceElements = rootElement.elements("resource");

    for (Element resourceElement : resourceElements) {
        resourceActionModels.addAll(/*w  w w .jav  a  2s .  c  o m*/
                readResourceActionModels(implDir, new String[] { resourceElement.attributeValue("file") }));
    }

    XPath xPath = document.createXPath("//model-resource/model-name");

    List<Element> elements = xPath.selectNodes(rootElement);

    for (Element element : elements) {
        resourceActionModels.add(element.getText().trim());
    }
}

From source file:com.mor.blogengine.xpath.SearchEngineConfigurator.java

License:Open Source License

resultType findContent(String pExpression) throws InvalidXPathException, NoMatchesFoundException,
        MissingPropertyException, IncorrectPropertyValueException {

    XPath xpathSelector = createXPath(pExpression);

    @SuppressWarnings("unchecked")
    resultType list = (resultType) ((xpathSelector.selectNodes(mDoc).size() > 0)
            ? xpathSelector.selectNodes(mDoc)
            : null);/*from   ww w  .  ja v a 2s .c  o m*/
    trace("Searched " + pExpression);
    if (list == null) {

        throw new NoMatchesFoundException(pExpression, isDebugOn());

    }

    return list;
}

From source file:com.nokia.ant.Database.java

License:Open Source License

private void readSignals(Element root, String antFile) throws DocumentException, IOException {
    SAXReader xmlReader = new SAXReader();
    Document antDoc = xmlReader.read(new File(antFile));

    XPath xpath = DocumentHelper.createXPath("//hlm:signalListenerConfig");
    xpath.setNamespaceURIs(map);//from   www.  j  av  a  2 s . co  m
    List signalNodes = xpath.selectNodes(antDoc);
    for (Iterator iterator = signalNodes.iterator(); iterator.hasNext();) {
        signaldoc = antDoc;
        Element propertyNode = (Element) iterator.next();
        String signalid = propertyNode.attributeValue("id");

        String signaltarget = propertyNode.attributeValue("target");
        List existinglist = globalSignalList.get(signaltarget);
        String failbuild = signalType(signalid, signaldoc);
        if (existinglist == null)
            existinglist = new ArrayList<String>();
        existinglist.add(signalid + "," + failbuild);
        globalSignalList.put(signaltarget, existinglist);
    }
}

From source file:com.nokia.ant.Database.java

License:Open Source License

private String signalType(String signalid, Document antDoc) {
    XPath xpath2 = DocumentHelper
            .createXPath("//hlm:signalListenerConfig[@id='" + signalid + "']/signalNotifierInput/signalInput");
    xpath2.setNamespaceURIs(map);// w  w w.j a va  2 s  . c  o  m
    List signalNodes3 = xpath2.selectNodes(antDoc);

    for (Iterator iterator3 = signalNodes3.iterator(); iterator3.hasNext();) {
        Element propertyNode3 = (Element) iterator3.next();
        String signalinputid = propertyNode3.attributeValue("refid");

        XPath xpath3 = DocumentHelper.createXPath("//hlm:signalInput[@id='" + signalinputid + "']");
        xpath3.setNamespaceURIs(map);
        List signalNodes4 = xpath3.selectNodes(antDoc);
        for (Iterator iterator4 = signalNodes4.iterator(); iterator4.hasNext();) {
            Element propertyNode4 = (Element) iterator4.next();
            return propertyNode4.attributeValue("failbuild");
        }
    }
    return null;
}

From source file:com.nokia.helium.ant.data.Database.java

License:Open Source License

@SuppressWarnings("unchecked")
private void readSignals(String antFile) throws IOException {
    SAXReader xmlReader = new SAXReader();
    Document antDoc;/*from w w  w. j a  va2  s  .c  o m*/
    try {
        antDoc = xmlReader.read(new File(antFile));
    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }

    XPath xpath = DocumentHelper.createXPath("//hlm:signalListenerConfig");
    xpath.setNamespaceURIs(namespaceMap);
    List<Node> signalNodes = xpath.selectNodes(antDoc);
    for (Iterator<Node> iterator = signalNodes.iterator(); iterator.hasNext();) {
        signaldoc = antDoc;
        Element propertyNode = (Element) iterator.next();
        String signalid = propertyNode.attributeValue("id");
        String signaltarget = propertyNode.attributeValue("target");
        List<String> existinglist = globalSignalList.get(signaltarget);
        String failbuild = findSignalFailMode(signalid, signaldoc);
        if (existinglist == null) {
            existinglist = new ArrayList<String>();
        }
        existinglist.add(signalid + "," + failbuild);
        globalSignalList.put(signaltarget, existinglist);
    }
}

From source file:com.nokia.helium.ant.data.Database.java

License:Open Source License

@SuppressWarnings("unchecked")
private String findSignalFailMode(String signalid, Document antDoc) {
    XPath xpath2 = DocumentHelper
            .createXPath("//hlm:signalListenerConfig[@id='" + signalid + "']/signalNotifierInput/signalInput");
    xpath2.setNamespaceURIs(namespaceMap);
    List signalNodes3 = xpath2.selectNodes(antDoc);

    for (Iterator iterator3 = signalNodes3.iterator(); iterator3.hasNext();) {
        Element propertyNode3 = (Element) iterator3.next();
        String signalinputid = propertyNode3.attributeValue("refid");

        XPath xpath3 = DocumentHelper.createXPath("//hlm:signalInput[@id='" + signalinputid + "']");
        xpath3.setNamespaceURIs(namespaceMap);
        List signalNodes4 = xpath3.selectNodes(antDoc);
        for (Iterator iterator4 = signalNodes4.iterator(); iterator4.hasNext();) {
            Element propertyNode4 = (Element) iterator4.next();
            return propertyNode4.attributeValue("failbuild");
        }/*from  w  ww .j  ava  2 s .  c  o  m*/
    }
    return null;
}

From source file:com.nokia.helium.ant.data.ProjectMeta.java

License:Open Source License

@SuppressWarnings("unchecked")
public void getConfigSignals(String targetName, List<String> signals) {
    XPath xpath = DocumentHelper.createXPath("//hlm:signalListenerConfig[@target='" + targetName + "']");
    xpath.setNamespaceURIs(Database.NAMESPACE_MAP);
    List<Node> signalNodes = xpath.selectNodes(getNode());
    for (Iterator<Node> iterator = signalNodes.iterator(); iterator.hasNext();) {
        Element propertyNode = (Element) iterator.next();
        String signalid = propertyNode.attributeValue("id");
        String failbuild = findSignalFailMode(signalid, getNode().getDocument());
        signals.add(signalid + "(" + failbuild + ")");
    }// w ww.  ja v a2 s . c  om
}

From source file:com.nokia.helium.ant.data.ProjectMeta.java

License:Open Source License

@SuppressWarnings("rawtypes")
private String findSignalFailMode(String signalid, Document antDoc) {
    XPath xpath2 = DocumentHelper
            .createXPath("//hlm:signalListenerConfig[@id='" + signalid + "']/signalNotifierInput/signalInput");
    xpath2.setNamespaceURIs(Database.NAMESPACE_MAP);
    List signalNodes3 = xpath2.selectNodes(antDoc);
    for (Iterator iterator3 = signalNodes3.iterator(); iterator3.hasNext();) {
        Element propertyNode3 = (Element) iterator3.next();
        String signalinputid = propertyNode3.attributeValue("refid");

        XPath xpath3 = DocumentHelper.createXPath("//hlm:signalInput[@id='" + signalinputid + "']");
        xpath3.setNamespaceURIs(Database.NAMESPACE_MAP);
        List signalNodes4 = xpath3.selectNodes(antDoc);
        for (Iterator iterator4 = signalNodes4.iterator(); iterator4.hasNext();) {
            Element propertyNode4 = (Element) iterator4.next();
            return propertyNode4.attributeValue("failbuild");
        }/* www. ja  va  2 s . c o m*/
    }
    return null;
}

From source file:com.ostrichemulators.semtool.ui.components.playsheets.BrowserPlaySheet2.java

License:Open Source License

protected BufferedImage getExportImageFromSVGBlock() throws IOException {
    log.debug("Using SVG block to save image.");
    DOMReader rdr = new DOMReader();
    Document doc = rdr.read(engine.getDocument());
    Document svgdoc = null;//from   ww  w.j a  va  2  s . c om
    File svgfile = null;
    try {
        Map<String, String> namespaceUris = new HashMap<>();
        namespaceUris.put("svg", "http://www.w3.org/2000/svg");
        namespaceUris.put("xhtml", "http://www.w3.org/1999/xhtml");

        XPath xp = DocumentHelper.createXPath("//svg:svg");
        xp.setNamespaceURIs(namespaceUris);
        // don't forget about the styles
        XPath stylexp = DocumentHelper.createXPath("//xhtml:style");
        stylexp.setNamespaceURIs(namespaceUris);

        svgdoc = DocumentHelper.createDocument();
        Element svg = null;
        List<?> theSVGElements = xp.selectNodes(doc);
        if (theSVGElements.size() == 1) {
            svg = Element.class.cast(theSVGElements.get(0)).createCopy();
        } else {
            int currentTop = 0;
            int biggestSize = 0;
            for (int i = 0; i < theSVGElements.size(); i++) {
                Element thisElement = Element.class.cast(theSVGElements.get(i)).createCopy();
                int thisSize = thisElement.asXML().length();
                if (thisSize > biggestSize) {
                    currentTop = i;
                    biggestSize = thisSize;
                }
            }
            svg = Element.class.cast(theSVGElements.get(currentTop)).createCopy();
        }

        svgdoc.setRootElement(svg);

        Element oldstyle = Element.class.cast(stylexp.selectSingleNode(doc));
        if (null != oldstyle) {
            Element defs = svg.addElement("defs");
            Element style = defs.addElement("style");
            style.addAttribute("type", "text/css");
            String styledata = oldstyle.getTextTrim();
            style.addCDATA(styledata);
            // put the stylesheet definitions first
            List l = svg.elements();
            l.remove(defs);
            l.add(0, defs);
        }

        // clean up the SVG a little...
        // d3 comes up with coords like
        // M360,27475.063247863247C450,27475.063247863247 450,27269.907692307694 540,27269.907692307694
        XPath cleanxp1 = DocumentHelper.createXPath("//svg:path");
        Pattern pat = Pattern.compile(",([0-9]+)\\.([0-9]{1,2})[0-9]+");
        cleanxp1.setNamespaceURIs(namespaceUris);
        List<?> cleanups = cleanxp1.selectNodes(svgdoc);
        for (Object n : cleanups) {
            Element e = Element.class.cast(n);
            String dstr = e.attributeValue("d");
            Matcher m = pat.matcher(dstr);
            dstr = m.replaceAll(",$1.$2 ");
            e.addAttribute("d", dstr.replaceAll("([0-9])C([0-9])", "$1 C$2").trim());
        }
        XPath cleanxp2 = DocumentHelper.createXPath("//svg:g[@class='node']");
        cleanxp2.setNamespaceURIs(namespaceUris);
        cleanups = cleanxp2.selectNodes(svgdoc);
        for (Object n : cleanups) {
            Element e = Element.class.cast(n);
            String dstr = e.attributeValue("transform");
            Matcher m = pat.matcher(dstr);
            dstr = m.replaceAll(",$1.$2");
            e.addAttribute("transform", dstr.trim());
        }

        svgfile = File.createTempFile("graphviz-", ".svg");
        try (Writer svgw = new BufferedWriter(new FileWriter(svgfile))) {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlw = new XMLWriter(svgw, format);
            xmlw.write(svgdoc);
            xmlw.close();

            if (log.isDebugEnabled()) {
                FileUtils.copyFile(svgfile, new File(FileUtils.getTempDirectory(), "graphvisualization.svg"));
            }
        }

        try (Reader svgr = new BufferedReader(new FileReader(svgfile))) {
            TranscoderInput inputSvg = new TranscoderInput(svgr);

            ByteArrayOutputStream baos = new ByteArrayOutputStream((int) svgfile.length());
            TranscoderOutput outputPng = new TranscoderOutput(baos);

            try {
                PNGTranscoder transcoder = new PNGTranscoder();
                transcoder.addTranscodingHint(PNGTranscoder.KEY_INDEXED, 256);
                transcoder.addTranscodingHint(ImageTranscoder.KEY_BACKGROUND_COLOR, Color.WHITE);
                transcoder.transcode(inputSvg, outputPng);
            } catch (Throwable t) {
                log.error(t, t);
            }
            baos.flush();
            baos.close();

            return ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
        }
    } catch (InvalidXPathException e) {
        log.error(e);
        String msg = "Problem creating image";
        if (null != svgdoc) {
            try {
                File errsvg = new File(FileUtils.getTempDirectory(), "graphvisualization.svg");
                FileUtils.write(errsvg, svgdoc.asXML(), Charset.defaultCharset());
                msg = "Could not create the image. SVG data store here: " + errsvg.getAbsolutePath();
            } catch (IOException ex) {
                // don't care
            }
        }
        throw new IOException(msg, e);
    } finally {
        if (null != svgfile) {
            FileUtils.deleteQuietly(svgfile);
        }
    }
}