Example usage for org.dom4j XPath setNamespaceURIs

List of usage examples for org.dom4j XPath setNamespaceURIs

Introduction

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

Prototype

void setNamespaceURIs(Map<String, String> map);

Source Link

Document

Sets the current NamespaceContext from a Map where the keys are the String namespace prefixes and the values are the namespace URIs.

Usage

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  ww .  j a va  2s  .  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.panet.imeta.trans.steps.getxmldata.GetXMLData.java

License:Open Source License

@SuppressWarnings("unchecked")
private boolean applyXPath() {
    try {/*from   ww w  .j a va2 s.  c  om*/
        XPath xpath = data.document.createXPath(data.PathValue);
        if (meta.isNamespaceAware()) {
            xpath = data.document.createXPath(addNSPrefix(data.PathValue, data.PathValue));
            xpath.setNamespaceURIs(data.NAMESPACE);
        }
        // get nodes list
        data.an = (List<AbstractNode>) xpath.selectNodes(data.document);
        data.nodesize = data.an.size();
        data.nodenr = 0;
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("GetXMLData.Log.ErrorApplyXPath", e.getMessage()));
        return false;
    }
    return true;
}

From source file:com.panet.imeta.trans.steps.getxmldata.GetXMLData.java

License:Open Source License

private Object[] processPutRow(Object[] row, AbstractNode node) throws KettleException {
    // Create new row...
    Object[] outputRowData = buildEmptyRow();

    try {/*from  w ww . j  a va  2  s  .  c  om*/
        data.nodenr++;
        if (row != null)
            System.arraycopy(row, 0, outputRowData, 0, data.totalpreviousfields);
        // Read fields...
        for (int i = 0; i < data.nrInputFields; i++) {
            // Get field
            GetXMLDataField xmlDataField = meta.getInputFields()[i];
            // Get the Path to look for
            String XPathValue = environmentSubstitute(xmlDataField.getXPath());
            // Get the path type
            String Element_Type = xmlDataField.getElementTypeCode();

            if (meta.isuseToken()) {

                // See if user use Token inside path field
                // The syntax is : @_Fieldname-
                // PDI will search for Fieldname value and replace it
                // Fieldname must be defined before the current node
                int indexvarstart = XPathValue.indexOf(data.tokenStart);
                int indexvarend = XPathValue.indexOf(data.tokenEnd);

                if (indexvarstart >= 0 && indexvarend >= 0) {
                    String NameVarInputField = XPathValue.substring(indexvarstart + 2, indexvarend);
                    for (int k = 0; k < meta.getInputFields().length; k++) {
                        GetXMLDataField Tmp_xmlInputField = meta.getInputFields()[k];
                        if (Tmp_xmlInputField.getName().equalsIgnoreCase(NameVarInputField)) {
                            XPathValue = XPathValue.replaceAll(
                                    data.tokenStart + NameVarInputField + data.tokenEnd,
                                    "'" + outputRowData[data.totalpreviousfields + k] + "'");
                            if (log.isDetailed())
                                log.logDetailed(toString(), XPathValue);
                        }
                    }
                }
            } // end if use token

            // Get node value
            String nodevalue = null;
            if (!Element_Type.equals("node"))
                XPathValue = '@' + XPathValue; // TODO only put @ to the
            // last element in path, not
            // in front at all

            if (meta.isNamespaceAware()) {
                XPath xpathField = node.createXPath(addNSPrefix(XPathValue, data.PathValue));
                xpathField.setNamespaceURIs(data.NAMESPACE);
                nodevalue = xpathField.valueOf(node);
            } else {
                nodevalue = node.valueOf(XPathValue);
            }

            // Do trimming
            switch (xmlDataField.getTrimType()) {
            case GetXMLDataField.TYPE_TRIM_LEFT:
                nodevalue = Const.ltrim(nodevalue);
                break;
            case GetXMLDataField.TYPE_TRIM_RIGHT:
                nodevalue = Const.rtrim(nodevalue);
                break;
            case GetXMLDataField.TYPE_TRIM_BOTH:
                nodevalue = Const.trim(nodevalue);
                break;
            default:
                break;
            }

            if (meta.getIsInFields()) {
                // Add result field to input stream
                outputRowData = RowDataUtil.addValueData(outputRowData, data.totalpreviousfields + i,
                        nodevalue);
            }
            // Do conversions
            //
            ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(data.totalpreviousfields + i);
            ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(data.totalpreviousfields + i);

            if (targetValueMeta.isBinary()) {
                byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(nodevalue);
                outputRowData[data.totalpreviousfields + i] = b;
            } else {
                outputRowData[data.totalpreviousfields + i] = targetValueMeta.convertData(sourceValueMeta,
                        nodevalue);
            }

            // Do we need to repeat this field if it is null?
            if (meta.getInputFields()[i].isRepeated()) {
                if (data.previousRow != null && Const.isEmpty(nodevalue) && data.previousRow != null
                        && data.previousRow.length > data.totalpreviousfields + i) {
                    outputRowData[data.totalpreviousfields + i] = data.previousRow[data.totalpreviousfields
                            + i];
                }
            }
        } // End of loop over fields...

        int rowIndex = data.nrInputFields;

        // See if we need to add the filename to the row...
        if (meta.includeFilename() && !Const.isEmpty(meta.getFilenameField())) {
            outputRowData[rowIndex++] = KettleVFS.getFilename(data.file);
        }
        // See if we need to add the row number to the row...
        if (meta.includeRowNumber() && !Const.isEmpty(meta.getRowNumberField())) {
            outputRowData[rowIndex++] = new Long(data.rownr);
        }

        RowMetaInterface irow = getInputRowMeta();

        data.previousRow = irow == null ? outputRowData : (Object[]) irow.cloneRow(outputRowData); // copy it to make
        // surely the next step doesn't change it in between...

    } catch (Exception e) {
        if (getStepMeta().isDoingErrorHandling()) {
            // Simply add this row to the error row
            putError(data.outputRowMeta, outputRowData, 1, e.toString(), null, "GetXMLData001");
            data.errorInRowButContinue = true;
            return null;
        } else {
            log.logError(toString(), e.toString());
            throw new KettleException(e.toString());
        }
    }
    return outputRowData;
}

