Example usage for org.dom4j Document add

List of usage examples for org.dom4j Document add

Introduction

In this page you can find the example usage for org.dom4j Document add.

Prototype

void add(Node node);

Source Link

Document

Adds the given Node or throws IllegalAddException if the given node is not of a valid type.

Usage

From source file:org.infoglue.cms.applications.contenttool.actions.SimpleContentXmlAction.java

License:Open Source License

public String doRootContent() throws Exception {
    Document doc = DocumentHelper.createDocument();
    ContentVO rootContent = ContentController.getContentController().getRootContentVO(repositoryId,
            getInfoGluePrincipal().getName(), true);
    doc.add(getPlainContentElement(rootContent));
    return out(getFormattedDocument(doc));
}

From source file:org.infoglue.cms.applications.contenttool.actions.SimpleContentXmlAction.java

License:Open Source License

public String doContentVersionHead() throws Exception {
    Document doc = DocumentHelper.createDocument();
    Element element = DocumentHelper.createElement("contentVersion");

    element.add(getContentVersionHeadElement(parent));
    element.add(DocumentHelper.createElement("value"));
    doc.add(element);
    return out(getFormattedDocument(doc));
}

From source file:org.intalio.tempo.workflow.fds.tools.SoapTools.java

License:Open Source License

public static Document unwrapMessage(Document soapEnvelope) throws InvalidInputFormatException {
    if (_log.isDebugEnabled())
        _log.debug(soapEnvelope.asXML());
    Document result = DocumentHelper.createDocument();
    Node node = null;/*from   w  ww  . j a v a 2s  .c o  m*/
    synchronized (path) {
        node = path.selectSingleNode(soapEnvelope);
    }
    result.add((Node) node.clone());
    return result;
}

From source file:org.jivesoftware.admin.AdminConsole.java

License:Open Source License

/**
 * Rebuilds the generated model.//  w  w w  .  j  a  va 2 s .c  o  m
 */
private static synchronized void rebuildModel() {
    Document doc = DocumentFactory.getInstance().createDocument();
    generatedModel = coreModel.createCopy();
    doc.add(generatedModel);

    // Add in all overrides.
    for (Element element : overrideModels.values()) {
        // See if global settings are overriden.
        Element appName = (Element) element.selectSingleNode("//adminconsole/global/appname");
        if (appName != null) {
            Element existingAppName = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/appname");
            existingAppName.setText(appName.getText());
            if (appName.attributeValue("plugin") != null) {
                existingAppName.addAttribute("plugin", appName.attributeValue("plugin"));
            }
        }
        Element appLogoImage = (Element) element.selectSingleNode("//adminconsole/global/logo-image");
        if (appLogoImage != null) {
            Element existingLogoImage = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/logo-image");
            existingLogoImage.setText(appLogoImage.getText());
            if (appLogoImage.attributeValue("plugin") != null) {
                existingLogoImage.addAttribute("plugin", appLogoImage.attributeValue("plugin"));
            }
        }
        Element appLoginImage = (Element) element.selectSingleNode("//adminconsole/global/login-image");
        if (appLoginImage != null) {
            Element existingLoginImage = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/login-image");
            existingLoginImage.setText(appLoginImage.getText());
            if (appLoginImage.attributeValue("plugin") != null) {
                existingLoginImage.addAttribute("plugin", appLoginImage.attributeValue("plugin"));
            }
        }
        Element appVersion = (Element) element.selectSingleNode("//adminconsole/global/version");
        if (appVersion != null) {
            Element existingVersion = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/version");
            if (existingVersion != null) {
                existingVersion.setText(appVersion.getText());
                if (appVersion.attributeValue("plugin") != null) {
                    existingVersion.addAttribute("plugin", appVersion.attributeValue("plugin"));
                }
            } else {
                ((Element) generatedModel.selectSingleNode("//adminconsole/global"))
                        .add(appVersion.createCopy());
            }
        }
        // Tabs
        for (Object o : element.selectNodes("//tab")) {
            Element tab = (Element) o;
            String id = tab.attributeValue("id");
            Element existingTab = getElemnetByID(id);
            // Simple case, there is no existing tab with the same id.
            if (existingTab == null) {
                // Make sure that the URL on the tab is set. If not, default to the
                // url of the first item.
                if (tab.attributeValue("url") == null) {
                    Element firstItem = (Element) tab.selectSingleNode("//item[@url]");
                    if (firstItem != null) {
                        tab.addAttribute("url", firstItem.attributeValue("url"));
                    }
                }
                generatedModel.add(tab.createCopy());
            }
            // More complex case -- a tab with the same id already exists.
            // In this case, we have to overrite only the difference between
            // the two elements.
            else {
                overrideTab(existingTab, tab);
            }
        }
    }

    // Special case: show a link to Clearspace admin console if it is integrated with
    // Openfire.
    if (ClearspaceManager.isEnabled()) {
        Element clearspace = generatedModel.addElement("tab");
        clearspace.addAttribute("id", "tab-clearspace");
        clearspace.addAttribute("name", LocaleUtils.getLocalizedString("tab.tab-clearspace"));
        clearspace.addAttribute("url", "clearspace-status.jsp");
        clearspace.addAttribute("description", LocaleUtils.getLocalizedString("tab.tab-clearspace.descr"));
        Element sidebar = clearspace.addElement("sidebar");
        sidebar.addAttribute("id", "sidebar-clearspace");
        sidebar.addAttribute("name", LocaleUtils.getLocalizedString("sidebar.sidebar-clearspace"));

        Element statusItem = sidebar.addElement("item");
        statusItem.addAttribute("id", "clearspace-status");
        statusItem.addAttribute("name", LocaleUtils.getLocalizedString("sidebar.clearspace-status"));
        statusItem.addAttribute("url", "clearspace-status.jsp");
        statusItem.addAttribute("description",
                LocaleUtils.getLocalizedString("sidebar.clearspace-status.descr"));

        Element adminItem = sidebar.addElement("item");
        adminItem.addAttribute("id", "clearspace-admin");
        adminItem.addAttribute("name", LocaleUtils.getLocalizedString("sidebar.clearspace-admin"));
        adminItem.addAttribute("url", "clearspace-admin.jsp");
        adminItem.addAttribute("description", LocaleUtils.getLocalizedString("sidebar.clearspace-admin.descr"));

    }
}

