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:it.eng.qbe.datasource.configuration.dao.fileimpl.CalculatedFieldsDAOFileImpl.java

License:Mozilla Public License

private void guardedWrite(Document document, File file) {
    Writer out;//from www.j av a  2 s .com
    OutputFormat format;
    XMLWriter writer;

    logger.debug("IN");

    out = null;
    writer = null;

    try {

        logger.debug("acquiring lock...");
        getLock();
        logger.debug("Lock acquired");

        out = null;
        try {
            out = new FileWriter(file);
        } catch (IOException e) {
            throw new DAOException("Impossible to open file [" + file + "]", e);
        }
        Assert.assertNotNull(out, "Output stream cannot be null");

        format = OutputFormat.createPrettyPrint();
        format.setEncoding("ISO-8859-1");
        format.setIndent("    ");
        writer = new XMLWriter(out, format);
        try {

            writer.write(document);
            writer.flush();
        } catch (IOException e) {
            throw new DAOException("Impossible to write to file [" + file + "]", e);
        }
    } catch (Throwable t) {
        if (t instanceof DAOException)
            throw (DAOException) t;
        throw new DAOException("An unpredicetd error occurred while writing on file [" + file + "]");
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                throw new DAOException("Impossible to properly close stream to file file [" + file + "]", e);
            }
        }
        logger.debug("releasing lock...");
        releaseLock();
        logger.debug("lock released");

        logger.debug("OUT");
    }

}

From source file:it.pdfsam.env.EnvWorker.java

License:Open Source License

/**
 * Saves the environment/*from  ww  w . j  av a2 s .  c  o  m*/
 * 
 */
public void saveJob() {
    try {
        file_chooser.setApproveButtonText(GettextResource.gettext(i18n_messages, "Save job"));
        int return_val = file_chooser.showOpenDialog(null);
        File chosen_file = null;
        if (return_val == JFileChooser.APPROVE_OPTION) {
            chosen_file = file_chooser.getSelectedFile();
            if (chosen_file != null) {
                try {
                    Document document = DocumentHelper.createDocument();
                    Element root = document.addElement("pdfsam_saved_jobs");
                    root.addAttribute("version", MainGUI.NAME);
                    root.addAttribute("savedate", new SimpleDateFormat("dd-MMM-yyyy").format(new Date()));
                    for (int i = 0; i < pl_panel.length; i++) {
                        Element node = (Element) root.addElement("plugin");
                        node.addAttribute("class", pl_panel[i].getClass().getName());
                        node.addAttribute("name", pl_panel[i].getPluginName());
                        pl_panel[i].getJobNode(node);
                        fireLogPropertyChanged(GettextResource.gettext(i18n_messages,
                                pl_panel[i].getPluginName() + " job node loaded."), LogPanel.LOG_DEBUG);
                    }
                    FileWriter file_writer = new FileWriter(chosen_file);
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter xml_file_writer = new XMLWriter(file_writer, format);
                    xml_file_writer.write(document);
                    xml_file_writer.flush();
                    xml_file_writer.close();
                    fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Job saved."),
                            LogPanel.LOG_INFO);
                } catch (Exception ex) {
                    fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                            LogPanel.LOG_ERROR);

                }
            }
        }
    } catch (RuntimeException re) {
        fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "RuntimeError:")
                + " Unable to load environment. " + re.getMessage(), LogPanel.LOG_ERROR);
    } catch (Exception e) {
        fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error:")
                + " Unable to load environment. " + e.getMessage(), LogPanel.LOG_ERROR);
    }
}

From source file:it.pdfsam.util.XMLParser.java

License:Open Source License

/**
 * Write the DOM to the xml file//from  ww w.ja  va2 s  . c  om
 * 
 * @param domDoc Document to write
 * @param full_path Full path to the xml file to write
 * @throws Exception
 */
public static void writeXmlFile(Document domDoc, String full_path) throws Exception {
    FileWriter file_writer = new FileWriter(full_path);
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter xml_file_writer = new XMLWriter(file_writer, format);
    xml_file_writer.write(domDoc);
    xml_file_writer.flush();
    xml_file_writer.close();
}

From source file:it.pdfsam.utils.XMLParser.java