From source file:com.webtide.jetty.load.generator.jenkins.AlpnBootVersions.java

License:Open Source License

private AlpnBootVersions() {
    Map<String, String> map = new HashMap<>();

    try {/*w  w w .j a va  2 s  . c o m*/
        try (InputStream inputStream = this.getClass().getResourceAsStream("/jetty/jetty-project.pom")) {

            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            Map<String, String> namespaceMap = new HashMap<>();
            namespaceMap.put("mvn", "http://maven.apache.org/POM/4.0.0");
            XPath xpath = document.createXPath("//mvn:profiles/mvn:profile");
            xpath.setNamespaceURIs(namespaceMap);

            List<DefaultElement> nodes = xpath.selectNodes(document);
            for (DefaultElement o : nodes) {
                if (StringUtils.startsWith((String) o.element("id").getData(), "8u")) {
                    // olamy well a bit fragile way to parse if more than one property...
                    //"//mvn:properties/mvn:alpn.version"
                    // o.selectSingleNode( "//properties/alpn.version" );
                    Node version = o.element("properties").element("alpn.version");
                    //"//mvn:activation/mvn:property/mvn:value"
                    //o.selectSingleNode( "//activation/property/value" );
                    Node javaVersion = o.element("activation").element("property").element("value");

                    map.put(javaVersion.getStringValue(), version.getStringValue());
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    jdkVersionAlpnBootVersion = Collections.unmodifiableMap(map);
}

From source file:com.zimbra.common.soap.SoapTestHarness.java

License:Open Source License

private void doSelect(Element context, Element parent)
        throws SoapFaultException, IOException, HarnessException {

    String path = parent.getAttribute(A_PATH, null);
    String attr = parent.getAttribute(A_ATTR, null);
    String match = parent.getAttribute(A_MATCH, null);

    Element se;//w  ww  .  j  a  v  a  2 s .c  o  m
    if (path != null) {
        // FIXME: hacky!
        org.dom4j.Element d4context = context.toXML();
        org.dom4j.XPath xpath = d4context.createXPath(path);
        xpath.setNamespaceURIs(getURIs(mResponseProto));
        org.dom4j.Node node = xpath.selectSingleNode(d4context);
        //System.out.println("path = " + path + " node = " + node);
        if (!(node instanceof org.dom4j.Element)) {
            mCurrent.check(false, "select failed: " + path);
            return;
        } else {
            se = Element.convertDOM((org.dom4j.Element) node);
            mCurrent.check(true, "select ok: " + path);
        }
    } else {
        se = context;
    }

    String value;
    if (attr != null) {
        value = se.getAttribute(attr, null);
    } else {
        value = se.getText();
    }

    if (match != null) {
        boolean ok = Pattern.matches(match, value);
        mCurrent.check(ok, "match " + (ok ? "ok" : "failed") + " (" + match + ")" + " (" + value + ")");
    }

    //System.out.println(se.getText());
    String property = parent.getAttribute(A_SET, null);
    if (property != null) {
        //System.out.println(property+" "+value);
        setProperty(property, value);
    }

    for (Element e : parent.listElements()) {
        if (e.getQName().equals(E_SELECT)) {
            doSelect(se, e);
        } else {
            checkGlobals(e);
        }
    }
}

From source file:cz.mzk.editor.server.fedora.utils.Dom4jUtils.java

License:Open Source License

/**
 * Creates Xpath with prefixes from class Namespaces
 * //  ww w  .j  a  v a2s  . c  om
 * @param expression
 * @return
 */
public static XPath createXPath(String expression) {
    XPath result = DocumentHelper.createXPath(expression);
    result.setNamespaceURIs(Namespaces.getPrefixUriMap());
    return result;
}

From source file:de.innovationgate.wga.server.api.Xml.java

License:Open Source License

private XPath createXPath(String xpath, Branch branch, Map<String, String> ns) {
    XPath xpathObj = branch.createXPath(xpath);
    if (ns != null) {
        xpathObj.setNamespaceURIs(ns);
    }/*from w w w . j a v  a 2  s.c  o m*/
    return xpathObj;
}

From source file:dk.netarkivet.common.utils.SimpleXml.java

License:Open Source License

/**
 * Get an XPath version of the given dotted path. A dotted path foo.bar.baz corresponds to the XML node
 * &lt;foo&gt;&lt;bar&gt;&lt;baz&gt; &lt;/baz&gt;&lt;/bar&gt;&lt;/foo&gt;
 * <p>//www  .ja va  2  s .  c  o  m
 * Implementation note: If needed, this could be optimized by keeping a HashMap cache of the XPaths, since they
 * don't change.
 *
 * @param path A dotted path
 * @return An XPath that matches the dotted path equivalent, using "dk:" as namespace prefix for all but the first
 * element.
 */
private XPath getXPath(String path) {
    String[] pathParts = path.split("\\.");
    StringBuilder result = new StringBuilder();
    result.append("/");
    result.append(pathParts[0]);
    for (int i = 1; i < pathParts.length; i++) {
        result.append("/dk:");
        result.append(pathParts[i]);
    }
    XPath xpath = xmlDoc.createXPath(result.toString());
    Namespace nameSpace = xmlDoc.getRootElement().getNamespace();
    Map<String, String> namespaceURIs = new HashMap<String, String>(1);
    namespaceURIs.put("dk", nameSpace.getURI());
    xpath.setNamespaceURIs(namespaceURIs);
    return xpath;
}

From source file:dkpro.similarity.algorithms.sound.dict.PLS.java

License:Apache License

/**
 *
 * @param dictionaryFilename//from   ww w .  j ava  2s  .com
 *            The filename of the PLS dictionary to read in.
 * @throws DocumentException
 */
@SuppressWarnings("unchecked")
public PLS(String dictionaryFilename) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(dictionaryFilename);
    dict = new MultiValueMap();

    // Get dictionary alphabet and language
    Element lexicon = document.getRootElement();
    alphabetId = lexicon.attributeValue("alphabet");
    dictionaryLanguage = lexicon.attributeValue("lang");

    // Extract dictionary name from metadata
    Map<String, String> namespaceMap = new HashMap<String, String>();
    namespaceMap.put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
    namespaceMap.put("dc", "http://purl.org/dc/elements/1.1/");
    XPath xpath = document.createXPath("//rdf:Description");
    xpath.setNamespaceURIs(namespaceMap);
    Node node = xpath.selectSingleNode(lexicon);
    if (node != null) {
        dictionaryId = node.valueOf("@dc:title");
    } else {
        dictionaryId = "";
    }

    for (Iterator<Element> lexemeIterator = lexicon.elementIterator("lexeme"); lexemeIterator.hasNext();) {
        Element lexeme = lexemeIterator.next();
        List<Element> graphemes = lexeme.selectNodes("grapheme");
        List<Element> phonemes = lexeme.selectNodes("phoneme");
        for (Element grapheme : graphemes) {
            for (Element phoneme : phonemes) {
                dict.put(grapheme.getText(), phoneme.getText());
            }
        }
    }
}

From source file:eu.scape_project.planning.services.taverna.parser.T2FlowParser.java

License:Apache License

/**
 * Reads the ID annotation of the t2flow.
 * //from  ww  w .  java2s  .  com
 * @return the id the workflow adheres to
 * @throws TavernaParserException
 */
public String getId() throws TavernaParserException {

    log.debug("Extracting profile ID");

    XPath xpath = DocumentHelper.createXPath("/t2f:workflow/t2f:dataflow[@role='top']/@id");

    xpath.setNamespaceURIs(T2FLOW_NAMESPACE_MAP);
    Node node = xpath.selectSingleNode(doc);
    if (node == null) {
        return null;
    }
    return node.getText();
}