List of usage examples for org.dom4j.io XMLWriter close
public void close() throws IOException
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 w w w.ja va 2 s. 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: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. *///www . jav a2 s .co 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.// ww w . jav a2 s. c o 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(); }
From source file:dk.netarkivet.common.utils.StreamUtils.java
License:Open Source License
/** * Write document tree to stream. Note, the stream is flushed, but not closed. * * @param doc the document tree to save. * @param os the stream to write xml to/*from w w w .j a va 2s. co m*/ * @throws IOFailure On trouble writing XML to stream. */ public static void writeXmlToStream(Document doc, OutputStream os) { ArgumentNotValid.checkNotNull(doc, "Document doc"); ArgumentNotValid.checkNotNull(doc, "OutputStream os"); XMLWriter xwriter = null; try { try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(UTF8_CHARSET); xwriter = new XMLWriter(os, format); xwriter.write(doc); } finally { if (xwriter != null) { xwriter.close(); } os.flush(); } } catch (IOException e) { String errMsg = "Unable to write XML to stream"; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } }
From source file:edu.ccut.saturn.manager.dict.core.dbmanager.Dom4jUtils.java
License:Apache License
public static String writeXml(String file, Document doc) { String message = null;/* w w w. j av a 2 s .c o m*/ XMLWriter writer = null; OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("GB2312"); format.setIndent(true); format.setIndent(" "); format.setNewlines(true); OutputStream out = null; try { out = new FileOutputStream(file); } catch (FileNotFoundException e1) { try { String path = Thread.currentThread().getContextClassLoader().getResource(BLANK_STRING).getFile() + file.substring(1); out = new FileOutputStream(path); } catch (FileNotFoundException e) { e.printStackTrace(); } } try { writer = new XMLWriter(out, format); writer.write(doc); } catch (Exception e) { e.printStackTrace(); } finally { try { writer.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } message = TRUE; return message; }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
License:Open Source License
/** * write a single record//from w w w . j a v a 2 s . c om * @param dbTable the class name of the table * @param id the id number of the record */ @SuppressWarnings("unchecked") public void writeSingleRecordXML(String dbTable, int id) { FileOutputStream fout; Session dom4jSession = session.getSession(EntityMode.DOM4J); // load the object by using its primary key DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); String primaryKey = info.getPrimaryKeyName(); String query = "from " + dbTable + " where " + primaryKey + " = " + id; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ List userXML = dom4jSession.createQuery(query).list(); try { fout = new FileOutputStream(importFolderPath + dbTable + ".xml"); //$NON-NLS-1$ PrintStream p = new PrintStream(fout); p.print("<root>"); //$NON-NLS-1$ OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(fout, format); for (int i = 0; i < userXML.size(); i++) { Element writeMe = (Element) userXML.get(i); writer.write(writeMe); } p.println("\n</root>"); //$NON-NLS-1$ p.close(); fout.close(); writer.close(); System.out.println("Wrote: " + dbTable + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } System.out.println(); }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
License:Open Source License
/** * write all the records of the given table. * @param dbTable the class name of the table * @return creates an xml file with name of the table */// w w w . ja v a2 s. c o m @SuppressWarnings("unchecked") public void writeXMLfile(String dataBase) { FileOutputStream fout; Session dom4jSession = session.getSession(EntityMode.DOM4J); String query = "from " + dataBase + " where id = 1"; //$NON-NLS-1$ //$NON-NLS-2$ System.out.println(query); List userXML = dom4jSession.createQuery(query).list(); try { fout = new FileOutputStream(importFolderPath + dataBase + ".xml"); //$NON-NLS-1$ PrintStream p = new PrintStream(fout); p.print("<root>"); //$NON-NLS-1$ OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(fout, format); for (int i = 0; i < userXML.size(); i++) { Element writeMe = (Element) userXML.get(i); writer.write(writeMe); } p.println("\n</root>"); //$NON-NLS-1$ p.close(); fout.close(); writer.close(); System.out.println("Wrote: " + dataBase + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } }
From source file:edu.ku.brc.specify.tasks.services.CollectingEventLocalityKMLGenerator.java
License:Open Source License
/** * Write the KML out to a file.// w ww .j ava 2 s . co m * * @param filename the name of the output file * @throws IOException a file I/O exception occurred */ public void outputToFile(final String filename) throws IOException { Document document = DocumentHelper.createDocument(); Element root = document.addElement("kml").addAttribute("xmlns", KML_NAMESPACE_DECL); Element kmlDocument = root.addElement("Document"); if (StringUtils.isNotEmpty(description)) { kmlDocument.addElement("description").addText(description); } GenericKMLGenerator.generateStyle(kmlDocument, placemarkIconURL, balloonStyleBgColor, balloonStyleTextColor, balloonStyleText); boolean isDoingCollectingEvents = false; DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance().createSession(); for (int i = 0; i < dataObjs.size(); ++i) { String label = labels.get(i); FormDataObjIFace dataObj = dataObjs.get(i); session.attach(dataObj); if (dataObj instanceof CollectingEvent) { generatePlacemark(kmlDocument, (CollectingEvent) dataObj, label); isDoingCollectingEvents = true; } else if (dataObj instanceof Locality) { generatePlacemark(kmlDocument, (Locality) dataObj, label); } else if (dataObj instanceof CollectionObject) { generatePlacemark(kmlDocument, (CollectionObject) dataObj, label); } } } catch (Exception ex) { ex.printStackTrace(); } finally { if (session != null) { session.close(); } } if (isDoingCollectingEvents) { /*String kmlStr = generatePathForLocalities(); if (kmlStr != null) { writer.write(kmlStr); }*/ } FileWriter out = new FileWriter(filename); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(out, format); writer.write(document); writer.close(); out.close(); }
From source file:edu.ku.brc.util.services.GenericKMLGenerator.java
License:Open Source License
/** * Generates KML output based on the current points, names and descriptions given to the generator. * //w w w . ja v a2s .com * @param out a stream to which the KML is written * @throws IOException if an I/O error occurs */ public void generateKML(final FileWriter out) throws IOException { Document kml = generateKML(); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(out, format); writer.write(kml); writer.close(); }
From source file:edu.scripps.fl.pubchem.promiscuity.XMLDocument.java
License:Apache License
public void write(Document doc, File toFile) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(toFile), format); writer.write(doc);//from w w w. j a va 2 s. c om writer.close(); }