Example usage for org.dom4j.io OutputFormat createPrettyPrint

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

Introduction

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

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

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 ww.j a va2s.c om*/

    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./*  ww w. ja  v a2  s  .  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.//  w w  w.j av a2 s. c o  m
 *
 * @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 ww w.  j  av a 2 s . c  om*/
 */
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:eml.studio.server.oozie.workflow.WFGraph.java

License:Open Source License

public static void main(String args[]) {

    Namespace rootNs = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
    QName rootQName = QName.get("workflow-app", rootNs); // your root element's name
    Element workflow = DocumentHelper.createElement(rootQName);
    Document doc = DocumentHelper.createDocument(workflow);

    workflow.addAttribute("name", "test");
    Element test = workflow.addElement("test");
    test.addText("hello");
    OutputFormat outputFormat = OutputFormat.createPrettyPrint();
    outputFormat.setEncoding("UTF-8");
    outputFormat.setIndent(true);/*from   www  .  j av a 2  s  . c  o  m*/
    outputFormat.setIndent("    ");
    outputFormat.setNewlines(true);
    try {
        StringWriter stringWriter = new StringWriter();
        XMLWriter xmlWriter = new XMLWriter(stringWriter);
        xmlWriter.write(doc);
        xmlWriter.close();
        System.out.println(doc.asXML());
        System.out.println(stringWriter.toString().trim());

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

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

License:EUPL

public String validateRecord(String recordString, List<String> problems) {
    if (!recordString.contains("<")) {
        return recordString;
    }//  w  w w.j a va  2  s.  com
    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.workflow.ValidatePlanAction.java

License:Open Source License

/**
 * reads the executable preservation plan and formats it.
 * /*from  www . j a  v  a2s.com*/
 */
private String formatExecutablePlan(String executablePlan) {

    if (executablePlan == null || "".equals(executablePlan)) {
        return "";
    }

    try {
        Document doc = DocumentHelper.parseText(executablePlan);

        StringWriter sw = new StringWriter();

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setNewlines(true);
        format.setTrimText(true);
        format.setIndent("  ");
        format.setExpandEmptyElements(false);
        format.setNewLineAfterNTags(20);

        XMLWriter writer = new XMLWriter(sw, format);

        writer.write(doc);
        writer.close();

        return sw.toString();

    } catch (DocumentException e) {
        return "";
    } catch (IOException e) {
        return "";
    }
}

From source file:eu.scape_project.planning.plato.wf.CreateExecutablePlan.java

License:Apache License

/**
 * Generates the preservation action plan other plan information and stores
 * it in the plan.//from ww w.ja  v  a 2s. c om
 * 
 * @throws PlanningException
 *             if an error occurred
 */
public void generatePreservationActionPlan() throws PlanningException {
    try {
        Document papDoc = generator.generatePreservationActionPlanDocument(
                plan.getSampleRecordsDefinition().getCollectionProfile(), plan.getExecutablePlanDefinition(),
                plan);

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding(PlanXMLConstants.ENCODING);

        XMLWriter writer = new XMLWriter(out, outputFormat);

        writer.write(papDoc);
        writer.close();

        ByteStream bs = new ByteStream();
        bs.setData(out.toByteArray());
        bs.setSize(out.size());

        DigitalObject digitalObject = new DigitalObject();
        digitalObject.setFullname(PreservationActionPlanGenerator.FULL_NAME);
        digitalObject.setContentType("application/xml");
        digitalObject.setData(bs);

        digitalObjectManager.moveDataToStorage(digitalObject);

        if (plan.getPreservationActionPlan() != null && plan.getPreservationActionPlan().isDataExistent()) {
            bytestreamsToRemove.add(plan.getPreservationActionPlan().getPid());
        }

        plan.setPreservationActionPlan(digitalObject);
        addedBytestreams.add(digitalObject.getPid());
        plan.getPreservationActionPlan().touch();
    } catch (IOException e) {
        log.error("Error generating preservation action plan {}.", e.getMessage());
        throw new PlanningException("Error generating preservation action plan.", e);
    } catch (StorageException e) {
        log.error("An error occurred while storing the executable plan: {}", e.getMessage());
        throw new PlanningException("An error occurred while storing the profile", e);
    }
}

From source file:fedora.utilities.XMLDocument.java

License:fedora commons license

public void write(Writer writer) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter output = new XMLWriter(writer, format);
    output.write(document);//from   w  ww  . j av  a 2  s. c  o m
    output.close();
}

From source file:fr.gouv.culture.vitam.database.utils.StaticValues.java

License:Open Source License

public final static void initialize() {
    StaticValues.LABELS = new PreferencesResourceBundle(Locale.getDefault());
    config = new ConfigLoader(CONFIG_VITAM);
    defaultOutputFormat = OutputFormat.createPrettyPrint();
    defaultOutputFormat.setEncoding(CURRENT_OUTPUT_ENCODING);
    if (LBL.option_langue.get().equalsIgnoreCase("fr")) {
        HELP_COMMAND = "Necessite au moins \"--xml fichier\" ou \"--print fichier\" ou \"--convertpdfa source destination\" ou \" --checkdigest fichier\" comme argument\n"
                + "\t[--help] pour imprimer cette aide\n"
                + "\t[-0,--config configurationFile (defaut=vitam-config.xml)]";
    } else {/* ww w .  ja  va2 s  . co  m*/
        HELP_COMMAND = "Need at least \"--xml filename\" or \"--print filename\" or \"--convertpdfa from to\" or \"--checkdigest filename\" as argument\n"
                + "\t[--help] to print help\n" + "\t[-0,--config configurationFile (default=vitam-config.xml)]";
    }
    ConstanceDataType.initializeTypes();
}