Example usage for org.dom4j.io OutputFormat OutputFormat

List of usage examples for org.dom4j.io OutputFormat OutputFormat

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat OutputFormat.

Prototype

public OutputFormat(String indent, boolean newlines) 

Source Link

Document

Creates an OutputFormat with the given indent added with optional newlines between the Elements.

Usage

From source file:org.hibernate.envers.boot.internal.AdditionalJaxbMappingProducerImpl.java

License:LGPL

private static void dump(Document document) {
    if (!log.isTraceEnabled()) {
        return;/*from w ww. ja v  a2  s . co  m*/
    }

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Writer w = new PrintWriter(baos);

    try {
        final XMLWriter xw = new XMLWriter(w, new OutputFormat(" ", true));
        xw.write(document);
        w.flush();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    log.tracef("Envers-generate entity mapping -----------------------------\n%s", baos.toString());
    log.trace("------------------------------------------------------------");
}

From source file:org.hibernate.envers.configuration.EntitiesConfigurator.java

License:Open Source License

@SuppressWarnings({ "UnusedDeclaration" })
private void writeDocument(Document e) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer w = new PrintWriter(baos);

    try {//from   ww  w .j  a  v  a2s  .co m
        XMLWriter xw = new XMLWriter(w, new OutputFormat(" ", true));
        xw.write(e);
        w.flush();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    System.out.println("-----------");
    System.out.println(baos.toString());
    System.out.println("-----------");
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

License:Apache License

private org.dom4j.Element getExportLayoutDom(IPerson person, IUserProfile profile) {
    if (!this.layoutExistsForUser(person)) {
        return null;
    }/*from  w  w w.  ja v a2  s  . c  om*/

    org.dom4j.Document layoutDoc = null;
    try {
        final Document layoutDom = this._safeGetUserLayout(person, profile);
        person.setAttribute(Constants.PLF, layoutDom);
        layoutDoc = this.reader.get().read(layoutDom);
    } catch (final Throwable t) {
        final String msg = "Unable to obtain layout & profile for user '" + person.getUserName()
                + "', profileId " + profile.getProfileId();
        throw new RuntimeException(msg, t);
    }

    if (logger.isDebugEnabled()) {
        // Write out this version of the layout to the log for dev purposes...
        final StringWriter str = new StringWriter();
        final XMLWriter xml = new XMLWriter(str, new OutputFormat("  ", true));
        try {
            xml.write(layoutDoc);
            xml.close();
        } catch (final Throwable t) {
            throw new RuntimeException(
                    "Failed to write the layout for user '" + person.getUserName() + "' to the DEBUG log", t);
        }
        logger.debug("Layout for user: {}\n{}", person.getUserName(), str.getBuffer().toString());
    }

    /*
     * Attempt to detect a corrupted layout; return null in such cases
     */

    if (isLayoutCorrupt(layoutDoc)) {
        logger.warn("Layout for user: {} is corrupt; layout structures will not be exported.",
                person.getUserName());
        return null;
    }

    /*
     * Clean up the DOM for export.
     */

    // (1) Add structure & theme attributes...
    final int structureStylesheetId = profile.getStructureStylesheetId();
    this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, structureStylesheetId, "structure");

    final int themeStylesheetId = profile.getThemeStylesheetId();
    this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, themeStylesheetId, "theme");

    // (2) Remove locale info...
    final Iterator<org.dom4j.Attribute> locale = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@locale").iterator();
    while (locale.hasNext()) {
        final org.dom4j.Attribute loc = locale.next();
        loc.getParent().remove(loc);
    }

    // (3) Scrub unnecessary channel information...
    for (final Iterator<org.dom4j.Element> orphanedChannels = (Iterator<org.dom4j.Element>) layoutDoc
            .selectNodes("//channel[@fname = '']").iterator(); orphanedChannels.hasNext();) {
        // These elements represent UP_LAYOUT_STRUCT rows where the 
        // CHAN_ID field was not recognized by ChannelRegistryStore;  
        // best thing to do is remove the elements...
        final org.dom4j.Element ch = orphanedChannels.next();
        ch.getParent().remove(ch);
    }
    final List<String> channelAttributeWhitelist = Arrays.asList(new String[] { "fname", "unremovable",
            "hidden", "immutable", "ID", "dlm:plfID", "dlm:moveAllowed", "dlm:deleteAllowed" });
    final Iterator<org.dom4j.Element> channels = (Iterator<org.dom4j.Element>) layoutDoc
            .selectNodes("//channel").iterator();
    while (channels.hasNext()) {
        final org.dom4j.Element oldCh = channels.next();
        final org.dom4j.Element parent = oldCh.getParent();
        final org.dom4j.Element newCh = this.fac.createElement("channel");
        for (final String aName : channelAttributeWhitelist) {
            final org.dom4j.Attribute a = (org.dom4j.Attribute) oldCh.selectSingleNode("@" + aName);
            if (a != null) {
                newCh.addAttribute(a.getQName(), a.getValue());
            }
        }
        parent.elements().add(parent.elements().indexOf(oldCh), newCh);
        parent.remove(oldCh);
    }

    // (4) Convert internal DLM noderefs to external form (pathrefs)...
    for (final Iterator<org.dom4j.Attribute> origins = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@dlm:origin").iterator(); origins.hasNext();) {
        final org.dom4j.Attribute org = origins.next();
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), org.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            org.setValue(dlmPathref.toString());
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        org.getUniquePath(), person.getAttribute(IPerson.USERNAME), org.getValue());
            }
        }
    }
    for (final Iterator<org.dom4j.Attribute> it = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@dlm:target").iterator(); it.hasNext();) {
        final org.dom4j.Attribute target = it.next();
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), target.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            target.setValue(dlmPathref.toString());
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        target.getUniquePath(), person.getAttribute(IPerson.USERNAME), target.getValue());
            }
        }
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) {
        final org.dom4j.Attribute n = names.next();
        if (n.getValue() == null || n.getValue().trim().length() == 0) {
            // Outer <dlm:positionSet> elements don't seem to use the name 
            // attribute, though their childern do.  Just skip these so we 
            // don't send a false WARNING.
            continue;
        }
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), n.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            n.setValue(dlmPathref.toString());
            // These *may* have fnames...
            if (dlmPathref.getPortletFname() != null) {
                n.getParent().addAttribute("fname", dlmPathref.getPortletFname());
            }
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        n.getUniquePath(), person.getAttribute(IPerson.USERNAME), n.getValue());
            }
        }
    }

    // Remove synthetic Ids, but from non-fragment owners only...
    if (!this.isFragmentOwner(person)) {

        /*
         * In the case of fragment owners, the original database Ids allow 
         * us keep (not break) the associations that subscribers have with 
         * nodes on the fragment layout.
         */

        // (5) Remove dlm:plfID...
        for (final Iterator<org.dom4j.Attribute> plfid = (Iterator<org.dom4j.Attribute>) layoutDoc
                .selectNodes("//@dlm:plfID").iterator(); plfid.hasNext();) {
            final org.dom4j.Attribute plf = plfid.next();
            plf.getParent().remove(plf);
        }

        // (6) Remove database Ids...
        for (final Iterator<org.dom4j.Attribute> ids = (Iterator<org.dom4j.Attribute>) layoutDoc
                .selectNodes("//@ID").iterator(); ids.hasNext();) {
            final org.dom4j.Attribute a = ids.next();
            a.getParent().remove(a);
        }
    }

    return layoutDoc.getRootElement();
}

