Example usage for org.dom4j.io XMLWriter write

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

Introduction

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

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

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.j  ava  2s.  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 {//w w w.  j ava2s  .c om
        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.
 *//*from  w w w  . j a v a2  s  .c  om*/
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.xaniox.heavyspleef.migration.GameMigrator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  w  w w  .  j a  va2s. c o  m*/
public void migrate(Configuration inputSource, File outputFolder, Object cookie) throws MigrationException {
    if (cookie == null || !(cookie instanceof List<?>)) {
        throw new MigrationException("Cookie must be a game of lists");
    }

    countMigrated = 0;

    List<Game> gameList = (List<Game>) cookie;
    Set<String> gameNames = inputSource.getKeys(false);

    for (String name : gameNames) {
        ConfigurationSection section = inputSource.getConfigurationSection(name);

        File xmlFile = new File(outputFolder, name + FILE_EXTENSION);
        if (xmlFile.exists()) {
            //Rename this game as there is already a file
            xmlFile = new File(outputFolder, name + "_1" + FILE_EXTENSION);
        }

        XMLWriter writer = null;

        try {
            xmlFile.createNewFile();

            GameAccessor accessor = new GameAccessor(heavySpleef);
            Document document = DocumentHelper.createDocument();
            Element rootElement = document.addElement("game");

            Game game = migrateGame(section, rootElement);
            if (game == null) {
                continue;
            }

            accessor.write(game, rootElement);
            gameList.add(game);

            OutputStream out = new FileOutputStream(xmlFile);
            writer = new XMLWriter(out, outputFormat);
            writer.write(document);
            ++countMigrated;
        } catch (IOException e) {
            throw new MigrationException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:de.xaniox.heavyspleef.persistence.handler.CachingReadWriteHandler.java

License:Open Source License

@Override
public void saveGame(Game game) throws IOException {
    File gameFile = new File(xmlFolder, game.getName() + ".xml");
    if (!gameFile.exists()) {
        gameFile.createNewFile();/*from  ww w  .j  a va2  s.co m*/
    }

    Document document = DocumentHelper.createDocument();
    Element rootElement = document.addElement("game");

    xmlContext.write(game, rootElement);

    File gameSchematicFolder = new File(schematicFolder, game.getName());
    if (!gameSchematicFolder.exists()) {
        gameSchematicFolder.mkdir();
    }

    XMLWriter writer = null;

    try {
        FileOutputStream out = new FileOutputStream(gameFile);

        writer = new XMLWriter(out, xmlOutputFormat);
        writer.write(document);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    for (File file : gameSchematicFolder.listFiles(FLOOR_SCHEMATIC_FILTER)) {
        String floorName = file.getName().substring(2, file.getName().length() - 6);
        if (game.isFloorPresent(floorName)) {
            continue;
        }

        file.delete();
    }

    for (Floor floor : game.getFloors()) {
        File floorFile = new File(gameSchematicFolder, getFloorFileName(floor));
        if (!floorFile.exists()) {
            floorFile.createNewFile();
        }

        schematicContext.write(floorFile, floor);
    }
}

From source file:de.xaniox.leaderboardextensions.ExtensionXmlHandler.java

License:Open Source License

public void saveExtensions(Set<GameExtension> extensions) throws IOException {
    if (!xmlFile.exists()) {
        xmlFile.createNewFile();/*from  ww  w.  ja  v a2s. c  o m*/
    }

    Document document = DocumentHelper.createDocument();
    Element rootElement = document.addElement("extensions");

    for (GameExtension extension : extensions) {
        Element extensionElement = rootElement.addElement("extension");
        String name = registry.getExtensionName(extension.getClass());

        extensionElement.addAttribute("name", name);
        context.write(extension, extensionElement);
    }

    XMLWriter xmlWriter = null;

    try (OutputStream out = new FileOutputStream(xmlFile); Writer writer = new OutputStreamWriter(out, UTF8)) {
        xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(document);
        xmlWriter.flush();
    } finally {
        if (xmlWriter != null) {
            xmlWriter.close();
        }
    }
}

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

License:Apache License

/**
 * @param secDump//from  w  ww  .  j a va2 s  . com
 */
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/* w w w . ja  va2 s.  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   ww  w .  j a  va2s  .  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  v  a 2s . co m*/
 * @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();
}