License:Open Source License

/**
 * Write the DOM to the xml file//from   w  ww.j a  va 2  s .  c  om
 * @param domDoc Document to write
 * @param full_path Full path to the xml file to write
 * @throws Exception
 */
public static void writeXmlFile(Document domDoc, String full_path) throws Exception {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(full_path));
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    XMLWriter xml_file_writer = new XMLWriter(bos, format);
    xml_file_writer.write(domDoc);
    xml_file_writer.flush();
    xml_file_writer.close();
}

From source file:it.unibz.inf.xmlssd.metadator.helpers.Exporter.java

License:Apache License

/**
 * Export method which exports all the stored data as a XML document.
 * @throws IOException//ww  w. ja v  a  2s.c om
 */
public void export() throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(aFile.getCanonicalPath()), format);

    SQLiteManager sqlite = new SQLiteManager();

    writer.write(sqlite.get());
    writer.close();
}

From source file:it.unibz.inf.xmlssd.metadator.helpers.UIHelper.java

License:Apache License

/**
 * Method which return a pretty formated string. If it fails the untouched
 * string is given back./* www.j av  a  2 s  .  c  o  m*/
 * @param str
 * @return
 */
public static String prettyPrintString(String str) {
    try {
        Document document = DocumentHelper.parseText(str);
        OutputFormat format = OutputFormat.createPrettyPrint();

        // remove <?xml version="1.0" encoding="UTF-8"?>
        format.setSuppressDeclaration(true);

        StringWriter strWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(strWriter, format);

        writer.write(document);

        return strWriter.toString();
    } catch (IOException e) {
    } catch (DocumentException e) {
    }

    return str;
}

From source file:job.tot.xml.DOM4JConfiguration.java

License:Apache License

