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: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./*from w  w  w  . j a v a2  s  .com*/
 * @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:itensil.io.xml.XMLDocument.java

License:Open Source License

public static void writeStream(Document doc, OutputStream out) throws IOException {
    XMLWriter dxw = new XMLWriter(out, new OutputFormat("\t", true));
    dxw.write(doc);// w w  w.j  a v  a 2 s.  c  o m
}

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

License:Apache License

public synchronized void save() throws IOException {
    XMLWriter writer = null;/*www  . j ava2 s .c  om*/
    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

/**
 * Create an XML writer for the response
 * /*from  w  w w  . j a va2s. co  m*/
 * @return XMLWriter
 * @exception IOException
 */
protected final XMLWriter createXMLWriter() throws IOException {
    // Buffer the XML response, in case we have to reset mid-transaction
    m_xmlWriter = new CharArrayWriter(1024);
    return new XMLWriter(m_xmlWriter, getXMLOutputFormat());
}

From source file:jt56.comm.code.util.WolfXmlUtil.java

License:Open Source License

public void getXMLWrite(Document document, String filePath) throws Exception {
    OutputFormat of = new OutputFormat(" ", true);
    of.setEncoding("UTF-8");
    XMLWriter xw = new XMLWriter(new FileWriter(filePath), of);
    xw.setEscapeText(false);//from  w  w  w  .  j ava 2s.co m
    xw.write(document);
    xw.close();
    System.out.println(document.asXML());
}

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);/*from   www  .jav  a 2  s  .  c  o m*/
    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.
 * /*w  w w  .  j  ava2s.  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;
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Saves FREVO settings to the configuration file. Initiates file writing to
 * store data.//from  w w w.  ja v  a2 s  . co  m
 */
public static void saveSettings() {
    Document doc;
    File configfile = new File(FREVO_INSTALL_DIRECTORY + "/frevo_config.xml");
    if (configfile.exists()) {
        // load data if it already exists
        doc = SafeSAX.read(configfile, true);

        Node windowsizes = doc.selectSingleNode("/frevo/window-sizes");

        List<?> items = windowsizes.selectNodes(".//window");
        Iterator<?> it = items.iterator();

        while (it.hasNext()) {
            Element el = (Element) it.next();
            String name = el.valueOf("./@name");

            // save main data
            if (name.equals("main")) {
                el.addAttribute("width", Integer.toString(FrevoMain.mainWindowParameters[0]));
                el.addAttribute("height", Integer.toString(FrevoMain.mainWindowParameters[1]));
            }
            // save component browser data
            if (name.equals("componentbrowser")) {
                el.addAttribute("width", Integer.toString(FrevoMain.componentBrowserParameters[0]));
                el.addAttribute("height", Integer.toString(FrevoMain.componentBrowserParameters[1]));
                el.addAttribute("topsplit", Integer.toString(FrevoMain.componentBrowserParameters[2]));
                el.addAttribute("bigsplit", Integer.toString(FrevoMain.componentBrowserParameters[3]));
            }
        }
    } else {
        try {
            configfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // file does not exist
        doc = DocumentHelper.createDocument();
        doc.addDocType("frevo", null, "config.dtd");
        Element dfrevo = doc.addElement("frevo");

        dfrevo.addElement("tags");

        Element windowsizes = dfrevo.addElement("window-sizes");
        Element mainwindow = windowsizes.addElement("window");
        mainwindow.addAttribute("name", "main");
        mainwindow.addAttribute("width", Integer.toString(FrevoMain.mainWindowParameters[0]));
        mainwindow.addAttribute("height", Integer.toString(FrevoMain.mainWindowParameters[1]));

        Element compwindow = windowsizes.addElement("window");
        compwindow.addAttribute("name", "componentbrowser");
        compwindow.addAttribute("width", Integer.toString(FrevoMain.componentBrowserParameters[0]));
        compwindow.addAttribute("height", Integer.toString(FrevoMain.componentBrowserParameters[1]));
        compwindow.addAttribute("topsplit", Integer.toString(FrevoMain.componentBrowserParameters[2]));
        compwindow.addAttribute("bigsplit", Integer.toString(FrevoMain.componentBrowserParameters[3]));
    }

    // write to file
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        configfile.createNewFile();
        FileWriter out = new FileWriter(configfile);
        BufferedWriter bw = new BufferedWriter(out);
        XMLWriter wr = new XMLWriter(bw, format);
        wr.write(doc);
        wr.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Imports a component packaged in the FREVO package format (zcp). Copied
 * files will still persist even if operation fails or the component is bad.
 * //from  www  .j a v  a  2 s. co m
 * @param importfile
 *            The ZCP file to be imported.
 */
public static void importComponent(File importfile) {
    // unzip to the given location
    String outputdir = null;
    URI frevo_install_base = new File(FrevoMain.getInstallDirectory()).toURI();
    try {
        ZipFile zfile = new ZipFile(importfile);
        File directory = new File(FREVO_INSTALL_DIRECTORY + File.separator + "Components");

        Enumeration<? extends ZipEntry> entries = zfile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File file = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                file.getParentFile().mkdirs();
                InputStream in = zfile.getInputStream(entry);
                try {
                    copy(in, file);
                    // copy data from root XML
                    String extension = FrevoMain.getExtension(file);
                    if (extension.equals("xml")) {
                        URI fileURI = frevo_install_base.relativize(file.toURI());
                        String uristring = fileURI.toString();
                        String opath = uristring.substring(0, uristring.length() - extension.length() - 1);
                        if ((outputdir == null) || (opath.length() < outputdir.length())) {
                            outputdir = opath;
                        }
                    }
                } finally {
                    in.close();
                }
            }
        }
        zfile.close();
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // component successfully installed, add to Eclipse classpath
    File classpath = new File(FREVO_INSTALL_DIRECTORY + File.separator + ".classpath");
    if (classpath.exists()) {
        System.out.println("Adjusting Eclipse classpath...");
        Document doc = SafeSAX.read(classpath, true);

        Element root = doc.getRootElement();

        Element componentElement = root.addElement("classpathentry");
        componentElement.addAttribute("kind", "src");
        componentElement.addAttribute("output", outputdir);
        componentElement.addAttribute("path", outputdir);

        // save file
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setLineSeparator(System.getProperty("line.separator"));
            FileWriter out = new FileWriter(classpath);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            System.err.println("ERROR: Could not write Eclipse classpath file!");
            e.printStackTrace();
        }
    }

}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Removes the component from the installed components. This function also
 * removes all files within the component's directory. Forces FREVO to
 * reload all components afterwards.//w ww  .  j a  v  a 2  s .  co m
 * 
 * @param cdata
 *            The component to be removed
 */
