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:de.tud.kom.p2psim.impl.network.gnp.topology.HostMap.java

License:Open Source License

/**
 * saves host postion location, GNP position, groups, GNP Space, PingER
 * Lookup table in an xml file used within the simulation
 * /*from  ww  w. j  av  a  2s .  com*/
 * @param file
 */
public void exportToXml(File file) {
    log.debug("Export Hosts to an XML File");
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(getDocument());
        writer.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:de.tud.kom.p2psim.impl.vis.util.Config.java

License:Open Source License

/**
 * Schreibt die bestehende XML-Struktur in die Config-Datei
 *//*from   ww w.  j a va2 s  .co m*/
public static void writeXMLFile() {

    if (config != null) { // Schreibe Datei nur, wenn XML-Baum im Speicher
        // vorhanden
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(new FileWriter(configFile), format);
            writer.write(Config.config);
            writer.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.lab.uima.engine.uimaas.AsDeploymentDescription.java

License:Apache License

public void toXML(OutputStream aOutput) throws IOException {
    Element root = createElement(E_ROOT);
    if (getName() != null) {
        root.addElement(E_NAME).setText(getName());
    }/*from   w w w . ja v a  2 s.  c om*/
    if (getDescription() != null) {
        root.addElement(E_DESCRIPTION).setText(getDescription());
    }
    if (getVendor() != null) {
        root.addElement(E_VENDOR).setText(getVendor());
    }
    if (getVersion() != null) {
        root.addElement(E_VERSION).setText(getVersion());
    }

    Element deployment = root.addElement(E_DEPLOYMENT).addAttribute(A_PROTOCOL, getProtocol())
            .addAttribute(A_PROVIDER, getProvider());

    Element service = deployment.addElement(E_SERVICE);
    service.addElement(E_INPUT_QUEUE).addAttribute(A_ENDPOINT, getEndpoint())
            .addAttribute(A_BROKER_URL, getBrokerUrl()).addAttribute(A_PREFETCH, getPrefetch());
    service.addElement(E_TOP_DESCRIPTOR).addElement(E_IMPORT).addAttribute(A_LOCATION,
            getTopDescriptorFile().getAbsolutePath());

    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8");
    XMLWriter writer = new XMLWriter(aOutput, outformat);
    writer.write(createDocument(root));
    writer.flush();
}

From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.Packet.java

License:Open Source License

public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {// ww  w  .ja  va  2  s. c  o m
        writer.write(element);
    } catch (Exception e) {
        // Ignore.
    }
    return out.toString();
}

From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.StreamError.java

License:Open Source License

public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {/* ww w .  jav  a 2s  .c  o m*/
        writer.write(element);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return out.toString();
}

From source file:de.tu_berlin.cit.rwx4j.xmpp.util.XMLProperties.java

License:Open Source License

/**
 * Saves the properties to disk as an XML document. A temporary file is
 * used during the writing process for maximum safety.
 *///  ww w. j  a v  a  2s.  com
private synchronized void saveProperties() {
    boolean error = false;
    // Write data out to a temporary file first.
    File tempFile = null;
    Writer writer = null;
    try {
        tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile)));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
        xmlWriter.write(document);
    } catch (Exception e) {
        e.printStackTrace();
        // There were errors so abort replacing the old property file.
        error = true;
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
                error = true;
            }
        }
    }

    // No errors occured, so delete the main file.
    if (!error) {
        // Delete the old file so we can replace it.
        if (!file.delete()) {
            System.err.println("Error deleting property file: " + file.getAbsolutePath());
            return;
        }
        // Copy new contents to the file.
        try {
            copy(tempFile, file);
        } catch (Exception e) {
            e.printStackTrace();
            // There were errors so abort replacing the old property file.
            error = true;
        }
        // If no errors, delete the temp file.
        if (!error) {
            tempFile.delete();
        }
    }
}

From source file:de.xwic.sandbox.server.installer.XmlExport.java

License:Apache License

/**
 * @param secDump/* ww w  . j a  v a  2s  .c o  m*/
 */
