List of usage examples for org.jdom2.output XMLOutputter setFormat
public void setFormat(Format newFormat)
From source file:odml.core.Writer.java
License:Open Source License
/** * Writes the dom tree to the given output stream. * * @param stream the output stream// w w w . j a v a 2 s .c o m * @return true if the dom tree was successfully written to the stream, false otherwise * */ private boolean writeToStream(OutputStream stream) { if (doc == null) { System.out.println("Writing to Stream failed, document is empty!"); return false; } try { org.jdom2.output.Format format = org.jdom2.output.Format.getPrettyFormat().setIndent(" "); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, stream); } catch (IOException ie) { System.out.println("Write to file failed: " + ie.getMessage()); return false; } System.out.println("Writing to file successful!"); return true; }
From source file:org.apache.maven.io.util.AbstractJDOMWriter.java
License:Apache License
public final void write(final T source, final Document document, final Writer writer, final Format jdomFormat, final DocumentModifier modifier) throws java.io.IOException { if (modifier != null) { modifier.preProcess(document);/*from w w w.java2 s.co m*/ } update(source, new IndentationCounter(0), document.getRootElement()); if (modifier != null) { modifier.postProcess(document); } // Override XMLOutputter to correct initial comment trailing newlines. final XMLOutputter outputter = new XMLOutputter(new AbstractXMLOutputProcessor() { /** * This will handle printing of a {@link Document}. * * @param out <code>Writer</code> to use. * @param fstack the FormatStack * @param nstack the NamespaceStack * @param doc <code>Document</code> to write. * @throws IOException if the destination Writer fails */ @Override protected void printDocument(Writer out, FormatStack fstack, NamespaceStack nstack, Document doc) throws IOException { // If there is no root element then we cannot use the normal ways to // access the ContentList because Document throws an exception. // so we hack it and just access it by index. List<Content> list = doc.hasRootElement() ? doc.getContent() : new ArrayList<Content>(doc.getContentSize()); if (list.isEmpty()) { final int sz = doc.getContentSize(); for (int i = 0; i < sz; i++) { list.add(doc.getContent(i)); } } printDeclaration(out, fstack); Walker walker = buildWalker(fstack, list, true); if (walker.hasNext()) { while (walker.hasNext()) { final Content c = walker.next(); // we do not ignore Text-like things in the Document. // the walker creates the indenting for us. if (c == null) { // but, what we do is ensure it is all whitespace, and not CDATA final String padding = walker.text(); if (padding != null && Verifier.isAllXMLWhitespace(padding) && !walker.isCDATA()) { // we do not use the escaping or text* method because this // content is outside of the root element, and thus is not // strict text. write(out, padding); } } else { switch (c.getCType()) { case Comment: printComment(out, fstack, (Comment) c); // This modification we have made to the overridden method in order // to correct newline declarations. write(out, fstack.getLineSeparator()); break; case DocType: printDocType(out, fstack, (DocType) c); break; case Element: printElement(out, fstack, nstack, (Element) c); if (walker.hasNext()) { // This modification we have made to the overridden method in order // to correct newline declarations. write(out, fstack.getLineSeparator()); } break; case ProcessingInstruction: printProcessingInstruction(out, fstack, (ProcessingInstruction) c); break; case Text: final String padding = ((Text) c).getText(); if (padding != null && Verifier.isAllXMLWhitespace(padding)) { // we do not use the escaping or text* method because this // content is outside of the root element, and thus is not // strict text. write(out, padding); } default: // do nothing. } } } if (fstack.getLineSeparator() != null) { write(out, fstack.getLineSeparator()); } } } }); outputter.setFormat(jdomFormat); outputter.output(document, writer); }
From source file:org.crazyt.xgogdownloader.Util.java
License:Open Source License
public final int createXML(String filepath, int chunk_size, String xml_dir) { int res = 0;//from w w w . j a va 2 s . c o m File infile; int filesize; int size; int chunks; int i; if (xml_dir == "") { xml_dir = ".cache/xgogdownloader/xml"; } // end of if File path = Factory.newFile(xml_dir); if (!path.exists()) { if (!path.mkdirs()) { System.out.println("Failed to create directory: " + path); } } infile = Factory.newFile(filepath); // RandomAccessFile file = new RandomAccessFile("file.txt", "rw");? // fseek/seek ftell/getFilePointer rewind/seek(0) if (infile.exists()) { filesize = (int) infile.length(); } else { System.out.println(filepath + " doesn't exist"); return res; } // end of if-else // Get filename String filename = FilenameUtils.removeExtension(infile.getName()); String filenameXML = xml_dir + "/" + filename + ".xml"; System.out.println(filename); // Determine number of chunks int remaining = filesize % chunk_size; chunks = (remaining == 0) ? filesize / chunk_size : (filesize / chunk_size) + 1; System.out.println("Filesize: " + filesize + " bytes"); System.out.println("Chunks: " + chunks); System.out.println("Chunk size: " + (chunk_size / Math.pow(2.0, 20.0)) + " MB"); Util util_md5 = new Util(); String file_md5 = util_md5.getFileHash(filepath); System.out.println("MD5: " + file_md5); Element fileElem = new Element("file"); fileElem.setAttribute(new Attribute("name", filename)); fileElem.setAttribute(new Attribute("md5", file_md5)); fileElem.setAttribute(new Attribute("chunks", String.valueOf(chunks))); fileElem.setAttribute(new Attribute("total_size", String.valueOf(filesize))); System.out.println("Getting MD5 for chunks"); for (i = 0; i < chunks; i++) { int range_begin = i * chunk_size; // fseek(infile, range_begin, SEEK_SET); if ((i == chunks - 1) && (remaining != 0)) { chunk_size = remaining; } int range_end = range_begin + chunk_size - 1; String chunk = String.valueOf(chunk_size * 4); String hash = util_md5.getChunkHash(chunk); // calculates hash of // chunk string? Element chunkElem = new Element("chunk"); chunkElem.setAttribute(new Attribute("id", String.valueOf(i))); chunkElem.setAttribute(new Attribute("from", String.valueOf(range_begin))); chunkElem.setAttribute(new Attribute("to", String.valueOf(range_begin))); chunkElem.setAttribute(new Attribute("method", "md5")); chunkElem.addContent(new Text(hash)); fileElem.addContent(chunkElem); System.out.println("Chunks hashed " + (i + 1) + " / " + chunks + "\r"); } Document doc = new Document(fileElem); System.out.println("Writing XML: " + filenameXML); try { XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, Factory.newFileWriter(filenameXML)); res = 1; } catch (IOException e) { System.out.println("Can't create " + filenameXML); return res; } return res; }
From source file:org.geoserver.backuprestore.tasklet.AbstractCatalogBackupRestoreTasklet.java
License:Open Source License
/** * This method dumps the current Backup index: - List of Workspaces - List of Stores - List of * Layers/*from ww w .j ava 2s . c o m*/ * * @param sourceFolder * @throws IOException */ protected void dumpBackupIndex(Resource sourceFolder) throws IOException { Element root = new Element("Index"); Document doc = new Document(); for (WorkspaceInfo ws : getCatalog().getWorkspaces()) { if (!filteredResource(ws, false)) { Element workspace = new Element("Workspace"); workspace.addContent(new Element("Name").addContent(ws.getName())); root.addContent(workspace); for (DataStoreInfo ds : getCatalog().getStoresByWorkspace(ws.getName(), DataStoreInfo.class)) { if (!filteredResource(ds, ws, true, StoreInfo.class)) { Element store = new Element("Store"); store.setAttribute("type", "DataStoreInfo"); store.addContent(new Element("Name").addContent(ds.getName())); workspace.addContent(store); for (FeatureTypeInfo ft : getCatalog().getFeatureTypesByDataStore(ds)) { if (!filteredResource(ft, ws, true, ResourceInfo.class)) { for (LayerInfo ly : getCatalog().getLayers(ft)) { if (!filteredResource(ly, ws, true, LayerInfo.class)) { Element layer = new Element("Layer"); layer.setAttribute("type", "VECTOR"); layer.addContent(new Element("Name").addContent(ly.getName())); store.addContent(layer); } } } } } } for (CoverageStoreInfo cs : getCatalog().getStoresByWorkspace(ws.getName(), CoverageStoreInfo.class)) { if (!filteredResource(cs, ws, true, StoreInfo.class)) { Element store = new Element("Store"); store.setAttribute("type", "CoverageStoreInfo"); store.addContent(new Element("Name").addContent(cs.getName())); workspace.addContent(store); for (CoverageInfo ci : getCatalog().getCoveragesByCoverageStore(cs)) { if (!filteredResource(ci, ws, true, ResourceInfo.class)) { for (LayerInfo ly : getCatalog().getLayers(ci)) { if (!filteredResource(ly, ws, true, LayerInfo.class)) { Element layer = new Element("Layer"); layer.setAttribute("type", "RASTER"); layer.addContent(new Element("Name").addContent(ly.getName())); store.addContent(layer); } } } } } } } } if (filterIsValid()) { Element filter = new Element("Filters"); if (getFilters().length > 0 && getFilters()[0] != null) { Element wsFilter = new Element("Filter"); wsFilter.setAttribute("type", "WorkspaceInfo"); wsFilter.addContent(new Element("ECQL").addContent(ECQL.toCQL(getFilters()[0]))); filter.addContent(wsFilter); } if (getFilters().length > 1 && getFilters()[1] != null) { Element siFilter = new Element("Filter"); siFilter.setAttribute("type", "StoreInfo"); siFilter.addContent(new Element("ECQL").addContent(ECQL.toCQL(getFilters()[1]))); filter.addContent(siFilter); } if (getFilters().length > 2 && getFilters()[2] != null) { Element liFilter = new Element("Filter"); liFilter.setAttribute("type", "LayerInfo"); liFilter.addContent(new Element("ECQL").addContent(ECQL.toCQL(getFilters()[2]))); filter.addContent(liFilter); } root.addContent(filter); } doc.setRootElement(root); XMLOutputter outter = new XMLOutputter(); outter.setFormat(Format.getPrettyFormat()); outter.output(doc, new FileWriter(sourceFolder.get(BR_INDEX_XML).file())); }
From source file:org.goobi.managedbeans.ProcessBean.java
License:Open Source License
/** * Create the database information xml file and send it to the servlet output stream */// w ww . j a va2s . c o m public void downloadProcessDatebaseInformation() { FacesContext facesContext = FacesContextHelper.getCurrentFacesContext(); if (!facesContext.getResponseComplete()) { org.jdom2.Document doc = new ExportXmlLog().createExtendedDocument(myProzess); String outputFileName = myProzess.getId() + "_db_export.xml"; HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType(outputFileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + outputFileName + "\""); try { ServletOutputStream out = response.getOutputStream(); XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getPrettyFormat()); outp.output(doc, out); out.flush(); } catch (IOException e) { Helper.setFehlerMeldung("could not export database information: ", e); } facesContext.responseComplete(); } }
From source file:org.goobi.production.export.ExportXmlLog.java
License:Open Source License
/** * This method exports the production metadata as xml to a given stream. * //from ww w . ja va 2s.c o m * @param process the process to export * @param os the OutputStream to write the contents to * @throws IOException * @throws ExportFileException */ @Override public void startExport(Process process, OutputStream os, String xslt) throws IOException { try { Document doc = createDocument(process, true); XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getPrettyFormat()); outp.output(doc, os); os.close(); } catch (Exception e) { throw new IOException(e); } }
From source file:org.goobi.production.export.ExportXmlLog.java
License:Open Source License
/** * This method exports the production metadata for al list of processes as a single file to a given stream. * /*www . ja v a2 s. com*/ * @param processList * @param outputStream * @param xslt */ public void startExport(List<Process> processList, OutputStream outputStream, String xslt) { Document answer = new Document(); Element root = new Element("processes"); answer.setRootElement(root); Namespace xmlns = Namespace.getNamespace("http://www.goobi.io/logfile"); Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); root.addNamespaceDeclaration(xsi); root.setNamespace(xmlns); Attribute attSchema = new Attribute("schemaLocation", "http://www.goobi.io/logfile" + " XML-logfile.xsd", xsi); root.setAttribute(attSchema); for (Process p : processList) { Document doc = createDocument(p, false); Element processRoot = doc.getRootElement(); processRoot.detach(); root.addContent(processRoot); } XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getPrettyFormat()); try { outp.output(answer, outputStream); } catch (IOException e) { } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { outputStream = null; } } } }
From source file:org.helm.notation2.tools.xHelmNotationExporter.java
License:Open Source License
/** * method to get xhelm for the helm2 notation with the new functionality * * @param helm2notation, HELM2Notation object * @return xhelm/* w w w .ja v a 2 s.com*/ * @throws MonomerException * @throws JDOMException * @throws IOException * @throws ChemistryException */ public static String getXHELM2(HELM2Notation helm2notation) throws MonomerException, IOException, JDOMException, ChemistryException { set = new HashSet<Monomer>(); Element root = new Element(xHelmNotationExporter.XHELM_ELEMENT); Document doc = new Document(root); Element helmElement = new Element(xHelmNotationExporter.HELM_NOTATION_ELEMENT); helmElement.setText(helm2notation.toHELM2()); root.addContent(helmElement); Element monomerListElement = new Element(xHelmNotationExporter.MONOMER_LIST_ELEMENT); /* save all adhocMonomers */ for (MonomerNotation monomernotation : MethodsMonomerUtils .getListOfMonomerNotation(helm2notation.getListOfPolymers())) { /* get all elements of an rna */ if (monomernotation instanceof MonomerNotationUnitRNA) { for (MonomerNotationUnit unit : ((MonomerNotationUnitRNA) monomernotation).getContents()) { addAdHocMonomer(unit); } } else { addAdHocMonomer(monomernotation); } } /* give the adhocMonomer's information */ for (Monomer distinctmonomer : set) { Element monomerElement = MonomerParser.getMonomerElement(distinctmonomer); monomerListElement.getChildren().add(monomerElement); } root.addContent(monomerListElement); XMLOutputter xmlOutput = new XMLOutputter(); // display nice xmlOutput.setFormat(Format.getPrettyFormat()); return xmlOutput.outputString(doc); }
From source file:org.helm.notation2.tools.xHelmNotationExporter.java
License:Open Source License
/** * method to get xhelm for the helm notation, only if it was possible to * convert the helm in the old format//from w w w . j a v a 2s . co m * * @param helm2notation, HELM2Notation object * @return xhelm * @throws MonomerException * @throws HELM1FormatException * @throws JDOMException * @throws IOException * @throws NotationException * @throws CTKException * @throws ValidationException * @throws ChemistryException if the Chemistry Engine can not be initialized */ public static String getXHELM(HELM2Notation helm2notation) throws MonomerException, HELM1FormatException, IOException, JDOMException, NotationException, CTKException, ValidationException, ChemistryException { set = new HashSet<Monomer>(); Element root = new Element(xHelmNotationExporter.XHELM_ELEMENT); Document doc = new Document(root); Element helmElement = new Element(xHelmNotationExporter.HELM_NOTATION_ELEMENT); helmElement.setText(HELM1Utils.getStandard(helm2notation)); root.addContent(helmElement); Element monomerListElement = new Element(xHelmNotationExporter.MONOMER_LIST_ELEMENT); /* save all adhocMonomers in the set */ for (MonomerNotation monomernotation : MethodsMonomerUtils .getListOfMonomerNotation(helm2notation.getListOfPolymers())) { /* get all elements of an rna */ if (monomernotation instanceof MonomerNotationUnitRNA) { for (MonomerNotationUnit unit : ((MonomerNotationUnitRNA) monomernotation).getContents()) { addAdHocMonomer(unit); } } else { addAdHocMonomer(monomernotation); } } /* give adhoc monomer's information */ for (Monomer distinctmonomer : set) { Element monomerElement = MonomerParser.getMonomerElement(distinctmonomer); monomerListElement.getChildren().add(monomerElement); } root.addContent(monomerListElement); XMLOutputter xmlOutput = new XMLOutputter(); // display nice xmlOutput.setFormat(Format.getPrettyFormat()); return xmlOutput.outputString(doc); }
From source file:org.isima.carsharing.launcher.Launcher.java
public static void addConfigComment(SettingsDelegate settingsDelegate, File out) { try {/* w ww.j a v a 2 s. c o m*/ SAXBuilder builder = new SAXBuilder(); Document doc = (Document) builder.build(out); Element rootNode = doc.getRootElement(); Element rootNodeCopy = rootNode.clone(); doc.removeContent(rootNode); rootNodeCopy.detach(); Comment comment = new Comment(settingsDelegate.usedConfigsToXMLComment()); doc.addContent(comment); doc.addContent(rootNodeCopy); XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new FileWriter(out)); } catch (JDOMException | IOException ex) { Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex); } }