public static void deleteComponent(ComponentXMLData cdata) {

    // remove base XML
    File baseXML = cdata.getSourceXMLFile();
    baseXML.delete();

    // erase all files within component directory
    // get class root directory
    String classDir = cdata.getClassDir();

    // extract directory name
    // construct copy
    int i = 0;
    while (i < classDir.length()) {
        char c = classDir.charAt(i);
        if ((c == '/') || (c == '\\')) {
            i++;
        } else {
            break;
        }
    }

    int end = i + 1;
    while (end < classDir.length()) {
        char c = classDir.charAt(end);
        if ((c == '/') || (c == '\\')) {
            break;
        } else {
            end++;
        }
    }

    classDir = classDir.substring(i, end);

    String comprootdirname = classDir.split("/")[0];

    // get component root directory
    String comprootdir = FrevoMain.getComponentDirectory(cdata.getComponentType()) + comprootdirname;

    File rootdir = new File(comprootdir);

    eraseDirectory(rootdir);

    // Remove entry from classpath
    File classpath = new File(FrevoMain.getInstallDirectory() + File.separator + ".classpath");
    if (classpath.exists()) {
        Document doc = SafeSAX.read(classpath, true);

        Element root = doc.getRootElement();
        String output; // the string to match the "output" field in
        // classpath xml

        // correct pathname for multiproblems
        if (cdata.getComponentType() == ComponentType.FREVO_MULTIPROBLEM)
            output = "Components/" + "Problems/" + comprootdirname;
        else if (cdata.getComponentType() == ComponentType.FREVO_BULKREPRESENTATION)
            output = "Components/" + "Representations/" + comprootdirname;
        else
            output = "Components/" + FrevoMain.getComponentTypeAsString(cdata.getComponentType()) + "s/"
                    + comprootdirname;
        // System.out.println("removing "+output);
        Node node = root.selectSingleNode("classpathentry[@output='" + output + "']");
        if (node != null)
            node.detach();

        // save XML
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setLineSeparator(System.getProperty("line.separator"));
            FileWriter out = new FileWriter(classpath);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            System.err.println("ERROR: Could not write Eclipse classpath file!");
            e.printStackTrace();
        }

    }

    // force reloading components
    FrevoMain.reLoadComponents(true);
}