Example usage for org.dom4j.io XMLWriter XMLWriter

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

Introduction

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

Prototype

public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

From source file:edu.umd.cs.findbugs.AddMessages.java

License:Open Source License

@SuppressFBWarnings("DM_EXIT")
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("Usage: " + AddMessages.class.getName() + " <input collection> <output collection>");
        System.exit(1);//from   w ww . j  av a2 s .c  om
    }

    // Load plugins, in order to get message files
    DetectorFactoryCollection.instance();

    String inputFile = args[0];
    String outputFile = args[1];
    Project project = new Project();

    SortedBugCollection inputCollection = new SortedBugCollection(project);
    inputCollection.readXML(inputFile);

    Document document = inputCollection.toDocument();

    AddMessages addMessages = new AddMessages(inputCollection, document);
    addMessages.execute();

    XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(outputFile)),
            OutputFormat.createPrettyPrint());
    writer.write(document);
    writer.close();
}

From source file:edu.umd.cs.findbugs.ml.GenerateUIDs.java

License:Open Source License

@SuppressWarnings("unchecked")
public void execute() throws IOException, DocumentException {
    InputStream in = null;/* w  w  w.  j  ava  2 s. co  m*/
    try {
        if (inputFilename.equals("-")) {
            in = System.in;
        } else {
            in = new BufferedInputStream(new FileInputStream(inputFilename));
            if (inputFilename.endsWith(".gz"))
                in = new GZIPInputStream(in);
        }

        bugCollection.readXML(in);
        in = null;
    } finally {
        if (in != null)
            in.close();
    }
    Document document = DocumentFactory.getInstance().createDocument();
    Dom4JXMLOutput xmlOutput = new Dom4JXMLOutput(document);
    bugCollection.writeXML(xmlOutput);

    int count = 0;

    List<Element> bugInstanceList = document.selectNodes("/BugCollection/BugInstance");
    for (Element element : bugInstanceList) {
        Attribute uidAttr = element.attribute("uid");
        if (uidAttr == null) {
            element.addAttribute("uid", Integer.toString(count++));
        }
    }

    OutputStream out;
    if (outputFilename.equals("-")) {
        out = System.out;
    } else {
        out = new BufferedOutputStream(new FileOutputStream(outputFilename));
    }

    XMLWriter xmlWriter = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {
        xmlWriter.write(document);
    } finally {
        xmlWriter.close();
    }
}

From source file:edu.umd.cs.findbugs.XDocsBugReporter.java

License:Open Source License

private void writeXML(Writer out, Project project) throws IOException {
    Document document = endDocument(project);

    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    writer.write(document);/*from ww  w.  j  a v  a 2s .  c o  m*/
}

From source file:edu.upenn.cis.orchestra.workloadgenerator.GeneratorJournal.java

License:Apache License

/**
 * Write this <code>GeneratorJournal</code> out to <code>writer</code>.
 * See <code>serialize(...)</code> for the format.
 * /*w w  w . jav  a 2  s. c  om*/
 * @param writer
 *            to which to write this <code>GeneratorJournal</code>.
 * @param params
 *            run parameters, see <code>Generator</code>.
 * @throws IOException
 *             if such is thrown whilst writing this
 *             <code>GeneratorJournal</code>.
 */
public void write(Writer writer, Map<String, Object> params) throws IOException {
    XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
    xmlWriter.write(serialize(params));
    xmlWriter.flush();
    xmlWriter.close();
}

From source file:edu.upenn.cis.orchestra.workloadgenerator.MetadataXml.java

License:Apache License

