Example usage for org.dom4j.io XMLWriter close

List of usage examples for org.dom4j.io XMLWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying Writer

Usage

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

License:Open Source License

/**
 * Generates a TLD based on its makumba skeleton
 * // w ww .ja  v  a  2 s.c  om
 * @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  w  w  w  . j ava 2s. com*/
        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.mitre.ace2004.callisto.ExportAPF5_0_2.java

License:Open Source License

/**
 *//*from   ww w .  ja  v a2 s . co  m*/
private boolean writeAPF(Document xmlDoc, URI uri) throws IOException {
    File apfFile = new File(uri);
    File backFile = new File(apfFile.toString() + "~");
    File tmpFile = ATLASHelper.createTempFile(uri);
    if (DEBUG > 0)
        System.err.println("Export APF File: " + apfFile + "\n       TMP File: " + tmpFile);

    FileOutputStream fileOut = new FileOutputStream(tmpFile);
    // always output APF as UTF-8, though the source file may be something else
    Writer writer = new OutputStreamWriter(fileOut, "UTF-8");
    writer = new BufferedWriter(writer);

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter xmlWriter = new XMLWriter(writer, format);
    xmlWriter.write(xmlDoc);
    xmlWriter.close();

    if (apfFile.exists()) {
        if (backFile.exists())
            backFile.delete();
        apfFile.renameTo(backFile);
    }

    return tmpFile.renameTo(apfFile);
}

From source file:org.mitre.jawb.io.ATLASHelper.java

License:Open Source License

public static void dump(Document doc, OutputStream out) throws IOException {

    // Pretty print the document to System.out
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("US-ASCII");
    Writer writer = new OutputStreamWriter(out, "US-ASCII");
    XMLWriter xmlWriter = new XMLWriter(writer, format);
    xmlWriter.write(doc);//from   w  w  w  . j  av  a2s  .c  om
    xmlWriter.close();
}

From source file:org.modelibra.persistency.xml.XmlEntities.java

License:Apache License

/**
 * Saves a document to the XML data file using the given encoding.
 * /*from   www  . j  ava2s .  c  om*/
 * @param document
 *            XML document
 * @param dataFilePath
 *            XML data file path
 * @param encoding
 *            text encoding
 */
private void save(Document document, String dataFilePath, String encoding) {
    XMLWriter writer;
    try {
        writer = new XMLWriter(new FileOutputStream(dataFilePath), new OutputFormat("  ", true, encoding));
    } catch (FileNotFoundException e) {
        String message = "=== Problem with XmlEntities.save(Document, String, String) === " + e.getMessage();
        throw new PersistencyRuntimeException(message, e);
    } catch (UnsupportedEncodingException e) {
        String message = "=== Problem with XmlEntities.save(Document, String, String) === " + e.getMessage();
        throw new PersistencyRuntimeException(message, e);
    }
    try {
        writer.write(document);
        writer.close();
    } catch (IOException e) {
        String message = "=== Problem with XmlEntities.save(Document, String, String) === " + e.getMessage();
        throw new PersistencyRuntimeException(message, e);
    }
}

From source file:org.mule.module.xml.transformer.XmlPrettyPrinter.java

License:Open Source License

@Override
protected Object doTransform(Object src, String outputEncoding) throws TransformerException {
    try {//from  w w  w.j  a v a2 s. c o m
        Document document = XMLUtils.toDocument(src, muleContext);
        if (document != null) {
            ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
            XMLWriter writer = new XMLWriter(resultStream, this.getOutputFormat());
            writer.write(document);
            writer.close();
            return resultStream.toString(outputEncoding);
        } else {
            throw new DocumentException("Payload is not valid XML");
        }
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:org.napile.asm.io.xml.out.AsmXmlFileWriter.java

License:Apache License

@NotNull
@Override//from   w  ww  .j av  a  2s .c o m
protected File getResult() {
    File file = null;
    List<FqName> paths = fqName.path();
    for (int i = 0; i < paths.size(); i++) {
        FqName path = paths.get(i);
        file = new File(outputDir, path.getFqName().replace(".", File.separator));

        // last segment is original FqName
        if (i != paths.size() - 1)
            file.mkdirs();
    }

    assert file != null;

    file = new File(file.getAbsolutePath() + DOT_EXTENSION);

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndent("\t");
    try {
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        writer.write(document);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}

From source file:org.napile.asm.io.xml.out.AsmXmlTextWriter.java

License:Apache License

@NotNull
@Override//from w w  w  . j av a  2 s  .co  m
protected String getResult() {
    StringWriter stringWriter = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndent("\t");
    try {
        XMLWriter writer = new XMLWriter(stringWriter, format);
        writer.write(document);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringWriter.toString();
}

From source file:org.neo4j.neoclipse.util.XMLUtils.java

License:Apache License

public static void save(Element pRoot, File pFile) {
    try {/*from   w  w  w  . j  av  a 2  s  .co m*/
        pFile.getParentFile().mkdirs();
        FileOutputStream fileOutputStream = new FileOutputStream(pFile);
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint());
        xmlWriter.startDocument();
        xmlWriter.write(pRoot);
        xmlWriter.endDocument();
        xmlWriter.flush();
        xmlWriter.close();
    } catch (Exception e) {
        ErrorMessage.showDialog("Couldn't save: " + pFile.getAbsolutePath(), e);
    }

}

From source file:org.nuclos.client.datasource.querybuilder.QueryBuilderEditor.java

License:Open Source License

/**
 * @return/*from   w ww  .j a va 2  s  .c  o  m*/
 * @throws NuclosBusinessException
 */
public String getXML(DatasourceEntityOptions eOptions) throws CommonBusinessException {
    String result = "";
    try {
        final Document doc = DocumentHelper.createDocument();
        doc.addDocType(QueryBuilderConstants.DOCTYPE, null, QueryBuilderConstants.SYSTEMID);

        Element root = doc.addElement(QueryBuilderConstants.DOCTYPE);
        Element header = root.addElement(QueryBuilderConstants.TAG_HEADER);
        Element tables = root.addElement(QueryBuilderConstants.TAG_TABLES);
        Element connectors = root.addElement(QueryBuilderConstants.TAG_CONNECTORS);
        Element columns = root.addElement(QueryBuilderConstants.TAG_COLUMNS);
        Element parameters = root.addElement(QueryBuilderConstants.TAG_PARAMETERS);
        Element sql = root.addElement(QueryBuilderConstants.TAG_SQL);

        serializeHeader(header);
        serializeTables(tables);
        serializeConnectors(connectors);
        serializeColumns(columns);
        serializeParameters(parameters);

        if (eOptions != null) {
            Element entityoptions = root.addElement(QueryBuilderConstants.TAG_ENTITYOPTIONS);
            entityoptions.addAttribute("dynamic", eOptions.isDynamic() ? "yes" : "no");
        }

        final boolean bModelUsed = parent.isModelUsed();
        sql.addAttribute("isModelUsed", bModelUsed ? "true" : "false");
        if (!bModelUsed) {
            sql.addCDATA(StringUtils.emptyIfNull(parent.getSql()));
        }

        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        //format.setEncoding("ISO-8859-1");
        final StringWriter sw = new StringWriter();
        final XMLWriter xmlw = new XMLWriter(sw, format);
        xmlw.write(doc);
        xmlw.close();
        result = sw.toString();
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
    return result;
}