From source file:org.olat.ims.qti.render.LocalizedXSLTransformer.java

License:Apache License

/**
 * Render with a localized stylesheet. The localized stylesheet is addressed by its name with appended locale. E.g. mystyle.xsl in DE locale is addressed by
 * mystyle_de.xsl//from ww  w  .java  2 s .co  m
 * 
 * @param node The node to render
 * @param styleSheetName The stylesheet to use.
 * @return Results of XSL transformation
 */
private StringBuilder render(final Element node) {
    try {
        Document doc = node.getDocument();
        if (doc == null) {
            doc = new DOMDocument();
            doc.add(node);
        }
        final DocumentSource xmlsource = new DocumentSource(node);

        // ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final StringWriter sw = new StringWriter();
        final StreamResult result = new StreamResult(sw);
        synchronized (transformer) {// o_clusterOK by:fj transformer is per vm
            transformer.transform(xmlsource, result);
        }
        final String res = sw.toString();
        return new StringBuilder(res); // .append(result.getOutputStream());
    } catch (final Exception e) {
        throw new OLATRuntimeException(LocalizedXSLTransformer.class, "Error transforming XML.", e);
    }
}

From source file:org.opensha.commons.geo.RegionUtils.java

License:Apache License

public static void regionToKML(Region region, String filename, Color c) {
    String kmlFileName = filename + ".kml";
    Document doc = DocumentHelper.createDocument();
    Element root = new DefaultElement("kml", new Namespace("", "http://www.opengis.net/kml/2.2"));
    doc.add(root);

    Element e_doc = root.addElement("Document");
    Element e_doc_name = e_doc.addElement("name");
    e_doc_name.addText(kmlFileName);//from w  ww  .  j av a2s. com

    addBorderStyle(e_doc, c);
    addBorderVertexStyle(e_doc);
    addGridNodeStyle(e_doc, c);

    Element e_folder = e_doc.addElement("Folder");
    Element e_folder_name = e_folder.addElement("name");
    e_folder_name.addText("region");
    Element e_open = e_folder.addElement("open");
    e_open.addText("1");

    addBorder(e_folder, region);
    addPoints(e_folder, "Border Nodes", region.getBorder(), Style.BORDER_VERTEX);
    if (region.getInteriors() != null) {
        for (LocationList interior : region.getInteriors()) {
            addPoints(e_folder, "Interior Nodes", interior, Style.BORDER_VERTEX);
        }
    }

    if (region instanceof GriddedRegion) {
        addPoints(e_folder, "Grid Nodes", ((GriddedRegion) region).getNodeList(), Style.GRID_NODE);
    }

    // TODO absolutely need to create seom platform specific output directory
    // that is not in project space (e.g. desktop, Decs and Settings);

    String outDirName = "sha_kml/";
    File outDir = new File(outDirName);
    outDir.mkdirs();
    String tmpFile = outDirName + kmlFileName;

    try {
        //XMLUtils.writeDocumentToFile(tmpFile, doc);
        XMLWriter writer;
        OutputFormat format = new OutputFormat("\t", true);
        writer = new XMLWriter(new FileWriter(tmpFile), format);
        writer.write(doc);
        writer.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    //Element e = new Elem
}

From source file:org.opensha.commons.geo.RegionUtils.java

License:Apache License

public static void locListToKML(LocationList locs, String filename, Color c) {
    String kmlFileName = filename + ".kml";
    Document doc = DocumentHelper.createDocument();
    Element root = new DefaultElement("kml", new Namespace("", "http://www.opengis.net/kml/2.2"));
    doc.add(root);

    Element e_doc = root.addElement("Document");
    Element e_doc_name = e_doc.addElement("name");
    e_doc_name.addText(kmlFileName);//from  w  w w  .ja v a 2s  . c  om

    addBorderStyle(e_doc, c);
    addBorderVertexStyle(e_doc);
    addGridNodeStyle(e_doc, c);

    Element e_folder = e_doc.addElement("Folder");
    Element e_folder_name = e_folder.addElement("name");
    e_folder_name.addText("region");
    Element e_open = e_folder.addElement("open");
    e_open.addText("1");

    //      addLocationPoly(e_folder, locs);
    addLocationLine(e_folder, locs);
    addPoints(e_folder, "Border Nodes", locs, Style.BORDER_VERTEX);

    // TODO absolutely need to create seom platform specific output directory
    // that is not in project space (e.g. desktop, Decs and Settings);

    String outDirName = "sha_kml/";
    File outDir = new File(outDirName);
    outDir.mkdirs();
    String tmpFile = outDirName + kmlFileName;

    try {
        //XMLUtils.writeDocumentToFile(tmpFile, doc);
        XMLWriter writer;
        OutputFormat format = new OutputFormat("\t", true);
        writer = new XMLWriter(new FileWriter(tmpFile), format);
        writer.write(doc);
        writer.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    //Element e = new Elem
}

From source file:org.orbeon.oxf.processor.ProcessorUtils.java

License:Open Source License

public static Document createDocumentFromEmbeddedOrHref(Element element, String urlString) {
    final Document result;
    if (urlString == null) {
        // Case of embedded XML
        final Element originalElement = (Element) ((Element) element).elementIterator().next();
        if (originalElement == null)
            throw new OXFException("Content for element '" + element.getName() + "' is mandatory");
        Element copiedElement = Dom4jUtils.copyElementCopyParentNamespaces(originalElement);
        result = new NonLazyUserDataDocument();
        result.add(copiedElement);
    } else {/*from   www.j a v a  2  s  . c om*/
        // External URI
        final LocationData locationData = (LocationData) element.getData();
        result = createDocumentFromURL(urlString, locationData);
    }
    return result;
}

From source file:org.orbeon.oxf.processor.SignatureVerifierProcessor.java

License:Open Source License

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) {
        public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
            try {
                final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY);
                final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key");
                final byte[] pubBytes = Base64.decode(pubString);
                final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                final Signature dsa = Signature.getInstance("SHA1withDSA");
                dsa.initVerify(pubKey);//from  w w w .j av  a 2  s .  c  o  m

                final Document data = readInputAsDOM4J(context, INPUT_DATA);
                final Node sigDataNode = data.selectSingleNode("/signed-data/data/*");
                final String sig = StringUtils
                        .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature"));

                sigDataNode.detach();
                final Document sigData = new NonLazyUserDataDocument();
                sigData.add(sigDataNode);

                dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8"));

                // Verify signature and throw in case of failure
                try {
                    if (!dsa.verify(Base64.decode(sig)))
                        throw new OXFException("Signature verification failed");
                } catch (SignatureException e) {
                    throw e;
                } catch (Exception e) {
                    // A number of things can fail above, including Base64 decoding
                    // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception
                    throw new SignatureException("Signature verification failed");
                }

                // Signature verification passed
                final LocationSAXWriter saw = new LocationSAXWriter();
                saw.setContentHandler(xmlReceiver);
                saw.write(sigData);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java

License:Open Source License

/**
 * Evaluate a sequence a statements, and insert the result of the
 * evaluation the given parent node at the given position.
 *///from w w w  . j  ava 2 s.c  o m
public static void insert(LocationData locationData, Node parent, int position, Object toInsert) {
    List nodesToInsert = xpathObjectToDOM4JList(locationData, toInsert);
    if (parent instanceof Element)
        Collections.reverse(nodesToInsert);
    for (Iterator j = nodesToInsert.iterator(); j.hasNext();) {
        Object object = j.next();
        Node node = object instanceof String || object instanceof Number
                ? Dom4jUtils.createText(object.toString())
                : (Node) ((Node) object).clone();
        if (parent instanceof Element) {
            Element element = (Element) parent;
            if (node instanceof Attribute) {
                element.attributes().add(node);
            } else {
                element.content().add(position, node);
            }
        } else if (parent instanceof Attribute) {
            Attribute attribute = (Attribute) parent;
            attribute.setValue(attribute.getValue() + node.getText());
        } else if (parent instanceof Document) {
            // Update a document element
            final Document document = (Document) parent;
            if (node instanceof Element) {
                if (document.getRootElement() != null)
                    throw new ValidationException("Document already has a root element", locationData);
                document.setRootElement((Element) node);
            } else if (node instanceof ProcessingInstruction) {
                document.add(node);
            } else {
                throw new ValidationException(
                        "Only an element or processing instruction can be at the root of a document",
                        locationData);
            }

        } else {
            throw new ValidationException("Cannot insert into a node of type '" + parent.getClass() + "'",
                    locationData);
        }
    }
}