@SuppressWarnings("unchecked")
public void metadataXml(List<List<List<String>>> schemas, List<Integer> peers, List<List<Object>> mappings,
        String extension) {/*from  w  w  w.j av a  2 s  .c o m*/

    Writer writer = null;
    if (null == _params.get("filename")) {
        writer = new PrintWriter(System.out);
    } else {
        try {
            if (!"".equals(extension)) {
                extension = "." + extension;
            }
            writer = new FileWriter((String) _params.get("filename") + extension + ".schema");
            // + ".schema.new");
        } catch (IOException e) {
            throw new IllegalStateException("Unable to create schema file.", e);
        }
    }

    Document document = DocumentHelper.createDocument();
    document.addComment(WorkloadGeneratorUtils.stamp() + "\n" + _params);
    Element catalog = document.addElement("catalog").addAttribute("recMode", "false").addAttribute("name",
            (String) _params.get("filename"));
    catalog.addElement("migrated").setText("true");
    for (int i = 0; i < peers.size(); i++) {
        if (null == peers.get(i)) {
            continue;
        }
        Element peer = catalog.addElement("peer").addAttribute("name", "P" + i).addAttribute("address",
                "localhost");
        int j = peers.get(i);
        Element schema = peer.addElement("schema").addAttribute("name", "S" + j);
        for (int k = 0; k < schemas.get(j).size(); k++) {
            for (String var : iovariations()) {
                Element relation = schema.addElement("relation")
                        .addAttribute("name", WorkloadGeneratorUtils.relname(i, j, k) + var)
                        .addAttribute("materialized", "true");
                if ((Double) _params.get("coverage") == 1) {
                    relation.addAttribute("noNulls", "true");
                }

                String hasLocalData;
                if (Generator.peerHasLocalData(i, (Integer) _params.get("topology"),
                        (Integer) _params.get("modlocal"), (Integer) _params.get("peers"),
                        (Integer) _params.get("fanout"))) {
                    hasLocalData = "true";
                } else {
                    hasLocalData = "false";
                }

                relation.addAttribute("hasLocalData", hasLocalData);
                relation.addElement("dbinfo").addAttribute("schema", (String) _params.get("username"))
                        .addAttribute("table", WorkloadGeneratorUtils.relname(i, j, k) + var);
                relation.addElement("field").addAttribute("name", "KID").addAttribute("type", "integer")
                        .addAttribute("key", "true");
                for (String att : schemas.get(j).get(k)) {
                    if ((Boolean) _params.get("addValueAttr") && att.equals(Relation.valueAttrName)) {
                        relation.addElement("field").addAttribute("name", att).addAttribute("type", "integer")
                                .addAttribute("key", "true");
                    } else {
                        relation.addElement("field").addAttribute("name", att).addAttribute("type",
                                universalType(att, _params));
                    }
                }
            }
        }
    }

    for (int k = 0; k < mappings.size(); k++) {
        if (null == mappings.get(k)) {
            continue;
        }
        int i = (Integer) mappings.get(k).get(0);
        int j = (Integer) mappings.get(k).get(1);

        List<String> x = (List<String>) mappings.get(k).get(2);
        List<String> source = selectAtoms(i, "KID", x, "_", schemas, peers,
                (Boolean) _params.get("addValueAttr"), true);
        // _ means don't care
        List<String> target = selectAtoms(j, "KID", x, "-", schemas, peers,
                (Boolean) _params.get("addValueAttr"), false);
        // - means null
        Element mapping = catalog.addElement("mapping").addAttribute("name", "M" + k)
                .addAttribute("materialized", "true");
        if (1 == (Integer) _params.get("bidir")) {
            mapping.addAttribute("bidirectional", "true");
        }
        Element head = mapping.addElement("head");
        for (String atom : target) {
            Element atomElem = head.addElement("atom");
            if (1 == (Integer) _params.get("bidir")) {
                atomElem.addAttribute("del", "true");
            }
            atomElem.addText(atom);
        }
        Element body = mapping.addElement("body");
        for (String atom : source) {
            Element atomElem = body.addElement("atom");
            if (1 == (Integer) _params.get("bidir")) {
                atomElem.addAttribute("del", "true");
            }
            atomElem.addText(atom);
        }
    }

    Element mappingsElem = catalog.addElement("engine").addElement("mappings");
    if (1 == (Integer) _params.get("tukwila")) {
        mappingsElem.addAttribute("type", "tukwila").addAttribute("host", "localhost").addAttribute("port",
                "7777");
    } else {
        mappingsElem.addAttribute("type", "sql")
                .addAttribute("server", (String) _params.get("mappingsServer") + "/"
                // "jdbc:db2://localhost:50000/"
                        + _params.get("dbalias"))
                .addAttribute("username", (String) _params.get("username"))
                .addAttribute("password", (String) _params.get("password"));
    }
    if (null != _params.get("updateAlias")) {
        catalog.addElement("updates")
                .addAttribute("server", "jdbc:db2://localhost:50000/" + _params.get("updateAlias"))
                .addAttribute("username", (String) _params.get("username"))
                .addAttribute("password", (String) _params.get("password"));
    }

    // Output some default (dummy) reconciliation store info
    Element store = catalog.addElement("store");
    store.addElement("update").addAttribute("type", "bdb").addAttribute("hostname", "localhost")
            .addAttribute("port", "777");
    store.addElement("state").addAttribute("type", "hash");

    // Output trust conditions saying that everyone trusts everyone
    for (int i = 0; i < peers.size(); i++) {
        if (null == peers.get(i)) {
            continue;
        }
        int j = peers.get(i);
        Element trustConditions = catalog.addElement("trustConditions").addAttribute("peer", "P" + i)
                .addAttribute("schema", "S" + j);
        for (int i2 = 0; i2 < peers.size(); i2++) {
            if (null == peers.get(i2)) {
                continue;
            }
            int j2 = peers.get(i2);
            if (i != i2) {
                for (int k2 = 0; k2 < schemas.get(j2).size(); k2++) {
                    trustConditions.addElement("trusts").addAttribute("pid", "P" + i2)
                            .addAttribute("pidType", "STRING").addAttribute("pidType", "STRING")
                            .addAttribute("priority", "5")
                            .addAttribute("relation", WorkloadGeneratorUtils.relname(i2, j2, k2));
                }
            }
        }
    }

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(document);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new IllegalStateException("Problem writing schema file.", e);
    }
}

From source file:edu.vt.middleware.ldap.dsml.AbstractDsml.java

License:Open Source License