public void exportSecurity(File secDump) throws IOException, ConfigurationException {

    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement(ELM_EXPORT);
    root.addAttribute("type", "security");

    Element info = root.addElement(ELM_EXPORTDDATE);
    info.setText(DateFormat.getDateTimeInstance().format(new Date()));

    Element data = root.addElement(ELM_DATA);

    addAll(IActionDAO.class, data);
    addAll(IActionSetDAO.class, data);
    addAll(IScopeDAO.class, data);
    addAll(IRoleDAO.class, data);
    addAll(IRightDAO.class, data);
    addAll(IUserDAO.class, data);

    OutputFormat prettyFormat = OutputFormat.createPrettyPrint();
    OutputStream out = new FileOutputStream(secDump);
    XMLWriter writer = new XMLWriter(out, prettyFormat);
    writer.write(doc);
    writer.flush();
    out.close();

}

From source file:de.xwic.sandbox.server.installer.XmlExport.java

License:Apache License

/**
 * @param plDump//from  w  w w . j  a v a  2s . c o m
 */
public void exportPicklists(File plDump) throws IOException, ConfigurationException {

    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement(ELM_EXPORT);
    root.addAttribute("type", "picklists");

    Element info = root.addElement(ELM_EXPORTDDATE);
    info.setText(DateFormat.getDateTimeInstance().format(new Date()));

    Element data = root.addElement(ELM_DATA);

    addPicklisten(data);

    OutputFormat prettyFormat = OutputFormat.createPrettyPrint();
    OutputStream out = new FileOutputStream(plDump);
    XMLWriter writer = new XMLWriter(out, prettyFormat);
    writer.write(doc);
    writer.flush();
    out.close();

}

From source file:delphsim.model.Epidemia.java

License:Open Source License

/**
 * Guarda la informacin de esta epidemia en el archivo pasado como
 * parmetro, siguiendo el esquema del .xsd de la aplicacin.
 * @param archivoDestino El archivo destino donde se guardar el modelo.
 * @throws java.io.IOException Si hay problemas al escribir en disco.
 * @throws org.dom4j.DocumentException Si hay problemas al crear el objeto de tipo rbol.
 * @throws java.lang.Exception Si se produce algn otro problema.
 *///from w  ww . j  a va  2  s.c  o m
public void guardarXML(File archivoDestino) throws IOException, DocumentException, Exception {
    // Primero crear el documento dom4j con la informacin del modelo
    Document documento = DocumentHelper.createDocument();
    // Elemento raz epidemia
    Element elementoEpidemia = new DefaultElement("epidemia");
    documento.setRootElement(elementoEpidemia);
    elementoEpidemia.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    elementoEpidemia.addAttribute("xsi:noNamespaceSchemaLocation", "DelphSim1.18.xsd");
    elementoEpidemia.addAttribute("unidadTiempo", this.unidadTiempo);

    // Elementos parmetros
    if (this.parametros != null) {
        for (Parametro param : this.parametros) {
            Element elementoParametro = param.volcarAXML();
            elementoEpidemia.add(elementoParametro);
        }
    }

    // Elementos procesos
    if (this.procesos != null) {
        for (Proceso proc : this.procesos) {
            Element elementoProceso = proc.volcarAXML();
            elementoEpidemia.add(elementoProceso);
        }
    }

    // Elemento poblacin
    Element elementoPoblacion = this.poblacion.volcarAXML();
    elementoEpidemia.add(elementoPoblacion);

    // Elementos compartimentos
    for (Compartimento comp : this.compartimentos) {
        Element elementoCompartimento = comp.volcarAXML();
        elementoEpidemia.add(elementoCompartimento);
    }

    // Luego crear el formato, stream y escritor de la salida
    OutputFormat formato = OutputFormat.createPrettyPrint();
    formato.setEncoding("UTF-16");
    formato.setIndent("\t");
    formato.setNewLineAfterDeclaration(false);
    formato.setPadText(false);
    formato.setTrimText(true);
    formato.setXHTML(true);
    java.io.OutputStreamWriter salida = new java.io.OutputStreamWriter(
            new java.io.FileOutputStream(archivoDestino), "UTF-16");
    XMLWriter escritor = new XMLWriter(salida, formato);
    // Y escribir
    escritor.write(documento);
    escritor.close();
}

From source file:delphsim.model.Resultado.java

License:Open Source License