public synchronized void save() throws IOException {
    XMLWriter writer = null;// w  w  w .ja v a2 s. com
    OutputStream out = null;
    try {
        OutputFormat outputter = OutputFormat.createPrettyPrint();
        out = new BufferedOutputStream(new FileOutputStream(getFile()));
        writer = new XMLWriter(out, outputter);
        writer.write(document);
    } finally {
        if (out != null) {
            out.close();
        }

        if (writer != null) {
            writer.close();
        }
    }
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

License:Open Source License

/**
 * Returns the format required for an XML response. This may vary per method.
 *//*from w ww  .  jav a 2  s. c  o m*/
protected OutputFormat getXMLOutputFormat() {
    // Check if debug output or XML pretty printing is enabled
    return (XMLPrettyPrint || logger.isDebugEnabled()) ? OutputFormat.createPrettyPrint()
            : OutputFormat.createCompactFormat();
}

From source file:lempel.blueprint.base.config.XmlConfig.java

License:Open Source License

public void save(final String fileName) throws IOException {
    org.dom4j.Document dom4jDoc = new DOMReader().read(config);
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
    writer.write(dom4jDoc);// w w  w  . j  a  v a2 s .  com
    writer.close();
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Starts a saving procedure calling the method's own saveResults function.
 * Run-specific data will be added to the end of the file.
 * /*from w ww .j  a  v  a2 s.  c  o m*/
 * @param fileName
 *            Name of the saved file without the extension. (E.g.
 *            solution_generation_13)
 * @param method
 *            The corresponding method instance to be called for saving.
 */
public static File saveResult(String fileName, final Element representationRootElement, long startSeed,
        long currentActiveSeed) {
    // create new document for output
    Document doc = DocumentHelper.createDocument();
    doc.addDocType("frevo", null, System.getProperty("user.dir") + "//Components//ISave.dtd");
    Element dfrevo = doc.addElement("frevo");

    String fileLocation = "Undefined";

    // export sessionconfig
    Element sessionconfig = dfrevo.addElement("sessionconfig");

    // custom name
    Element configentry = sessionconfig.addElement("configentry");
    configentry.addAttribute("key", "CustomName");
    configentry.addAttribute("type", "STRING");
    configentry.addAttribute("value", customName);

    // number of runs
    Element runentry = sessionconfig.addElement("configentry");
    runentry.addAttribute("key", "NumberofRuns");
    runentry.addAttribute("type", "INT");
    runentry.addAttribute("value", Integer.toString(getNumberOfSimulationRuns()));

    // starting seed
    Element seedentry = sessionconfig.addElement("configentry");
    seedentry.addAttribute("key", "StartingSeed");
    seedentry.addAttribute("type", "LONG");
    // seedentry.addAttribute("value", Long.toString(getSeed()));
    seedentry.addAttribute("value", Long.toString(startSeed));

    // active seed
    Element aseedentry = sessionconfig.addElement("configentry");
    aseedentry.addAttribute("key", "CurrentSeed");
    aseedentry.addAttribute("type", "LONG");
    aseedentry.addAttribute("value", Long.toString(currentActiveSeed));

    try {
        // export problem
        Element problemsettings = dfrevo.addElement("problem");
        ComponentXMLData problem = FrevoMain.SELECTED_PROBLEM;
        problemsettings.addAttribute("class", problem.getClassName());
        Vector<String> keys = new Vector<String>(problem.getProperties().keySet());
        for (String k : keys) {
            Element entry = problemsettings.addElement("problementry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", problem.getTypeOfProperty(k).toString());
            entry.addAttribute("value", problem.getValueOfProperty(k));
        }

        // export method
        Element methodsettings = dfrevo.addElement("method");
        ComponentXMLData method = FrevoMain.SELECTED_METHOD;
        methodsettings.addAttribute("class", method.getClassName());
        keys = new Vector<String>(method.getProperties().keySet());
        for (String k : keys) {
            Element entry = methodsettings.addElement("methodentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", method.getTypeOfProperty(k).toString());
            entry.addAttribute("value", method.getValueOfProperty(k));
        }

        // export ranking
        Element rankingsettings = dfrevo.addElement("ranking");
        ComponentXMLData ranking = FrevoMain.SELECTED_RANKING;
        rankingsettings.addAttribute("class", ranking.getClassName());
        keys = new Vector<String>(ranking.getProperties().keySet());
        for (String k : keys) {
            Element entry = rankingsettings.addElement("rankingentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", ranking.getTypeOfProperty(k).toString());
            entry.addAttribute("value", ranking.getValueOfProperty(k));
        }

        // export representation
        Element repsettings = dfrevo.addElement("representation");
        ComponentXMLData representation = FrevoMain.SELECTED_REPRESENTATION;
        repsettings.addAttribute("class", representation.getClassName());
        keys = new Vector<String>(representation.getProperties().keySet());
        for (String k : keys) {
            Element entry = repsettings.addElement("representationentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", representation.getTypeOfProperty(k).toString());
            entry.addAttribute("value", representation.getValueOfProperty(k));
        }

        // call method's own save solution
        dfrevo.add(representationRootElement);

        // save contents to file

        String location = FREVO_INSTALL_DIRECTORY + File.separator + "Results" + File.separator + customName;
        File rootSaveDir = new File(location);

        // remove spaces from filename
        fileName.replaceAll(" ", "_");

        // create save directory based on given custom name
        rootSaveDir.mkdirs();

        // create sub-directories for different seeds
        if (FrevoMain.getNumberOfSimulationRuns() > 1) {
            // create seed directory if there are more than one run
            File seedDir = new File(location + File.separator + "seed_" + startSeed);
            seedDir.mkdir();
            fileLocation = seedDir + File.separator + fileName + ".zre";
        } else {
            // save it the root location
            fileLocation = rootSaveDir + File.separator + fileName + ".zre";
        }

        File saveFile = new File(fileLocation);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        saveFile.createNewFile();
        FileWriter out = new FileWriter(saveFile);
        BufferedWriter bw = new BufferedWriter(out);
        XMLWriter wr = new XMLWriter(bw, format);
        wr.write(doc);
        wr.close();
        System.out.println("XML Writing Completed: " + fileLocation);

        if (isFrevoWithGraphics()) {
            mainWindow.addRecentResult(saveFile);
        }
        return saveFile;
    } catch (OutOfMemoryError mem) {
        System.err.println("Could not export! (Out of memory)");
    } catch (IOException e) {
        System.err.println("IOException while writing to XML! Check path at: " + fileLocation);
        e.printStackTrace();
    }
    return null;
}