From source file:org.jboss.tools.jbpm.convert.bpmnto.util.DomXmlWriter.java

License:Open Source License

public static String toString(Document document) throws IOException {
    OutputFormat outputFormat = new OutputFormat("  ", true);
    Writer writer = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(writer, outputFormat);
    xmlWriter.write(document);/*from   w w  w .ja  v a2  s.co m*/
    xmlWriter.flush();
    writer.flush();
    return writer.toString();
}

From source file:org.jbpm.jpdl.xml.JpdlXmlWriter.java

License:Open Source License

public void write(ProcessDefinition processDefinition) {
    problems = new ArrayList();
    if (processDefinition == null)
        throw new JbpmException("processDefinition is null");
    try {//from  w  ww.j a  va  2  s . c o  m
        // collect the actions of the process definition
        // we will remove each named event action and the remaining ones will be written 
        // on the process definition.
        // create a dom4j dom-tree for the process definition
        Document document = createDomTree(processDefinition);

        // write the dom-tree to the given writer
        OutputFormat outputFormat = new OutputFormat("  ", true);
        // OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, outputFormat);
        xmlWriter.write(document);
        xmlWriter.flush();
        writer.flush();
    } catch (IOException e) {
        addProblem("couldn't write process definition xml: " + e.getMessage());
    }

    if (problems.size() > 0) {
        throw new JpdlException(problems);
    }
}

From source file:org.jogre.server.ServerProperties.java

License:Open Source License

/**
 * Save the server properties to a file.
 *///from   www  .j  a v a2s.  c  o m