/**
 * Mtodo esttico que exporta los valores obtenidos tras la simulacin al
 * formato XML./*from  w  ww .j a  va  2  s. c  om*/
 * @param destino El archivo de destino.
 * @param nombres Los nombres de las distintas columnas/funciones.
 * @param definiciones La definicin de cada columna/funcin.
 * @param temps Array con los archivos temporales de los cuales obtener los
 *              datos a exportar.
 * @param numPuntosTotal El nmero de puntos total que contienen los
 *                       archivos temporales.
 * @param numPuntosExportar El nmero de puntos que quiere obtener el usuario.
 * @throws java.io.IOException Si hubiera algn problema al crear el archivo en disco.
 */
public static void exportarComoXML(File destino, String[] nombres, String[] definiciones, File[] temps,
        long numPuntosTotal, long numPuntosExportar) throws IOException {
    // Crear el documento, el elemento 'raiz' y asignarlo
    org.dom4j.Document documento = DocumentHelper.createDocument();
    DefaultElement elementoResultado = new DefaultElement("resultado");
    documento.setRootElement(elementoResultado);

    // Creamos los bfers de lectura para leer los temporales
    BufferedReader[] buffers = new BufferedReader[temps.length];
    for (int i = 0; i < temps.length; i++) {
        buffers[i] = new BufferedReader(new FileReader(temps[i]));
    }
    // Calculamos cada cuanto tenemos que guardar un punto
    double cadaCuanto;
    if (numPuntosTotal == numPuntosExportar) {
        cadaCuanto = 1.0d;
    } else {
        cadaCuanto = new Double(numPuntosTotal) / new Double(numPuntosExportar - 1);
    }
    long siguientePuntoExportar = 0;
    long contadorNumPuntoLeido = 0;
    long contadorNumPuntosExportados = 0;
    // Comenzamos a leer los temporales aadiendo elementos al documento
    String[] valores = new String[buffers.length];
    for (int i = 0; i < buffers.length; i++) {
        valores[i] = buffers[i].readLine();
    }
    // En el momento en que se lee un null, se termina
    while (valores[0] != null) {
        // Para cada punto que haya que exportar
        if (siguientePuntoExportar == contadorNumPuntoLeido) {
            DefaultElement nuevaFila = new DefaultElement("fila");
            // Para el tiempo, nuevo elemento, su valor y aadirlo a la fila
            DefaultElement elementoTiempo = new DefaultElement("Tiempo");
            elementoTiempo.setText(valores[0]);
            nuevaFila.add(elementoTiempo);
            // Lo mismo para cada linea, pero ademas con nombre y definicin
            for (int i = 1; i < valores.length; i++) {
                DefaultElement elementoLinea = new DefaultElement("Lnea" + i);
                elementoLinea.add(new DefaultAttribute("nombre", nombres[i]));
                elementoLinea.add(new DefaultAttribute("definicion", definiciones[i]));
                elementoLinea.setText(valores[i]);
                nuevaFila.add(elementoLinea);
            }
            // Y aadimos la nueva fila
            elementoResultado.add(nuevaFila);
            // Calculamos el siguiente punto a exportar
            contadorNumPuntosExportados++;
            siguientePuntoExportar = Math.round(cadaCuanto * contadorNumPuntosExportados);
            if (siguientePuntoExportar >= numPuntosTotal) {
                siguientePuntoExportar = numPuntosTotal - 1;
            }
        }
        // Leemos la siguiente lnea de los ficheros
        for (int i = 0; i < buffers.length; i++) {
            valores[i] = buffers[i].readLine();
        }
        contadorNumPuntoLeido++;
    }
    // Cerramos los bfers y el archivo de salida
    for (int i = 0; i < buffers.length; i++) {
        buffers[i].close();
    }
    // Imprimimos el documento como XML
    OutputFormat formato = OutputFormat.createPrettyPrint();
    formato.setEncoding("UTF-16");
    formato.setIndent("\t");
    formato.setNewLineAfterDeclaration(false);
    formato.setPadText(false);
    formato.setTrimText(true);
    formato.setXHTML(true);
    OutputStreamWriter salida = new OutputStreamWriter(new FileOutputStream(destino), "UTF-16");
    XMLWriter escritor = new XMLWriter(salida, formato);
    escritor.write(documento);
    escritor.flush();
    escritor.close();
}