Example usage for org.dom4j XPath selectSingleNode

List of usage examples for org.dom4j XPath selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(Object context);

Source Link

Document

selectSingleNode evaluates this XPath expression on the given Node or List of Node s and returns the result as a single Node instance.

Usage

From source file:com.controlj.addon.weather.noaa.StationSourceImpl.java

License:Open Source License

private String getStringValue(XPath xpath) {
    String result = null;//from ww w  .  ja va  2 s .  c o  m
    Node node = xpath.selectSingleNode(stationNode);
    if (node != null) {
        result = node.getText();
    }
    return result;
}

From source file:com.digiaplus.modules.scorm.ScormCPManifestTreeModel.java

License:Apache License

/**
 * Constructor of the content packaging tree model
 * @param manifest the imsmanifest.xml file
 * @param itemStatus a Map containing the status of each item like "completed, not attempted, ..."
 *///ww w. ja v a  2s  .c o  m
public ScormCPManifestTreeModel(File manifest, Map itemStatus) {
    this.itemStatus = itemStatus;
    Document doc = loadDocument(manifest);
    // get all organization elements. need to set namespace
    rootElement = doc.getRootElement();
    String nsuri = rootElement.getNamespace().getURI();
    nsuris.put("ns", nsuri);

    XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);

    XPath metares = rootElement.createXPath("//ns:resources");
    metares.setNamespaceURIs(nsuris);
    Element elResources = (Element) metares.selectSingleNode(rootElement);
    if (elResources == null)
        throw new DAPRuntimeException(this.getClass(), "could not find element resources");

    List resourcesList = elResources.elements("resource");
    resources = new HashMap(resourcesList.size());
    for (Iterator iter = resourcesList.iterator(); iter.hasNext();) {
        Element elRes = (Element) iter.next();
        String identVal = elRes.attributeValue("identifier");
        String hrefVal = elRes.attributeValue("href");
        if (hrefVal != null) { // href is optional element for resource element
            try {
                hrefVal = URLDecoder.decode(hrefVal, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // each JVM must implement UTF-8
            }
        }
        resources.put(identVal, hrefVal);
    }
    /*
     * Get all organizations
     */
    List organizations = new LinkedList();
    organizations = meta.selectNodes(rootElement);
    if (organizations.isEmpty()) {
        throw new DAPRuntimeException(this.getClass(), "could not find element organization");
    }
    GenericTreeNode gtn = buildTreeNodes(organizations);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}

From source file:com.glaf.jbpm.tag.JbpmProcessImageTag.java

License:Apache License

private int[] extractBoxConstraint(Element root) {
    int[] result = new int[4];
    String nodeName = currentToken.getNode().getName();
    XPath xPath = new DefaultXPath("//node[@name='" + nodeName + "']");
    Element node = (Element) xPath.selectSingleNode(root);
    if (node != null) {
        result[0] = Integer.parseInt(node.attribute("x").getValue());
        result[1] = Integer.parseInt(node.attribute("y").getValue());
        result[2] = Integer.parseInt(node.attribute("width").getValue());
        result[3] = Integer.parseInt(node.attribute("height").getValue());
    }//from www  .ja  v  a 2s.  c om
    return result;
}

From source file:com.glaf.jbpm.tag.JbpmProcessImageTag.java

License:Apache License

private int[] extractBoxConstraint(Element root, Token token) {
    int[] result = new int[4];
    String nodeName = token.getNode().getName();
    XPath xPath = new DefaultXPath("//node[@name='" + nodeName + "']");
    Element node = (Element) xPath.selectSingleNode(root);
    if (node != null) {
        result[0] = Integer.parseInt(node.attribute("x").getValue());
        result[1] = Integer.parseInt(node.attribute("y").getValue());
        result[2] = Integer.parseInt(node.attribute("width").getValue());
        result[3] = Integer.parseInt(node.attribute("height").getValue());
    }/*ww w . ja v a  2  s  . co m*/
    return result;
}

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  .j  av a2s .  c o 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.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  w w w .  j ava  2 s  .  c o  m*/
    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);
        }
    }
}

From source file:com.pureinfo.dolphinview.component.model.ViewComponent.java

License:Open Source License

private String getPathText(Element _elemant, String _sPath) {
    XPath elementPath = _elemant.createXPath(_sPath);
    Element element = (Element) elementPath.selectSingleNode(_elemant);
    if (element == null) {
        return "";
    }/*w w  w .j  a  v  a2  s  .c om*/
    return element.getText();
}

From source file:com.surenpi.autotest.suite.parser.XmlSuiteParser.java

License:Apache License

/**
 * ??//  w ww  . j av a  2 s .c  o  m
 * @param suiteInputStream ??
 * @return 
 * @throws DocumentException
 */