/**
 * This will write the supplied LDAP search results to the supplied writer in
 * the form of DSML./*from  www.j a v a  2s .c  om*/
 *
 * @param  results  <code>Iterator</code> of LDAP search results
 * @param  writer  <code>Writer</code> to write to
 *
 * @throws  IOException  if an error occurs while writing
 */
public void outputDsml(final Iterator<SearchResult> results, final Writer writer) throws IOException {
    final XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
    xmlWriter.write(createDsml(results));
    writer.flush();
}

From source file:edu.vt.middleware.ldap.dsml.AbstractDsml.java

License:Open Source License

/**
 * This will write the supplied LDAP result to the supplied writer in the form
 * of DSML./*from  www  .  ja v a 2  s .c om*/
 *
 * @param  result  <code>LdapResult</code>
 * @param  writer  <code>Writer</code> to write to
 *
 * @throws  IOException  if an error occurs while writing
 */
public void outputDsml(final LdapResult result, final Writer writer) throws IOException {
    final XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
    xmlWriter.write(createDsml(result));
    writer.flush();
}

From source file:eml.studio.server.oozie.workflow.WFGraph.java

License:Open Source License

/**
 * Transform the Graph into an workflow xml definition
 * @param jobname the job name of Oozie job, can't be null
 * @return workflow xml/*from  w ww . j av  a  2s.co m*/
 */
public String toWorkflow(String jobname) {
    Namespace xmlns = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
    QName qName = QName.get("workflow-app", xmlns); // your root element's name
    Element workflow = DocumentHelper.createElement(qName);
    Document xmldoc = DocumentHelper.createDocument(workflow);
    // Create workflow root
    workflow.addAttribute("xmlns", "uri:oozie:workflow:0.4");
    // <workflow-app name='xxx'></workflow-app>
    if (jobname == null || "".equals(jobname))
        workflow.addAttribute("name", "Not specified");
    else
        workflow.addAttribute("name", jobname);

    Queue<NodeDef> que = new LinkedList<NodeDef>();
    que.add(start);

    while (!que.isEmpty()) {
        NodeDef cur = que.remove();

        cur.append2XML(workflow);

        for (NodeDef toNode : cur.getOutNodes()) {
            toNode.delInNode(cur);
            if (toNode.getInDegree() == 0)
                que.add(toNode);
        }
    }

    // Set XML document format
    OutputFormat outputFormat = OutputFormat.createPrettyPrint();
    // Set XML encoding, use the specified encoding to save the XML document to the string, it can be specified GBK or ISO8859-1
    outputFormat.setEncoding("UTF-8");
    outputFormat.setSuppressDeclaration(true); // Whether generate xml header
    outputFormat.setIndent(true); // Whether set indentation
    outputFormat.setIndent("    "); // Implement indentation with four spaces
    outputFormat.setNewlines(true); // Set whether to wrap

    try {
        // stringWriter is used to save xml document
        StringWriter stringWriter = new StringWriter();
        // xmlWriter is used to write XML document to string(tool)
        XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);

        // Write the created XML document into the string
        xmlWriter.write(xmldoc);

        xmlWriter.close();

        System.out.println(stringWriter.toString().trim());
        // Print the string, that is, the XML document
        return stringWriter.toString().trim();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:eu.delving.metadata.RecordValidator.java

License:EUPL

public String validateRecord(String recordString, List<String> problems) {
    if (!recordString.contains("<")) {
        return recordString;
    }/*from w w  w.ja  v a2 s.c o m*/
    String contextualizedRecord = String.format(context, recordString);
    StringWriter out = new StringWriter();
    try {
        long before = System.currentTimeMillis();
        InputSource source = new InputSource(new StringReader(contextualizedRecord));
        source.setEncoding("UTF-8");
        Document document = reader.read(source);
        totalParseTime += System.currentTimeMillis() - before;
        Map<Path, Counter> counters = new TreeMap<Path, Counter>();
        before = System.currentTimeMillis();
        validateDocument(document, problems, new TreeSet<String>(), counters);
        validateCardinalities(counters, problems);
        totalValidateTime += System.currentTimeMillis() - before;
        before = System.currentTimeMillis();
        XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
        writer.write(document);
        totalWriteTime += System.currentTimeMillis() - before;
    } catch (Exception e) {
        problems.add("Problem parsing: " + e.toString());
        return "Invalid";
    }
    out.getBuffer().delete(0, contextBegin);
    out.getBuffer().delete(out.getBuffer().length() - contextEnd, out.getBuffer().length());
    return out.toString();
}

From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java

License:Open Source License

/**
 * Dumps binary data to provided file//from   ww  w  . ja  va2  s . com
 * It results in an XML file with a single element: data, 
 * @param id
 * @param data
 * @param f
 * @param encoder
 * @throws IOException
 */
private static void writeBinaryData(int id, ByteStream data, File f, BASE64Encoder encoder) throws IOException {
    Document streamDoc = DocumentHelper.createDocument();
    Element d = streamDoc.addElement("data");
    d.addAttribute("id", "" + id);
    d.setText(encoder.encode(data.getData()));
    XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(f)), ProjectExporter.prettyFormat);
    writer.write(streamDoc);
    writer.flush();
    writer.close();
}