List of usage examples for org.jdom2.output Format getPrettyFormat
public static Format getPrettyFormat()
From source file:de.danielluedecke.zettelkasten.util.Tools.java
License:Open Source License
/** * This method returns the XML database as string. just for testing purposes. * @param dataObj//from w ww .ja va 2 s . c o m * @return */ public static String retrieveXMLFileAsString(Daten dataObj) { // create a new XML-outputter with the pretty output format, // so the xml-file looks nicer XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); // return XML data base as string return out.outputString(dataObj.getZknData()); }
From source file:de.danielluedecke.zettelkasten.ZettelkastenView.java
License:Open Source License
/** * /* w ww . j a v a 2s .c om*/ * @param exportlist * @param type */ private void exportList(LinkedList<String> exportlist, String type) { String formats = getResourceMap().getString("exportListFormat1") + "," + getResourceMap().getString("exportListFormat2") + "," + getResourceMap().getString("exportListFormat3"); if (type.equalsIgnoreCase("authors")) formats = formats + "," + getResourceMap().getString("exportListFormat4"); Object[] choice = formats.split(","); Object expo = JOptionPane.showInputDialog(getFrame(), getResourceMap().getString("exportListFormatMsg"), getResourceMap().getString("exportListFormatTitle"), JOptionPane.PLAIN_MESSAGE, null, choice, null); // check for valid return value or cancel-operation of user if (expo != null) { // convert object to string String exportformat = expo.toString(); // check for valid file extenstion if (exportformat.equalsIgnoreCase(getResourceMap().getString("exportListFormat4"))) exportformat = "bib"; // here we open a swing filechooser, in case the os ist no mac aqua File filepath = FileOperationsUtil.chooseFile(getFrame(), (settings.isMacAqua()) ? FileDialog.SAVE : JFileChooser.SAVE_DIALOG, JFileChooser.FILES_ONLY, null, null, getResourceMap().getString("exportListFormatTitle"), new String[] { "." + exportformat.toLowerCase() }, expo.toString(), settings); // if we have any valid if (filepath != null) { // init extension-string String ext = null; // retrieve fileextension, in case the user does not enter a fileextension later... if (exportformat.equals(getResourceMap().getString("exportListFormat1"))) ext = "." + getResourceMap().getString("exportListFormat1").toLowerCase(); if (exportformat.equals(getResourceMap().getString("exportListFormat2"))) ext = "." + getResourceMap().getString("exportListFormat2").toLowerCase(); if (exportformat.equals(getResourceMap().getString("exportListFormat3"))) ext = "." + getResourceMap().getString("exportListFormat3").toLowerCase(); if (exportformat.equals("bib")) ext = ".bib"; // check whether the user entered a file extension. if not, add "ext" as extension if (!filepath.getName().toLowerCase().endsWith(ext)) filepath = new File(filepath.getPath() + ext); // if file does not exist, create it - otherwise the getFilePath-method of // the settings-class would return "null" as filepath, if file doesn't exist if (!filepath.exists()) { try { filepath.createNewFile(); } catch (IOException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); } } else { // file exists, ask user to overwrite it... int optionDocExists = JOptionPane.showConfirmDialog(getFrame(), getResourceMap().getString("askForOverwriteFileMsg"), getResourceMap().getString("askForOverwriteFileTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); // if the user does *not* choose to overwrite, quit... if (optionDocExists != JOptionPane.YES_OPTION) return; } // create variable that indicates errors... boolean errorOccured = false; // sort list aphabetically before exporting it Collections.sort(exportlist, new Comparer()); // here startes the export of xml-data if (exportformat.equals(getResourceMap().getString("exportListFormat1"))) { // create new document Document exportfile = new Document(new Element(type)); // create list-iterator Iterator<String> i = exportlist.iterator(); // iterate exportlist while (i.hasNext()) { // create new element Element e = new Element(Daten.ELEMENT_ENTRY); // at element from the list e.setText(i.next()); // add element to the document exportfile.getRootElement().addContent(e); } // save the xml-file try { // open the outputstream FileOutputStream fos = new FileOutputStream(filepath); // create a new XML-outputter with the pretty output format, // so the xml-file looks nicer XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); try { // save the main-export-file out.output(exportfile, fos); // close the output stream fos.close(); } catch (IOException e) { // log error-message Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } } catch (FileNotFoundException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } } else if (exportformat.equals("bib")) { ByteArrayOutputStream bout = null; OutputStream exportfile = null; try { bout = bibtex.saveFile(); // create filewriter exportfile = new FileOutputStream(filepath); // retrieve string String bibdata = bout.toString("UTF-8"); // write content exportfile.write(bibdata.getBytes(Charset.forName("UTF-8"))); } catch (FileNotFoundException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; } finally { try { if (bout != null) bout.close(); if (exportfile != null) exportfile.close(); } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; } } } else { // create stringbuilder for the final content StringBuilder finalcontent = new StringBuilder(""); // create list-iterator Iterator<String> i = exportlist.iterator(); // here startes the export of txt-data if (exportformat.equals(getResourceMap().getString("exportListFormat2"))) { // iterate exportlist and copy each list-element to the string, separated by new lines while (i.hasNext()) finalcontent.append(i.next()).append(System.getProperty("line.separator")); } // here startes the export of html-data else if (exportformat.equals(getResourceMap().getString("exportListFormat3"))) { // init html-page finalcontent.append("<html><head></head><body><ol>") .append(System.getProperty("line.separator")); // iterate exportlist and copy each list-element to the string, separated by new lines while (i.hasNext()) { // create dummy string to convert German umlauts String dummy = i.next(); // convert special chars to html dummy = dummy.replace("&", "&"); dummy = dummy.replace("\"", """); dummy = dummy.replace("", "ä"); dummy = dummy.replace("", "Ä"); dummy = dummy.replace("", "ö"); dummy = dummy.replace("", "Ö"); dummy = dummy.replace("", "ü"); dummy = dummy.replace("", "Ü"); dummy = dummy.replace("", "ß"); // append converted author to stringbuilder finalcontent.append("<li>").append(dummy).append("</li>") .append(System.getProperty("line.separator")); } // close html-page finalcontent.append(System.getProperty("line.separator")).append("</ol></body></html>"); } // init output-filewriter Writer exportfile = null; try { // create filewriter exportfile = new FileWriter(filepath); // and save file to disk exportfile.write(finalcontent.toString()); } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } finally { try { // finally, close filewrite if (exportfile != null) { exportfile.close(); } } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } } } // if an errors occured, show error-log if (errorOccured) { showErrorIcon(); } else { JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("exportOkMsg"), getResourceMap().getString("exportOkTitle"), JOptionPane.PLAIN_MESSAGE); } } } }
From source file:de.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java
License:Creative Commons License
private static void write(EObject instance, Resource resource, OutputStream os, NonContainmentReferenceHandling refOption, Map<String, Object> saveOptions) throws IOException { if (refOption == null) { refOption = NonContainmentReferenceHandling.KEEP_ORIGINAL_LOCATION; }//from ww w . j a va2s . c om HashSet<EObject> alreadyVisited = new HashSet<EObject>(); List<EObject> rootList = new ArrayList<EObject>(); if (refOption == NonContainmentReferenceHandling.ADD_TO_RESOURCE) { instance = EmfUtils.clone(instance); resource.getContents().add(instance); collectObjectsWithoutResource(instance, alreadyVisited, rootList, refOption); resource.getContents().addAll(rootList); write(resource, os, saveOptions); } else if (refOption == NonContainmentReferenceHandling.KEEP_ORIGINAL_LOCATION) { instance = EcoreUtil.copy(instance); resource.getContents().add(instance); collectObjectsWithoutResource(instance, alreadyVisited, rootList, refOption); Resource resourceTemp = new XMLResourceFactoryImpl().createResource(URI.createURI("")); resourceTemp.getContents().addAll(rootList); write(resource, os, saveOptions); } else if (refOption == NonContainmentReferenceHandling.INLINE) { instance = EmfUtils.clone(instance); resource.getContents().add(instance); // Reads to DOM and injects dependencies(replaces href nodes) Document d; Map<String, Namespace> namespaces = new HashMap<String, Namespace>(); try { d = createDocFromEObject(instance, namespaces); Set<EObject> alreadyHandled = new HashSet<EObject>(); dfs(instance, d.getRootElement(), alreadyHandled, namespaces); for (String prefix : namespaces.keySet()) { Namespace namespace = d.getRootElement().getNamespace(prefix); if (namespace == null) d.getRootElement().addNamespaceDeclaration(namespaces.get(prefix)); } XMLOutputter out = new XMLOutputter(); out.setFormat(Format.getPrettyFormat()); out.output(d, os); } catch (Exception e) { logger.error("An error occured while serializing an object:\n" + e.getLocalizedMessage()); e.printStackTrace(); } } }
From source file:de.hbrs.oryx.yawl.util.YAWLUtils.java
License:Open Source License
static public String elementToString(final List<Element> list) { XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); return out.outputString(list); }
From source file:de.herm_detlef.java.application.io.Export.java
License:Apache License
public static Document exportExerciseItemListToFile(CommonData commonData, File file) { commonData.markSelectedAnswerPartItems(); final Document doc = createJdomDocument(commonData.getExerciseItemListMaster()); assert doc != null; XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); try {/*from w ww. ja v a2 s . co m*/ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1_000_000); xmlOutput.output(doc, outputStream); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); validateDocument(inputStream); xmlOutput.output(doc, new FileWriter(file.getCanonicalPath())); commonData.savedExerciseItemListMaster(); commonData.setRecentlySavedFile(file); commonData.setRecentlyOpenedFile(file); commonData.getExerciseItemListInitialMaster().clear(); commonData.getExerciseItemListInitialMaster().addAll(commonData.getExerciseItemListMaster()); } catch (IOException | JDOMException e) { Utilities.showErrorMessage(e.getClass().getSimpleName(), e.getMessage()); // e.printStackTrace(); return null; } return doc; }
From source file:de.huberlin.german.korpling.laudatioteitool.MergeTEI.java
License:Apache License
public void merge() throws LaudatioException { try {//from w w w .j a v a 2s . c o m if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { throw new LaudatioException( messages.getString("COULD NOT CREATE MERGED OUTPUTFILE: I CAN'T CREATE THE DIRECTORIES")); } Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element root = new Element("teiCorpus", teiNS); Element documentRoot = new Element("teiCorpus", teiNS); Element preparationRoot = new Element("teiCorpus", teiNS); mergeMainCorpusHeader(root); mergeDocumentHeader(documentRoot); mergePreparationHeader(preparationRoot); root.addContent(documentRoot); documentRoot.addContent(documentRoot.getChildren().size(), preparationRoot); Document mergedDoc = new Document(root); // output the new XML XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(mergedDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN MERGED TEI"), outputFile.getPath()); } catch (SAXException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } catch (JDOMException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } catch (IOException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } }
From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java
License:Apache License
private TEIValidator.Errors extractMainCorpusHeader(Document doc) throws LaudatioException, IOException, SAXException { TEIValidator validator = corpusSchemeURL == null ? new TEICorpusValidator() : new FromURLValidator(corpusSchemeURL); Element corpusHeader = doc.getRootElement().getChild("teiHeader", null); if (corpusHeader != null) { File corpusDir = new File(outputDirectory, "CorpusHeader"); if (!corpusDir.exists() && !corpusDir.mkdir()) { throw new LaudatioException( messages.getString("COULD NOT CREATE DIRECTORY") + corpusDir.getAbsolutePath()); }/* ww w .j a v a 2 s . c o m*/ // create the subtree for the global corpus header Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element newRootForCorpus = new Element("TEI", teiNS); newRootForCorpus.addContent(corpusHeader.clone()); Document corpusDoc = new Document(newRootForCorpus); if (corpusSchemeURL == null) { corpusDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + TEICorpusValidator.DEFAULT_SCHEME_URL + "\"")); } else { corpusDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + corpusSchemeURL + "\"")); } // we need to append an empty "text" element after the header Element text = new Element("text", teiNS); text.setText(""); newRootForCorpus.addContent(text); // we work with the copy from now corpusHeader = newRootForCorpus.getChild("teiHeader", null); Preconditions.checkNotNull(corpusHeader, messages.getString("ERROR NO CORPUS TITLE GIVEN")); Preconditions.checkState("CorpusHeader".equals(corpusHeader.getAttributeValue("type"))); Preconditions.checkNotNull(corpusHeader.getChild("fileDesc", null), messages.getString("ERROR NO CORPUS TITLE GIVEN")); Preconditions.checkNotNull(corpusHeader.getChild("fileDesc", null).getChild("titleStmt", null), messages.getString("ERROR NO CORPUS TITLE GIVEN")); String title = corpusHeader.getChild("fileDesc", null).getChild("titleStmt", null) .getChildTextNormalize("title", null); Preconditions.checkNotNull(title, messages.getString("ERROR NO CORPUS TITLE GIVEN")); // save the file with the title as file name File outputFile = new File(corpusDir, title + ".xml"); XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(corpusDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN CORPUS HEADER"), outputFile.getPath()); validator.validate(outputFile); } return validator.getErrors(); }
From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java
License:Apache License
private TEIValidator.Errors extractDocumentHeaders(Document doc) throws LaudatioException, IOException, SAXException { TEIValidator validator = documentSchemeURL == null ? new TEIDocumentValidator() : new FromURLValidator(documentSchemeURL); File documentDir = new File(outputDirectory, "DocumentHeader"); if (!documentDir.exists() && !documentDir.mkdir()) { throw new LaudatioException( messages.getString("COULD NOT CREATE DIRECTORY") + documentDir.getAbsolutePath()); }//from w ww .j a v a2 s . c o m Element documentRoot = Preconditions.checkNotNull(doc.getRootElement().getChild("teiCorpus", null)); for (Element docHeader : documentRoot.getChildren("teiHeader", null)) { Preconditions.checkState("DocumentHeader".equals(docHeader.getAttributeValue("type"))); // create the subtree for the global corpus header Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element tei = new Element("TEI", teiNS); tei.addContent(docHeader.clone()); Document newDoc = new Document(tei); if (documentSchemeURL == null) { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + TEIDocumentValidator.DEFAULT_SCHEME_URL + "\"")); } else { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + documentSchemeURL + "\"")); } // we need to append an empty "text" element after the header Element text = new Element("text", teiNS); text.setText(""); tei.addContent(text); Element fileDesc = Preconditions .checkNotNull(tei.getChild("teiHeader", null).getChild("fileDesc", null)); String outName = UUID.randomUUID().toString(); String id = fileDesc.getAttributeValue("id", Namespace.XML_NAMESPACE); if (id != null) { outName = id; } else { Element titleStmt = Preconditions.checkNotNull(fileDesc.getChild("titleStmt", null)); String title = titleStmt.getChildText("title", null); if (title != null) { outName = title; } } File outputFile = new File(documentDir, outName + ".xml"); XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(newDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN DOCUMENT HEADER"), outputFile.getPath()); validator.validate(outputFile); } return validator.getErrors(); }
From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java
License:Apache License
private TEIValidator.Errors extractPreparationSteps(Document doc) throws LaudatioException, IOException, SAXException { TEIValidator validator = preparationSchemeURL == null ? new TEIPreparationValidator() : new FromURLValidator(preparationSchemeURL); Multiset<String> knownPreparationTitles = HashMultiset.create(); File documentDir = new File(outputDirectory, "PreparationHeader"); if (!documentDir.exists() && !documentDir.mkdir()) { throw new LaudatioException( messages.getString("COULD NOT CREATE DIRECTORY") + documentDir.getAbsolutePath()); }/*from ww w. j av a2s.c om*/ Preconditions.checkNotNull(doc.getRootElement().getChild("teiCorpus", null)); Element preparationRoot = Preconditions .checkNotNull(doc.getRootElement().getChild("teiCorpus", null).getChild("teiCorpus", null)); for (Element preparationHeader : preparationRoot.getChildren("teiHeader", null)) { Preconditions.checkState("PreparationHeader".equals(preparationHeader.getAttributeValue("type"))); // create the subtree for the global corpus header Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element tei = new Element("TEI", teiNS); tei.addContent(preparationHeader.clone()); Document newDoc = new Document(tei); if (preparationSchemeURL == null) { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + TEIPreparationValidator.DEFAULT_SCHEME_URL + "\"")); } else { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + preparationSchemeURL + "\"")); } // we need to append an empty "text" element after the header Element text = new Element("text", teiNS); text.setText(""); tei.addContent(text); Element fileDesc = Preconditions .checkNotNull(tei.getChild("teiHeader", null).getChild("fileDesc", null)); String outName = UUID.randomUUID().toString(); Element titleStmt = Preconditions.checkNotNull(fileDesc.getChild("titleStmt", null)); Element title = Preconditions.checkNotNull(titleStmt.getChild("title", null)); String corresp = title.getAttributeValue("corresp"); if (corresp != null) { if (knownPreparationTitles.contains(corresp)) { knownPreparationTitles.add(corresp); outName = corresp + "_" + knownPreparationTitles.count(corresp); log.warn(messages.getString("MORE THAN ONE PREPARATION HEADER"), corresp); } else { outName = corresp; knownPreparationTitles.add(corresp); } } File outputFile = new File(documentDir, outName + ".xml"); XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(newDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN PREPARATION HEADER"), outputFile.getPath()); validator.validate(outputFile); } return validator.getErrors(); }
From source file:de.ing_poetter.binview.BinaryFormat.java
License:Open Source License
public void saveToFile(final File f) throws IOException { final Element root = new Element(ROOT_ELEMENT_NAME); for (int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final Element res = v.save(); root.addContent(res);/*from w ww . j a v a2 s .c o m*/ } final Document doc = new Document(root); final XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); final FileOutputStream bout = new FileOutputStream(f); xout.output(doc, bout); bout.flush(); bout.close(); }