Example usage for org.dom4j.io XMLWriter flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the underlying Writer

Usage

From source file:de.thischwa.pmcms.view.renderer.ExportRenderer.java

License:LGPL

/**
 * Start the export of the static html pages.
 * // w  w w .  java2 s  .c  o  m
 * @throws RuntimeException if an exception is happened during rendering.
 */
@Override
public void run() {
    logger.debug("Entered run.");
    File siteDir = PoPathInfo.getSiteDirectory(this.site);
    if (monitor != null)
        monitor.beginTask(
                String.format("%s: %d", LabelHolder.get("task.export.monitor"), this.renderableObjects.size()),
                this.renderableObjects.size()); //$NON-NLS-1$

    if (CollectionUtils.isEmpty(site.getPages()))
        renderRedirector();

    try {
        FileUtils.cleanDirectory(exportDir);

        // build the directory structure for the renderables
        for (IRenderable ro : renderableObjects) {
            File dir = PathTool.getExportFile(ro, poExtension).getParentFile();
            if (!dir.exists())
                dir.mkdirs();
        }

        // loop through the renderable objects
        renderRenderables();

        if (!exportController.isError() && !isInterruptByUser) {
            logger.debug("Static export successfull!");

            // extra files to copy
            Set<File> filesToCopy = renderData.getFilesToCopy();
            for (File srcFile : filesToCopy) {
                String exportPathPart = srcFile.getAbsolutePath()
                        .substring(siteDir.getAbsolutePath().length() + 1);
                File destFile = new File(exportDir, exportPathPart);
                if (srcFile.isFile())
                    FileUtils.copyFile(srcFile, destFile);
            }
            logger.debug("Extra files successful copied!");

            // generate hashes
            Collection<File> exportedFiles = FileTool.collectFiles(exportDir);
            if (monitor != null) {
                monitor.done();
                monitor.beginTask("Calculate checksums", exportedFiles.size());
            }
            Document dom = ChecksumTool
                    .getDomChecksums(ChecksumTool.get(exportedFiles, exportDir.getAbsolutePath(), monitor));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setEncoding(Constants.STANDARD_ENCODING);
            XMLWriter writer = new XMLWriter(out, outformat);
            writer.write(dom);
            writer.flush();
            String formatedDomString = out.toString();
            InputStream in = new ByteArrayInputStream(formatedDomString.getBytes());
            Map<InputStream, String> toCompress = new HashMap<InputStream, String>();
            toCompress.put(in, checksumFilename);
            File zipFile = new File(PoPathInfo.getSiteExportDirectory(site),
                    FilenameUtils.getBaseName(checksumFilename) + ".zip");
            Zip.compress(zipFile, toCompress);
            zipFile = null;
        } else
            FileUtils.cleanDirectory(exportDir);
    } catch (Exception e) {
        logger.error("Error while export: " + e.getMessage(), e);
        throw new FatalException("Error while export " + this.site.getUrl() + e.getMessage(), e);
    } finally {
        if (monitor != null)
            monitor.done();
    }
}

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 www . j  a  v a 2 s.com
    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.xaniox.leaderboardextensions.ExtensionXmlHandler.java

License:Open Source License

public void saveExtensions(Set<GameExtension> extensions) throws IOException {
    if (!xmlFile.exists()) {
        xmlFile.createNewFile();/* ww  w  . j a v a  2s.  c  om*/
    }

    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   www .  ja  v  a2 s  . c om
 */
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 ww w  .  j  ava  2s  .c  om*/
 */
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.Resultado.java

License:Open Source License

/**
 * Mtodo esttico que exporta los valores obtenidos tras la simulacin al
 * formato XML.//from w w w  .  j  a va 2s .  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();
}

From source file:edu.ku.brc.specify.toycode.L18NStringResApp.java

License:Open Source License

/**
 * @param file//from  ww  w  .  j av a2  s  .co  m
 */
public void process(final File fileArg, final boolean doDiffs) {
    try {
        String dirName = RES_PATH + "values-" + destLocale.getLanguage();
        String path = dirName + File.separator + fileArg.getName();

        File file = fileArg;
        if (doDiffs) {
            file = new File(path);
        }
        Document doc = readFileToDOM4J(new FileInputStream(file));
        Node root = doc.getRootElement();

        for (Object nodeObj : root.selectNodes("/resources/string")) {
            Node node = (Node) nodeObj;
            String name = XMLHelper.getAttr((Element) node, "name", null);

            if (doDiffs) {
                if (baseHash.get(name) != null) {
                    continue;
                }
            }

            String text = node.getText();
            String transText = translate(text);
            if (transText != null) {
                node.setText(transText);
            }
            System.out.println(name + "[" + text + "][" + transText + "]");
        }

        File dir = new File(dirName);
        if (!dir.exists()) {
            dir.mkdir();
        }

        FileOutputStream fos = new FileOutputStream(path);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        writer.flush();

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

From source file:edu.upenn.cis.orchestra.workloadgenerator.GeneratorJournal.java

License:Apache License

/**
 * Write this <code>GeneratorJournal</code> out to <code>writer</code>.
 * See <code>serialize(...)</code> for the format.
 * // w  ww  . j  a v  a 2  s  .co  m
 * @param writer
 *            to which to write this <code>GeneratorJournal</code>.
 * @param params
 *            run parameters, see <code>Generator</code>.
 * @throws IOException
 *             if such is thrown whilst writing this
 *             <code>GeneratorJournal</code>.
 */
public void write(Writer writer, Map<String, Object> params) throws IOException {
    XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
    xmlWriter.write(serialize(params));
    xmlWriter.flush();
    xmlWriter.close();
}

From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java

License:Open Source License

/**
 * Dumps binary data to provided file/*from   w w w . ja  v a  2 s  .  c o m*/
 * It results in an XML file with a single element: data, 
 * @param id
 * @param data
 * @param f
 * @param encoder
 * @throws IOException
 */
private static void writeBinaryData(int id, ByteStream data, File f, BASE64Encoder encoder) throws IOException {
    Document streamDoc = DocumentHelper.createDocument();
    Element d = streamDoc.addElement("data");
    d.addAttribute("id", "" + id);
    d.setText(encoder.encode(data.getData()));
    XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(f)), ProjectExporter.prettyFormat);
    writer.write(streamDoc);
    writer.flush();
    writer.close();
}

From source file:eu.planets_project.pp.plato.application.AdminAction.java

License:Open Source License

/**
 * Renders the given exported XML-Document as HTTP response
 *///from   w w w.j  a v  a 2 s  .c o  m
private String returnXMLExport(Document doc) {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_kkmmss");
    String timestamp = format.format(new Date(System.currentTimeMillis()));

    String filename = "export_" + timestamp + ".xml";
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + "\"");
    //response.setContentLength(xml.length());
    try {
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        XMLWriter writer = new XMLWriter(out, ProjectExporter.prettyFormat);
        writer.write(doc);
        writer.flush();
        writer.close();
        out.flush();
        out.close();
    } catch (IOException e) {
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                "An error occured while generating the export file.");
        log.error("Could not open response-outputstream: ", e);
    }
    FacesContext.getCurrentInstance().responseComplete();
    return null;
}