Example usage for org.dom4j Node asXML

List of usage examples for org.dom4j Node asXML

Introduction

In this page you can find the example usage for org.dom4j Node asXML.

Prototype

String asXML();

Source Link

Document

asXML returns the textual XML representation of this node.

Usage

From source file:com.noterik.bart.fs.fscommand.MoveCommand.java

License:Open Source License

/**
 * Move resource specified by the input parameters.
 * /*  ww w .j a  v a 2  s .  c  o m*/
 * @param input      input parameters
 * @param uri      local directory
 * @return         status/error message
 */
private String move(Properties input, String uri) {
    String res = null;

    // get input parameters
    String source = input.getProperty("source");
    String destination = input.getProperty("destination");
    String params = input.getProperty("params");
    logger.debug("source: " + source + ", destination: " + destination + ", params: " + params);

    // determine optional parameters
    boolean override = false;
    if (params != null) {
        override = params.contains("-o");
    }

    // check input parameters
    if (source == null || destination == null) {
        return FSXMLBuilder.getErrorMessage("500", "No source or destination",
                "Please provide the SOURCE and DESTINATION input parameters",
                "http://teamelements.noterik.com/team");
    }

    // resolve uris
    String sourceUri = URIParser.resolveLocalUri(source, uri);
    if (sourceUri.lastIndexOf("/") == sourceUri.length() - 1) {
        sourceUri = sourceUri.substring(0, sourceUri.lastIndexOf("/"));
    }
    String destinationUri = URIParser.resolveLocalUri(destination, uri);
    if (destinationUri.lastIndexOf("/") == destinationUri.length() - 1) {
        destinationUri = destinationUri.substring(0, destinationUri.lastIndexOf("/"));
    }
    logger.debug("ABSOLUTE URIS -- source: " + sourceUri + ", destination: " + destinationUri);

    // check if uri is an uri of type id
    String typeSource = URIParser.getResourceTypeFromUri(sourceUri);
    String cpDest = URIParser.getCurrentUriPart(destinationUri);
    if (!URIParser.isResourceId(sourceUri)) {
        return FSXMLBuilder.getErrorMessage("500", "Invalid source specified, only id nodes permitted.",
                "Invalid source specified, only id nodes permitted.", "http://teamelements.noterik.com/team");
    }

    String docStr = null;
    String refer = null;

    // get properties of source   
    Document doc = getPropertiesOfUri(sourceUri, -1);
    logger.debug("document being created: " + doc.asXML());

    // exception for first node
    Element root = doc.getRootElement();
    Node first = root.selectSingleNode("//" + typeSource);
    refer = first.valueOf("@referid");
    List<Node> children = first.selectNodes("child::*");
    for (Iterator<Node> iter = children.iterator(); iter.hasNext();) {
        Node node = iter.next();
        docStr += node.asXML();
    }
    docStr = "<fsxml>" + docStr + "</fsxml>";
    logger.debug("document being created after first node exception: " + docStr);

    // check if dest ends with 'properties'
    String newResourceUri = null;
    if (cpDest.equals(FSXMLHelper.XML_PROPERTIES)) {
        logger.debug("putting to " + destinationUri);
        res = rHandler.handlePUT(destinationUri, docStr);
        newResourceUri = URIParser.getParentUri(destinationUri);
    } else if (URIParser.isResourceId(destinationUri)) {
        destinationUri += "/" + FSXMLHelper.XML_PROPERTIES;
        logger.debug("putting to " + destinationUri);
        res = rHandler.handlePUT(destinationUri, docStr);
        newResourceUri = URIParser.getParentUri(destinationUri);
    } else {
        logger.debug("posting to " + destinationUri);
        res = rHandler.handlePOST(destinationUri, docStr);
        try {
            if (FSXMLParser.getErrorMessageFromXml(res) == null) {
                Document respDoc = DocumentHelper.parseText(res);
                newResourceUri = respDoc.valueOf("//uri");
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    // add refer of first node
    if (refer != null && !refer.equals("")) {
        logger.debug("adding refer for first node (" + refer + ")");
        boolean ok = rHandler.saveAttributes(newResourceUri,
                "<fsxml><attributes><referid>" + refer + "</referid></attributes></fsxml>", "PUT");
        logger.debug("attributes added: " + ok);
    } else {
        logger.debug("not need for adding refer id");
    }

    // check if copy was successful and remove original
    String vError = FSXMLParser.getErrorMessageFromXml(res);
    if (vError != null) {
        logger.error("copy before moving was unsuccessful.");
    } else {
        logger.debug("copy before moving was successful.");
        FSXMLRequestHandler.instance().deleteNodeProperties(sourceUri, true);
    }

    logger.debug("response: " + res);
    return res;
}

From source file:com.noterik.bart.fs.script.FSScript.java

License:Open Source License

/**
 * Parses documents for the actionsets//  w w w.  j a  v a2 s.  com
 * @param doc
 */
private void parseActionSets(Document doc) {
    List<Node> nodeList = doc.selectNodes("//actionset");
    Node node;
    String uri;
    for (Iterator<Node> iter = nodeList.iterator(); iter.hasNext();) {
        node = iter.next();
        try {
            if (node instanceof Element) {
                Element el = (Element) node;
                uri = this.id + "/actionset/" + el.attributeValue("id", "");

                logger.debug("actionset uri: " + uri);
                addActionSet(new ActionSet(this, uri, node.asXML()));
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
}

From source file:de.innovationgate.wgpublisher.webtml.utils.TagOutputFormatter.java

License:Open Source License

public String format(Object obj) throws FormattingException {

    try {/*from   w  ww  .  j av  a  2  s .c o m*/
        if (obj == null) {
            return "";
        } else if (obj instanceof java.util.Date) {
            return this.getDateFormatter().format((java.util.Date) obj);
        } else if (obj instanceof Number) {
            return this.getNumberFormatter().format((Number) obj);
        } else if (obj instanceof Element) {
            Element element = (Element) obj;
            if (element.hasMixedContent()) {
                Iterator nodes = element.content().iterator();
                Node node;
                StringBuffer output = new StringBuffer();
                while (nodes.hasNext()) {
                    node = (Node) nodes.next();
                    output.append(node.asXML());
                }
                return (trim ? output.toString().trim() : output.toString());
            } else {
                return (trim ? element.getStringValue().trim() : element.getStringValue());
            }

        } else if (obj instanceof Node) {
            return ((Node) obj).getStringValue();
        } else {
            return (trim ? obj.toString().trim() : obj.toString());
        }
    } catch (WGException e) {
        throw new FormattingException("Exception formatting tag", e);
    }

}

From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java

License:LGPL

/**
 * Replace the img-tag and a-tag with the equivalent velocity macro. Mainly used before saving a field value to the database.
 * // w  w  w. ja va2s.  co  m
 * @throws RenderingException
 *             If any exception was thrown while replacing the tags.
 */
@SuppressWarnings("unchecked")
public static String replaceTags(final Site site, final String oldValue) throws RenderingException {
    if (StringUtils.isBlank(oldValue))
        return null;

    // 1. add a root element (to have a proper xml) and replace the ampersand
    String newValue = String.format("<dummytag>\n%s\n</dummytag>",
            StringUtils.replace(oldValue, "&", ampReplacer));
    Map<String, String> replacements = new HashMap<String, String>();

    try {
        Document dom = DocumentHelper.parseText(newValue);
        dom.setXMLEncoding(Constants.STANDARD_ENCODING);

        // 2. Collect the keys, identify the img-tags.
        List<Node> imgs = dom.selectNodes("//img", ".");
        for (Node node : imgs) {
            Element element = (Element) node;
            if (element.attributeValue("src").startsWith("/")) // only internal links have to replaced with a velocity macro
                replacements.put(node.asXML(),
                        generateVelocityImageToolCall(site, element.attributeIterator()));
        }

        // 3. Collect the keys, identify the a-tags
        List<Node> links = dom.selectNodes("//a", ".");
        for (Node node : links) {
            Element element = (Element) node;
            if (element.attributeValue("href").startsWith("/")) // only internal links have to replaced with a velocity macro
                replacements.put(element.asXML(), generateVelocityLinkToolCall(site, element));
        }

        // 4. Replace the tags with the velomacro.
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, sourceFormat);
        writer.write(dom.selectSingleNode("dummytag"));
        writer.close();
        newValue = stringWriter.toString();
        for (String stringToReplace : replacements.keySet())
            newValue = StringUtils.replace(newValue, stringToReplace, replacements.get(stringToReplace));
        newValue = StringUtils.replace(newValue, "<dummytag>", "");
        newValue = StringUtils.replace(newValue, "</dummytag>", "");

    } catch (Exception e) {
        throw new RenderingException("While preprocessing the field value: " + e.getMessage(), e);
    }

    return StringUtils.replace(newValue, ampReplacer, "&");
}

From source file:hk.hku.cecid.piazza.commons.util.PropertyTree.java

License:Open Source License

/**
 * Creates a sub-tree from this property tree.
 * /*from ww w.  ja  v  a  2s  .c o m*/
 * @param xpath the xpath for locating the subtree.
 * @return a new property tree.
 */
public PropertyTree subtree(String xpath) {
    Node node = getPropertyNode(xpath);
    if (node == null) {
        return new PropertyTree();
    }
    try {
        return new PropertyTree(new ByteArrayInputStream(node.asXML().getBytes("UTF-8")));
    } catch (Exception e) {
        return new PropertyTree();
    }
}

From source file:io.mashin.oep.model.node.action.extended.CustomActionNode.java

License:Open Source License

@Override
public void read(Node hpdlNode) {
    super.read(hpdlNode);

    Node node = XMLReadUtils.schemaVersionParentNode(hpdlNode);
    xml.setStringValue(XMLUtils.schemaVersionToXmlns(node.asXML()));
}

From source file:it.eng.spagobi.jpivotaddins.crossnavigation.SpagoBICrossNavigationConfig.java

License:Mozilla Public License

/**
 * Constructor given the CROSS_NAVIGATION node of the xml document template.
 * @param config: the CROSS_NAVIGATION node of the xml document template
 *//*  ww w. ja  v a  2s .  c  o m*/
public SpagoBICrossNavigationConfig(Node config) {
    logger.debug("Configuration:\n" + config.asXML());
    init(config);
}

From source file:net.unicon.academus.apps.content.Web.java

License:Open Source License

public DocumentData getDocument(String path, String bodyXpath, String inputTags,
        XHTMLFilterConfig filterConfig) {
    // Assertions.
    if (path == null) {
        String msg = "Argument 'path' cannot be null.";
        throw new IllegalArgumentException(msg);
    }//w  w w .j a va2s  . co  m
    if (bodyXpath == null) {
        String msg = "Argument 'bodyXpath' cannot be null.";
        throw new IllegalArgumentException(msg);
    }
    if (inputTags == null) {
        String msg = "Argument 'inputTags' cannot be null.";
        throw new IllegalArgumentException(msg);
    }

    Map attrs = new HashMap();
    StringBuffer body = new StringBuffer();
    try {
        IFile f = (IFile) fac.getResource(path);
        Reader r = new BufferedReader(new InputStreamReader(f.getInputStream()));

        String xml = null;
        if (filterConfig != null) {
            // TagSoup it!
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            InputSource is = new InputSource(r);
            XHTMLFilter.filterHTML(is, bos, filterConfig);
            xml = bos.toString();
        } else { // Straight through
            // Read everything into a StringBuffer.
            StringBuffer chars = new StringBuffer();
            char[] buff = new char[512];
            int wasRead = 0;
            do {
                chars.append(buff, 0, wasRead); // NB:  No-op the first time...
                wasRead = r.read(buff, 0, buff.length);
            } while (wasRead != -1);

            // Perform entity replacement.
            xml = replaceUncleanEntities(chars.toString());
        }

        Document doc = new SAXReader().read(new StringReader(xml));

        Iterator it = doc.selectNodes(bodyXpath).iterator();
        body.append("<body>");
        while (it.hasNext()) {
            Node n = (Node) it.next();
            body.append(n.asXML());
        }
        body.append("</body>");

        String name = null;
        String value = null;
        it = doc.selectNodes(inputTags).iterator();
        while (it.hasNext()) {
            Element n = (Element) it.next();
            name = n.attribute("name").getValue();
            value = n.attribute("value").getValue();
            attrs.put(name, value);
        }
    } catch (Throwable t) {
        String msg = "Unable to obtain the specified document body:  " + path;
        throw new RuntimeException(msg, t);
    }

    return new DocumentData(body.toString(), attrs);

}

From source file:org.apache.taverna.activities.xpath.XPathActivity.java

License:Apache License

/**
 * This method executes pre-configured instance of XPath activity.
 */// w ww.  jav  a 2s. c  om
@Override
public void executeAsynch(final Map<String, T2Reference> inputs, final AsynchronousActivityCallback callback) {
    // Don't execute service directly now, request to be run asynchronously
    callback.requestRun(new Runnable() {
        @Override
        @SuppressWarnings("unchecked")
        public void run() {

            InvocationContext context = callback.getContext();
            ReferenceService referenceService = context.getReferenceService();

            // ---- RESOLVE INPUT ----

            String xmlInput = (String) referenceService.renderIdentifier(inputs.get(IN_XML), String.class,
                    context);

            // ---- DO THE ACTUAL SERVICE INVOCATION ----

            List<Node> matchingNodes = new ArrayList<Node>();

            // only attempt to execute XPath expression if there is some input data
            if (xmlInput != null && xmlInput.length() > 0) {
                // XPath configuration is taken from the config bean
                try {
                    XPath expr = DocumentHelper.createXPath(json.get("xpathExpression").textValue());
                    Map<String, String> xpathNamespaceMap = new HashMap<>();
                    for (JsonNode namespaceMapping : json.get("xpathNamespaceMap")) {
                        xpathNamespaceMap.put(namespaceMapping.get("prefix").textValue(),
                                namespaceMapping.get("uri").textValue());
                    }
                    expr.setNamespaceURIs(xpathNamespaceMap);
                    Document doc = DocumentHelper.parseText(xmlInput);
                    matchingNodes = expr.selectNodes(doc);
                } catch (InvalidXPathException e) {
                    callback.fail("Incorrect XPath Expression -- XPath processing library "
                            + "reported the following error: " + e.getMessage(), e);

                    // make sure we don't call callback.receiveResult later
                    return;
                } catch (DocumentException e) {
                    callback.fail("XML document was not valid -- XPath processing library "
                            + "reported the following error: " + e.getMessage(), e);

                    // make sure we don't call callback.receiveResult later
                    return;
                } catch (XPathException e) {
                    callback.fail("Unexpected error has occurred while executing the XPath expression. "
                            + "-- XPath processing library reported the following error:\n" + e.getMessage(),
                            e);

                    // make sure we don't call callback.receiveResult later
                    return;
                }
            }

            // --- PREPARE OUTPUTS ---

            List<String> outNodesText = new ArrayList<String>();
            List<String> outNodesXML = new ArrayList<String>();
            Object textValue = null;
            Object xmlValue = null;

            for (Object o : matchingNodes) {
                if (o instanceof Node) {
                    Node n = (Node) o;
                    if (n.getStringValue() != null && n.getStringValue().length() > 0) {
                        outNodesText.add(n.getStringValue());
                        if (textValue == null)
                            textValue = n.getStringValue();
                    }
                    outNodesXML.add(n.asXML());
                    if (xmlValue == null)
                        xmlValue = n.asXML();
                } else {
                    outNodesText.add(o.toString());
                    if (textValue == null)
                        textValue = o.toString();
                }
            }

            // ---- REGISTER OUTPUTS ----

            Map<String, T2Reference> outputs = new HashMap<String, T2Reference>();
            if (textValue == null) {
                ErrorDocumentService errorDocService = referenceService.getErrorDocumentService();
                textValue = errorDocService.registerError("No value produced", 0, callback.getContext());
            }

            if (xmlValue == null) {
                ErrorDocumentService errorDocService = referenceService.getErrorDocumentService();
                xmlValue = errorDocService.registerError("No value produced", 0, callback.getContext());
            }

            T2Reference firstNodeAsText = referenceService.register(textValue, 0, true, context);
            outputs.put(SINGLE_VALUE_TEXT, firstNodeAsText);

            T2Reference firstNodeAsXml = referenceService.register(xmlValue, 0, true, context);
            outputs.put(SINGLE_VALUE_XML, firstNodeAsXml);

            T2Reference outNodesAsText = referenceService.register(outNodesText, 1, true, context);
            outputs.put(OUT_TEXT, outNodesAsText);

            T2Reference outNodesAsXML = referenceService.register(outNodesXML, 1, true, context);
            outputs.put(OUT_XML, outNodesAsXML);

            // return map of output data, with empty index array as this is
            // the only and final result (this index parameter is used if
            // pipelining output)
            callback.receiveResult(outputs, new int[0]);
        }
    });
}

From source file:org.danann.cernunnos.runtime.XmlGrammar.java

License:Apache License

private EntityConfig prepareEntryConfig(Entry n, Node d, String source) {

    // Assertions...
    if (n == null) {
        String msg = "Argument 'n [Entry]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }//from   w  w  w.  j a v a 2 s  . co m
    if (d == null) {
        String msg = "Argument 'd [Element]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }
    if (source == null) {
        String msg = "Argument 'source' cannot be null.";
        throw new IllegalArgumentException(msg);
    }

    // Report any use of deprecated entries...
    if (n.isDeprecated()) {
        StringBuilder msg = new StringBuilder();
        msg.append("USE OF DEPRECATED API:  A deprecated ENTRY was referenced.").append("\n\t\tEntry Name:  ")
                .append(n.getName()).append("\n\t\tDeprecated Since:  ").append(n.getDeprecation().getVersion())
                .append("\n\t\tEntry Type:  ").append(n.getType()).append("\n\t\tSource:  ").append(source)
                .append("\n");
        log.warn(msg.toString());
    }

    try {

        Formula f = n.getFormula();

        Map<Reagent, Object> mappings = new HashMap<Reagent, Object>();
        List<Reagent> needed = new ArrayList<Reagent>(f.getReagents());
        needed.removeAll(n.getMappings().keySet());
        for (Reagent r : needed) {
            Object value = r.getReagentType().evaluate(this, d, r.getXpath());

            // Report any use of deprecated reagents...
            if (r.isDeprecated() && value != null) {
                StringBuilder msg = new StringBuilder();
                msg.append("USE OF DEPRECATED API:  A value was specified for a deprecated REAGENT.")
                        .append("\n\t\tReagent Name:  ").append(r.getName()).append("\n\t\tDeprecated Since:  ")
                        .append(r.getDeprecation().getVersion()).append("\n\t\tEntry Name:  ")
                        .append(n.getName()).append("\n\t\tEntry Type:  ").append(n.getType())
                        .append("\n\t\tSource:  ").append(d.getUniquePath() + "/" + r.getXpath()).append("\n");
                log.warn(msg.toString());
            }

            if (value == null) {
                // First see if there's a default...
                if (r.hasDefault()) {
                    value = r.getDefault();
                } else {
                    String msg = "The required expression '" + r.getXpath()
                            + "' is missing from the following node:  " + d.asXML();
                    throw new RuntimeException(msg);
                }
            }
            mappings.put(r, value);
        }
        mappings.putAll(n.getMappings());

        String entryName = null;
        if (n.getType().equals(Entry.Type.TASK)) {
            entryName = "<" + n.getName() + ">";
        } else if (n.getType().equals(Entry.Type.PHRASE)) {
            entryName = "${" + n.getName() + "}";
        } else {
            throw new RuntimeException("Unsupported Entry Type:  " + n.getType());
        }

        return new SimpleEntityConfig(this, entryName, source, n.getFormula(), mappings);

    } catch (Throwable t) {
        StringBuilder msg = new StringBuilder();
        msg.append("Unable to prepare an EntityConfig based on the specified information:")
                .append("\n\t\tEntity Name:  ").append(n.getName()).append("\n\t\tSource:  ").append(source);
        throw new RuntimeException(msg.toString(), t);
    }

}