public void saveXMLFile() {
    try {
        OutputFormat format = new OutputFormat("    ", true);
        XMLWriter writer = new XMLWriter(new FileWriter(DEFAULT_FILENAME), format);
        writer.write(doc);
        writer.close();
    } catch (IOException ioe) {
        ioe.printStackTrace(); // FIXME - proper logging
    }
}

From source file:org.makumba.commons.tags.MakumbaTLDGenerator.java

License:Open Source License

/**
 * Generates a TLD based on its makumba skeleton
 * /*from  w w w  .  j a v a 2 s.c  o m*/
 * @param sourcePath
 *            path to the documented source XML file to parse
 * @param jspTldPath
 *            path to the output TLD file
 * @param documentationPath
 *            path to the makumba documentation pages (JSPwiki)
 */
public void generateTLD(final String sourcePath, final String jspTldPath, final String jspTldPathHibernate,
        final String documentationPath) {

    HashMap<String, Element> processedTags = new HashMap<String, Element>();

    // read the documented XML files
    SAXReader saxReader = new SAXReader();
    Document document = null;
    try {
        document = saxReader.read(sourcePath);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    final String errorMsg = "Error processing '" + sourcePath + "': ";

    Element root = document.getRootElement();
    for (Element tag : getElementList(root)) {
        if (tag.getName().equals("description")) {
            // update makumba version place-holder
            tag.setText(tag.getText().replace("@version@", version.getVersion()));
        }
        if (StringUtils.equalsAny(tag.getName(), "tag", "function")) {
            boolean isTag = tag.getName().equals("tag");
            String tagName = tag.element(getTagName()).getText();

            for (Element tagContent : getElementList(tag)) {

                if (tagContent.getName().equals("attribute")) {
                    if (tagContent.attributeValue("name") != null
                            && tagContent.attributeValue("specifiedIn") != null) { // have a referring attribute
                        replaceReferencedAttribute(processedTags, errorMsg, tagName, tagContent);
                    } else { // normal attribute
                        for (Element attributeContent : getElementList(tagContent)) {
                            String inheritedFrom = null;
                            if (attributeContent.getName().equals("inheritedFrom")) {
                                inheritedFrom = attributeContent.getText();
                            }

                            // remove all the tags for makumba documentation generation inside <attribute> elements
                            if (StringUtils.equalsAny(attributeContent.getName(), "comments", "deprecated",
                                    "descriptionPage", "commentsPage", "inheritedFrom")) {
                                attributeContent.getParent().remove(attributeContent);
                            }

                            // generate description and comment pages for an attribute
                            if (attributeContent.getName().equals("description")) {

                                // insert the description
                                String descriptionFileName = "";
                                if (inheritedFrom != null) {
                                    descriptionFileName += org.apache.commons.lang.StringUtils
                                            .capitalize(inheritedFrom) + (isTag ? "Tag" : "Function");
                                } else {
                                    descriptionFileName += org.apache.commons.lang.StringUtils
                                            .capitalize(tagName) + (isTag ? "Tag" : "Function");
                                }
                                descriptionFileName += "Attribute" + org.apache.commons.lang.StringUtils
                                        .capitalize(tagContent.elementText("name")) + "AttributeDescription";

                                File d = new File(
                                        documentationPath + File.separator + descriptionFileName + ".txt");
                                if (!d.exists()) {
                                    System.err.println("Could not find attribute description file " + d);
                                }

                                String desc = "";

                                if (d.exists()) {
                                    try {
                                        desc = readFileAsString(d.getAbsolutePath());
                                    } catch (IOException e) {
                                        System.err.println("Could not read attribute description file " + d);
                                    }
                                }
                                attributeContent.setText(desc.trim());
                            }
                        }
                    }
                }

                // remove the invalid tags
                if (StringUtils.equalsAny(tagContent.getName(), "see", "example")) {
                    tagContent.getParent().remove(tagContent);
                }

                // if we have a descriptionPage instead of a raw text, use the content of that page
                if (tagContent.getName().equals("descriptionPage")) {
                    String descriptionFileName = org.apache.commons.lang.StringUtils.capitalize(tagName)
                            + (isTag ? "Tag" : "Function") + "Description";
                    String desc = "";
                    try {
                        desc = readFileAsString(
                                documentationPath + File.separator + descriptionFileName + ".txt");
                    } catch (IOException e1) {
                        System.err.println("Could not read tag description file " + documentationPath
                                + File.separator + descriptionFileName + ".txt");
                    }
                    Element d = null;
                    if ((d = tagContent.getParent().element("description")) == null) {
                        d = tagContent.getParent().addElement("description");
                    }
                    d.setText(desc.trim());
                    tagContent.getParent().remove(tagContent);
                }
            }
            processedTags.put(tagName, tag);
        }
    }

    // generate the clean TLD
    System.out.println("Writing general Makumba TLD at path " + jspTldPath);
    try {
        File path = new File(jspTldPath);
        path.getParentFile().mkdirs();
        XMLWriter output = new XMLWriter(new FileWriter(path), new OutputFormat("", false));
        output.write(document);
        output.close();
    } catch (IOException e1) {
        System.out.println(e1.getMessage());
    }

    // generate hibernate TLD

    Document hibernateTLD = document;
    hibernateTLD.getRootElement().element("uri").setText(HIBERNATE_TLD_URI);

    System.out.println("Writing hibernate Makumba TLD at path " + jspTldPathHibernate);
    try {
        XMLWriter output = new XMLWriter(new FileWriter(new File(jspTldPathHibernate)),
                new OutputFormat("", false));
        output.write(document);
        output.close();
    } catch (IOException e1) {
        System.out.println(e1.getMessage());
    }

    // here we could now also generate the list-hql, forms-hql, ... TLDs
    // this would be easily done by defining an array of tags that should be in each of them, iterate over all the
    // tags in the doc
    // and take only the right ones
    // and then write this with the right URL

}

From source file:org.makumba.devel.MDDRelationVisualiser.java

License:Open Source License

public static void main(String[] args) throws IOException {
    DataDefinitionProvider ddp = DataDefinitionProvider.getInstance();

    Vector<String> mdds;
    if (args.length > 0) {
        mdds = ddp.getDataDefinitionsInAbsoluteLocation(args[0]);
    } else {//from   ww  w .j a v  a  2 s.  c om
        mdds = ddp.getDataDefinitionsInDefaultLocations();
    }
    File tmp = new File("/tmp/graph.ml"); // File.createTempFile("graph_", ".ml");

    Document d = DocumentHelper.createDocument();
    Element graphml_tag = d.addElement("graphml");

    Element root = graphml_tag.addElement("graph");
    root.addAttribute("edgedefault", "directed");

    Namespace ns = Namespace.get("", "http://graphml.graphdrawing.org/xmlns");
    d.getRootElement().add(ns);

    Element incoming = root.addElement("key");
    incoming.addAttribute("id", "name");
    incoming.addAttribute("for", "node");
    incoming.addAttribute("attr.name", "name");
    incoming.addAttribute("attr.type", "string");

    for (String mdd : mdds) {
        try {
            processMDD(root, ddp.getDataDefinition(mdd));
        } catch (DataDefinitionParseError e) {
            System.out.println("Skipping broken MDD " + mdd);
        }
    }

    XMLWriter serializer = new XMLWriter(new FileWriter(tmp), new OutputFormat("", false));
    serializer.write(d);
    serializer.close();

    Graph graph = null;
    try {
        graph = new GraphMLReader().readGraph(tmp.getAbsoluteFile());
    } catch (DataIOException e) {
        e.printStackTrace();
        System.err.println("Error loading graph. Exiting...");
        System.exit(1);
    }

    int minEdges = 3;

    for (int i = graph.getNodeCount() - 1; i >= 0; i--) {
        Node node = graph.getNode(i);
        System.out.println(node + ", " + node.getOutDegree());
        if (node.getOutDegree() < minEdges) {
            graph.removeNode(node);
        }
    }

    // add the graph to the visualization as the data group "graph"
    // nodes and edges are accessible as "graph.nodes" and "graph.edges"
    Visualization m_vis = new Visualization();
    m_vis.add("graph", graph);
    m_vis.setInteractive(treeNodes, null, false);

    // draw the "name" label for NodeItems
    LabelRenderer m_nodeRenderer = new LabelRenderer("name");
    m_nodeRenderer.setRenderType(AbstractShapeRenderer.RENDER_TYPE_FILL);
    m_nodeRenderer.setHorizontalAlignment(Constants.CENTER);
    m_nodeRenderer.setRoundedCorner(8, 8); // round the corners

    EdgeRenderer m_edgeRenderer = new EdgeRenderer();
    m_edgeRenderer.setDefaultLineWidth(1.0);

    // create a new default renderer factory
    // return our name label renderer as the default for all non-EdgeItems
    // includes straight line edges for EdgeItems by default
    final DefaultRendererFactory rf = new DefaultRendererFactory(m_nodeRenderer);
    rf.add(new InGroupPredicate(treeEdges), m_edgeRenderer);
    m_vis.setRendererFactory(rf);

    // use black for node text
    ColorAction text = new ColorAction(treeNodes, VisualItem.TEXTCOLOR, ColorLib.gray(0));
    // use light grey for edges
    ColorAction edges = new ColorAction(treeEdges, VisualItem.STROKECOLOR, ColorLib.gray(200));

    // create an action list containing all color assignments
    ActionList color = new ActionList();
    // color.add(fill);
    color.add(text);
    color.add(edges);

    // create the tree layout action
    Layout graphLayout = new SquarifiedTreeMapLayout("graph");
    m_vis.putAction("circleLayout", graphLayout);

    // create an action list with an animated layout
    // the INFINITY parameter tells the action list to run indefinitely
    ActionList layout = new ActionList(Activity.DEFAULT_STEP_TIME * 500);
    Layout l = new ForceDirectedLayout("graph");
    layout.add(l);
    layout.add(new RepaintAction());

    // add the actions to the visualization
    m_vis.putAction("color", color);
    m_vis.putAction("layout", layout);

    // create a new Display that pull from our Visualization
    Display display = new Display(m_vis);
    display.setSize(1200, 800); // set display size
    display.addControlListener(new DragControl()); // drag items around
    display.addControlListener(new PanControl()); // pan with background left-drag
    display.addControlListener(new ZoomControl()); // zoom with vertical right-drag

    // create a new window to hold the visualization
    JFrame frame = new JFrame("MDD analysis");
    // ensure application exits when window is closed
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(display);
    frame.pack(); // layout components in window
    frame.setVisible(true); // show the window

    m_vis.run("color"); // assign the colors
    m_vis.run("layout"); // start up the animated layout

}

From source file:org.olat.ims.qti.process.FilePersister.java

License:Apache License

/**
 * Persist results for this user/aiid as an XML document. dlPointer is aiid in this case.
 * /*from w ww  .j a v a2 s  . c  o m*/
 * @param doc
 * @param type
 * @param info
 */
public static void createResultsReporting(final Document doc, final Identity subj, final String type,
        final long aiid) {
    final File fUserdataRoot = new File(WebappHelper.getUserDataRoot());
    final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type;
    final File fReportingDir = new File(fUserdataRoot, path);
    try {
        fReportingDir.mkdirs();
        final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml"));
        final Element element = doc.getRootElement();
        final XMLWriter xw = new XMLWriter(os, new OutputFormat("  ", true));
        xw.write(element);
        // closing steams
        xw.close();
        os.close();
    } catch (final Exception e) {
        throw new OLATRuntimeException(FilePersister.class, "Error persisting results reporting for subject: '"
                + subj.getName() + "'; assessment id: '" + aiid + "'", e);
    }
}

From source file:org.olat.ims.qti.qpool.QTIExportProcessor.java

License:Apache License

/**
 * <li>List all items//from   ww w .j av  a 2 s.c om
 * <li>Rewrite path
 * <li>Assemble qti.xml
 * <li>Write files at new path
 * @param fullItems
 * @param zout
 */
public void assembleTest(List<QuestionItemFull> fullItems, ZipOutputStream zout) {
    ItemsAndMaterials itemAndMaterials = new ItemsAndMaterials();
    for (QuestionItemFull fullItem : fullItems) {
        collectMaterials(fullItem, itemAndMaterials);
    }

    try {
        byte[] buffer = new byte[FileUtils.BSIZE];

        //write qti.xml
        Element sectionEl = createSectionBasedAssessment("Assessment");
        for (Element itemEl : itemAndMaterials.getItemEls()) {
            //generate new ident per item
            String ident = getAttributeValue(itemEl, "ident");
            String exportIdent = QTIEditHelper.generateNewIdent(ident);
            itemEl.addAttribute("ident", exportIdent);
            sectionEl.add(itemEl);
        }
        zout.putNextEntry(new ZipEntry("qti.xml"));
        XMLWriter xw = new XMLWriter(zout, new OutputFormat("  ", true));
        xw.write(sectionEl.getDocument());
        zout.closeEntry();

        //write materials
        for (ItemMaterial material : itemAndMaterials.getMaterials()) {
            String exportPath = material.getExportUri();
            zout.putNextEntry(new ZipEntry(exportPath));
            InputStream in = material.getLeaf().getInputStream();
            int c;
            while ((c = in.read(buffer, 0, buffer.length)) != -1) {
                zout.write(buffer, 0, c);
            }
            IOUtils.closeQuietly(in);
            zout.closeEntry();
        }
    } catch (IOException e) {
        log.error("", e);
    }
}