public Suite parse(InputStream suiteInputStream) throws DocumentException {
    SAXReader reader = new SAXReader();
    reader.setEncoding("utf-8");

    Document document = reader.read(suiteInputStream);

    simpleNamespaceContext.addNamespace("ns", NS_URI);

    XPath xpath = new DefaultXPath("/ns:suite");
    xpath.setNamespaceContext(simpleNamespaceContext);
    Element suiteEle = (Element) xpath.selectSingleNode(document);
    if (suiteEle == null) {
        suiteEle = document.getRootElement();
        //         throw new RuntimeException("Can not found suite config.");
    }

    Suite suite = new Suite();
    String xmlConfPath = suiteEle.attributeValue("pageConfig");
    String pagePackage = suiteEle.attributeValue("pagePackage", "");
    String rows = suiteEle.attributeValue("rows", "1");
    String lackLines = suiteEle.attributeValue("lackLines", "nearby");
    String errorLines = suiteEle.attributeValue("errorLines", "stop");
    String afterSleep = suiteEle.attributeValue("afterSleep", "0");

    suite.setXmlConfPath(xmlConfPath);
    suite.setPagePackage(pagePackage);
    suite.setRows(rows);
    suite.setLackLines(lackLines);
    suite.setErrorLines(errorLines);
    suite.setAfterSleep(Long.parseLong(afterSleep));

    pagesParse(document, suite);

    return suite;
}

From source file:com.surenpi.autotest.suite.parser.XmlSuiteParser.java

License:Apache License

/**
 * ?page?//from  w  w  w.  j  a v  a2 s . c om
 * @param document
 * @param suite
 */
private void pagesParse(Document document, Suite suite) {
    List<SuitePage> pageList = new ArrayList<SuitePage>();
    suite.setPageList(pageList);

    String pagePackage = suite.getPagePackage();
    if (!StringUtils.isBlank(pagePackage)) {
        pagePackage = (pagePackage.trim() + ".");
    }

    XPath xpath = new DefaultXPath("/ns:suite/ns:page");
    xpath.setNamespaceContext(simpleNamespaceContext);

    @SuppressWarnings("unchecked")
    List<Element> pageNodes = xpath.selectNodes(document);
    if (pageNodes == null || pageNodes.size() == 0) {
        throw new RuntimeException("Can not found page config.");
    }

    for (Element pageEle : pageNodes) {
        String pageCls = pageEle.attributeValue("class");

        xpath = new DefaultXPath("ns:actions");
        xpath.setNamespaceContext(simpleNamespaceContext);

        Element actionsEle = (Element) xpath.selectSingleNode(pageEle);
        if (actionsEle == null) {
            throw new RuntimeException("Can not found actions config.");
        }

        String disable = actionsEle.attributeValue("disable", "false");
        if (Boolean.parseBoolean(disable)) {
            continue;
        }

        String beforeSleep = actionsEle.attributeValue("beforeSleep", "0");
        String afterSleep = actionsEle.attributeValue("afterSleep", "0");
        String repeat = actionsEle.attributeValue("repeat", "1");

        List<SuiteAction> actionList = new ArrayList<SuiteAction>();

        SuitePage suitePage = new SuitePage(String.format("%s%s", pagePackage, pageCls));
        suitePage.setActionList(actionList);
        suitePage.setRepeat(Integer.parseInt(repeat));

        pageList.add(suitePage);

        parse(actionList, actionsEle, beforeSleep, afterSleep);
    }
}

From source file:com.ten45.service.aggregator.ConfigurationServiceImpl.java

/**
 * Expand the original configuration document with the referred node.
 * It reads the referred document, finds the referred element in the same 
 * path as the original document, and moves all the children of the 
 * referred element into the original element.
 * /*from   w w w. j a v a 2 s  . co  m*/
 * @param doc
 * @param node
 * @return
 * @throws DocumentException
 */
private Document expandReference(Document doc, Node node) throws DocumentException {
    // Find the 'anchor' element that contains the reference declaration.
    Element anchor = node.getParent();
    XPath anchorXPath = DocumentHelper.createXPath(anchor.getPath());

    // Remove the reference declaration node from the document.
    node.detach();

    // Read the new configuration.
    String resourceName = rootPath + node.getText() + ".xml";
    log.debug("Reading resource " + resourceName);
    InputStream in = this.getClass().getResourceAsStream(resourceName);
    SAXReader reader = new SAXReader();
    try {
        Document refDoc = reader.read(in);

        Element refElement = (Element) anchorXPath.selectSingleNode(refDoc);
        if (refElement != null) {
            log.debug("Expanding " + anchorXPath.getText() + " with " + refElement.asXML());
            // Move all elements from the referenced document into the anchor.
            List children = refElement.elements();
            if (children != null && children.size() > 0) {
                for (int i = 0; i < children.size(); i++) {
                    Element child = (Element) children.get(i);
                    XPath refXPath = DocumentHelper.createXPath(child.getPath());
                    if (refXPath.selectSingleNode(doc) == null) {
                        log.debug("Adding element " + refXPath.getText());
                        child.detach();
                        anchor.add(child);
                    } else {
                        log.debug("Ignore pre-existing element " + refXPath.getText());
                    }
                }
            }
        }
    } catch (DocumentException de) {
        throw de;
    }
    return doc;
}