List of usage examples for org.jdom2.input SAXBuilder SAXBuilder
public SAXBuilder()
From source file:de.danielluedecke.zettelkasten.tasks.importtasks.ImportFromZkx.java
License:Open Source License
@Override protected Object doInBackground() { // what we do here is importing new zettelkasten-data (.zkn3). // in the beginning, we simply load the data-file. but when appending // it to the existing data, we need to convert the author- and keyword- // index-numbers. therefore, for each entry the author and keyword-strings // are retrieved, added to the existing author and keyword-file, and the // new index-numbers replace the old ones. finally, when the complete // data-file is converted, it is appended to the existing data-file. //// w w w.j a v a 2 s .c o m // TODO unique-Zettel-IDs durch Verweise auf entsprechende Zettel (Zettelnummer) ersetzen. // dies gilt fr: // - Schreibtischdaten // - Suchergebnisse // create dummy-documents, where the imported data is stored. Document zkn3Doc = new Document(new Element("zettelkasten")); Document author3Doc = new Document(new Element("authors")); Document keyword3Doc = new Document(new Element(Daten.ELEMENT_KEYWORD)); Document bookmark3Doc = new Document(new Element("bookmarks")); Document search3Doc = new Document(new Element("searches")); Document desktop3Doc = new Document(new Element("desktops")); Document desktopModifiedEntries3Doc = new Document(new Element("modifiedEntries")); Document meta3Doc = new Document(new Element("metainformation")); try { // it looks like the SAXBuilder is closing an input stream. So we have to // re-open the ZIP-file each time we want to retrieve an XML-file from it // this is necessary, because we want tot retrieve the zipped xml-files // *without* temporarily saving them to harddisk for (int cnt = 0; cnt < dataObj.getFilesToLoadCount(); cnt++) { // open the zip-file ZipInputStream zip = new ZipInputStream(new FileInputStream(filepath)); ZipEntry zentry; // now iterate the zip-file, searching for the requested file in it while ((zentry = zip.getNextEntry()) != null) { String entryname = zentry.getName(); // if the found file matches the requested one, start the SAXBuilder if (entryname.equals(dataObj.getFileToLoad(cnt))) { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(zip); // compare, which file we have retrieved, so we store the data // correctly on our data-object if (entryname.equals(Constants.metainfFileName)) { meta3Doc = doc; } if (entryname.equals(Constants.zknFileName)) { zkn3Doc = doc; } if (entryname.equals(Constants.authorFileName)) { author3Doc = doc; } if (entryname.equals(Constants.keywordFileName)) { keyword3Doc = doc; } if (entryname.equals(Constants.bookmarksFileName)) { bookmark3Doc = doc; } if (entryname.equals(Constants.searchrequestsFileName)) { search3Doc = doc; } if (entryname.equals(Constants.desktopFileName)) { desktop3Doc = doc; } if (entryname.equals(Constants.desktopModifiedEntriesFileName)) { desktopModifiedEntries3Doc = doc; } break; } catch (JDOMException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } } } zip.close(); } // retrieve version-element Element ver_el = meta3Doc.getRootElement().getChild("version"); // store fileformat-information String importedFileFormat = ""; // check whether it's null or not if (null == ver_el) { taskinfo.setImportOk(false); } else { // get data-version of imported file importedFileFormat = ver_el.getAttributeValue("id"); float lv = Float.parseFloat(importedFileFormat); // get fileversion of backward compatibility // float cv = Float.parseFloat(currentFileFormat); float cv = Float.parseFloat(Daten.backwardCompatibleVersion); // check whether the current data-version is newer than the loaded one taskinfo.setImportOk(lv >= cv); } // if we have not the right file-format, tell this the user... if (!taskinfo.isImportOk()) { // log error-message Constants.zknlogger.log(Level.WARNING, "Failed when importing Zettelkasten-data. Import-Fileversion: {0} Requested Fileversion: {1}", new Object[] { importedFileFormat, Daten.backwardCompatibleVersion }); // display error message box JOptionPane.showMessageDialog(null, resourceMap.getString("importDlgErrWrongFileFormat", Daten.backwardCompatibleVersion, importedFileFormat), resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE); // leave thread return null; } // remove all entries with identical ID, because we can't have these entries twice // in the database. if the user wants to update entries (with same IDs), the synch feature // can be used. removeDoubleEntries(zkn3Doc); // get the length of the data final int len = zkn3Doc.getRootElement().getContentSize(); // reset the progressbar setProgress(0, 0, len); msgLabel.setText(resourceMap.getString("importDlgMsgEdit")); // // at first, add the description of the new importet zettelkasten // // get the child element Element el = meta3Doc.getRootElement().getChild(Daten.ELEMEMT_DESCRIPTION); // if we have any element, add description if (el != null) { dataObj.addZknDescription(el.getText()); } // // now, convert the old index-numbers of the authors and keywords // to the new numbers and add the entries to the existing data file // // go through all entries and prepare them and add them to the // main data file. especially the new author- and keyword-index-numbers // have to be prepared for (int cnt = 0; cnt < len; cnt++) { // get each child Element z = (Element) zkn3Doc.getRootElement().getContent(cnt); // we only need to convert the author- and keyword-index-numbers. // first we start with the author-index-numbers... // if the author-element is not empty... if (!z.getChild(Daten.ELEMENT_AUTHOR).getText().isEmpty()) { // ...get the autors indexnumbers String[] aun = z.getChild(Daten.ELEMENT_AUTHOR).getText().split(","); // create new stringbuilder that will contain the new index-numbers StringBuilder sb = new StringBuilder(""); // iterate the array for (int c = 0; c < aun.length; c++) { // get the related author-element from the author-file. // the needed author-index-number is stored as integer (string-value) // in the author-indexnumbers-array "aun". Element dummyauthor = (Element) author3Doc.getRootElement() .getContent(Integer.parseInt(aun[c]) - 1); // get the string value for that author String authorstring = dummyauthor.getText(); // if we have any author, go on.. if (!authorstring.isEmpty()) { // add author to the data file // and store the position of the new added author in the // variable authorPos int authorPos = dataObj.addAuthor(authorstring, 1); // store author position as string value sb.append(String.valueOf(authorPos)); sb.append(","); } } // truncate last comma if (sb.length() > 1) { sb.setLength(sb.length() - 1); } // set new author-index-numbers z.getChild(Daten.ELEMENT_AUTHOR).setText(sb.toString()); } // now that the authors are converted, we need to convert // the keyword-index-numbers // if the keyword-element is not empty... if (!z.getChild(Daten.ELEMENT_KEYWORD).getText().isEmpty()) { // ...get the keywords-index-numbers String[] kwn = z.getChild(Daten.ELEMENT_KEYWORD).getText().split(","); // create new stringbuilder that will contain the new index-numbers StringBuilder sb = new StringBuilder(""); // iterate the array for (int c = 0; c < kwn.length; c++) { // get the related keyword-element from the keyword-file. // the needed keyword-index-number is stored as integer (string-value) // in the keyword-indexnumbers-array "kwn". Element dummykeyword = (Element) keyword3Doc.getRootElement() .getContent(Integer.parseInt(kwn[c]) - 1); // get the string value for that keyword String keywordstring = dummykeyword.getText(); // if we have any keywords, go on.. if (!keywordstring.isEmpty()) { // add it to the data file // and store the position of the new added keyword in the // variable keywordPos int keywordPos = dataObj.addKeyword(keywordstring, 1); // store author position as string value sb.append(String.valueOf(keywordPos)); sb.append(","); } } // truncate last comma if (sb.length() > 1) { sb.setLength(sb.length() - 1); } // set new keyword-index-numbers z.getChild(Daten.ELEMENT_KEYWORD).setText(sb.toString()); } // update progressbar setProgress(cnt, 0, len); } // now that all entries are converted, append the data to the existing file dataObj.appendZknData(zkn3Doc); // TODO append desktop-data // TODO append search-data // append bookmarks bookmarksObj.appendBookmarks(dataObj, bookmark3Doc); } catch (IOException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } return null; // return your result }
From source file:de.danielluedecke.zettelkasten.tasks.LoadFileTask.java
License:Open Source License
@Override protected Object doInBackground() { // Your Task's code here. This method runs // on a background thread, so don't reference // the Swing GUI from here. // prevent task from processing when the file path is incorrect // init status text msgLabel.setText(resourceMap.getString("msg1")); // get the file path from the data file which has to be opened File fp = settingsObj.getFilePath(); // if no file exists, exit task if (null == fp || !fp.exists()) { // log error Constants.zknlogger.log(Level.WARNING, "Filepath is null or does not exist!"); return null; }/*from w w w. ja v a 2 s .c om*/ try { // reset the zettelkasten-data-files dataObj.initZettelkasten(); desktopObj.clear(); bookmarkObj.clear(); searchrequestsObj.clear(); // log file path Constants.zknlogger.log(Level.INFO, "Opening file {0}", fp.toString()); // it looks like the SAXBuilder is closing an input stream. So we have to // re-open the ZIP-file each time we want to retrieve an XML-file from it // this is necessary, because we want tot retrieve the zipped xml-files // *without* temporarily saving them to harddisk for (int cnt = 0; cnt < dataObj.getFilesToLoadCount(); cnt++) { // show status text switch (cnt) { case 0: case 1: msgLabel.setText(resourceMap.getString("msg1")); break; case 2: msgLabel.setText(resourceMap.getString("msg2")); break; case 3: msgLabel.setText(resourceMap.getString("msg3")); break; case 4: msgLabel.setText(resourceMap.getString("msg4")); break; case 5: msgLabel.setText(resourceMap.getString("msg5")); break; case 6: case 7: msgLabel.setText(resourceMap.getString("msg6")); break; default: msgLabel.setText(resourceMap.getString("msg1")); break; } // open the zip-file ZipInputStream zip = new ZipInputStream(new FileInputStream(fp)); ZipEntry entry; // now iterate the zip-file, searching for the requested file in it while ((entry = zip.getNextEntry()) != null) { // get filename of zip-entry String entryname = entry.getName(); // if the found file matches the requested one, start the SAXBuilder if (entryname.equals(dataObj.getFileToLoad(cnt))) { if (entryname.equals(Constants.bibTexFileName)) { bibtexObj.openFile(zip, "UTF-8"); Constants.zknlogger.log(Level.INFO, "{0} data successfully opened.", entryname); zip.close(); break; } else { try { SAXBuilder builder = new SAXBuilder(); // Document doc = new Document(); Document doc = builder.build(zip); // compare, which file we have retrieved, so we store the data // correctly on our data-object if (entryname.equals(Constants.metainfFileName)) dataObj.setMetaInformationData(doc); if (entryname.equals(Constants.zknFileName)) dataObj.setZknData(doc); if (entryname.equals(Constants.authorFileName)) dataObj.setAuthorData(doc); if (entryname.equals(Constants.keywordFileName)) dataObj.setKeywordData(doc); if (entryname.equals(Constants.bookmarksFileName)) bookmarkObj.setBookmarkData(doc); if (entryname.equals(Constants.searchrequestsFileName)) searchrequestsObj.setSearchData(doc); if (entryname.equals(Constants.desktopFileName)) desktopObj.setDesktopData(doc); if (entryname.equals(Constants.desktopModifiedEntriesFileName)) desktopObj.setDesktopModifiedEntriesData(doc); if (entryname.equals(Constants.desktopNotesFileName)) desktopObj.setDesktopNotesData(doc); if (entryname.equals(Constants.synonymsFileName)) synonymsObj.setDocument(doc); // tell about success Constants.zknlogger.log(Level.INFO, "{0} data successfully opened.", entryname); break; } catch (JDOMException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } } } } zip.close(); } // tell about success Constants.zknlogger.log(Level.INFO, "Complete data file successfully opened."); } catch (IOException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } return null; // return your result }
From source file:de.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java
License:Creative Commons License
/** * Serialize an object to XML using standard EMF * /*from w ww .j a v a 2 s . c om*/ * @param object * @return * @throws Exception */ private static Document createDocFromEObject(EObject object, Map<String, Namespace> namespaces) throws Exception { HashMap<String, Object> options = new HashMap<String, Object>(); options.put(XMIResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.FALSE); options.put(XMIResource.OPTION_DECLARE_XML, Boolean.FALSE); options.put(XMLResource.OPTION_FORMATTED, Boolean.FALSE); options.put(XMLResource.OPTION_KEEP_DEFAULT_CONTENT, Boolean.TRUE); String result = writeToString(object, NonContainmentReferenceHandling.KEEP_ORIGINAL_LOCATION, options); Document doc = null; try { doc = new SAXBuilder().build(new StringReader(result)); Namespace namespace = doc.getRootElement().getNamespace(); if (!namespaces.containsKey(namespace.getPrefix())) namespaces.put(namespace.getPrefix(), namespace); for (Namespace additionalNamespace : doc.getRootElement().getAdditionalNamespaces()) { if (!namespaces.containsKey(additionalNamespace.getPrefix())) namespaces.put(additionalNamespace.getPrefix(), additionalNamespace); } } catch (Exception e) { logger.error(e.getMessage()); assert (false); } return doc; }
From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutArranger.java
License:Open Source License
public Element arrangeLayout(Element root) throws JDOMException, IOException { sb = new StringBuilder(); sb.append("<layout>"); sb.append("<specification id=\"Initial\">"); sb.append("<size w=\"1000\" h=\"1000\"/>"); List<Element> specifications = root.getChildren("specification", root.getNamespace()); for (Element specification : specifications) { List<Element> decompositions = specification.getChildren("decomposition", root.getNamespace()); for (Element yawlDecomposition : decompositions) { createNet(yawlDecomposition); }/*www. java 2 s . c o m*/ } sb.append("<labelFontSize>12</labelFontSize>"); sb.append("</specification>"); sb.append("</layout>"); String XMLLayoutContent = sb.toString(); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(new StringReader(XMLLayoutContent)); return document.getRootElement(); }
From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutConverter.java
License:Open Source License
private void initXMLReader() throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder(); Document document = builder.build(new StringReader(specificationString)); Element root = document.getRootElement(); layout = root.getChild("layout", root.getNamespace()); if (layout == null) layout = yawlLayoutArranger.arrangeLayout(root); yawlNamespace = layout.getNamespace(); setYAWLLocale(layout);//from ww w . j av a2s. com }
From source file:de.huberlin.german.korpling.laudatioteitool.MergeTEI.java
License:Apache License
private void mergeMainCorpusHeader(Element root) throws SAXException, IOException, LaudatioException, JDOMException { // append global header File corpusHeaderDir = new File(inputDir, "CorpusHeader"); Preconditions.checkArgument(corpusHeaderDir.isDirectory()); File[] corpusHeaderFiles = corpusHeaderDir.listFiles(new FilenameFilter() { @Override/*from w w w. ja va 2 s.com*/ public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); Preconditions.checkArgument(corpusHeaderFiles.length > 0); File headerFile = corpusHeaderFiles[0]; TEIValidator validator = corpusSchemeURL == null ? new TEICorpusValidator() : new FromURLValidator(corpusSchemeURL); if (validator.validate(headerFile)) { SAXBuilder sax = new SAXBuilder(); Document corpusDoc = sax.build(headerFile); // remove the pending text element corpusDoc.getRootElement().removeChild("text", null); // append to our new root root.addContent(corpusDoc.getRootElement().getChild("teiHeader", null).clone()); } else { System.err.println(validator.toString()); throw new LaudatioException("Corpus header is not valid"); } }
From source file:de.huberlin.german.korpling.laudatioteitool.MergeTEI.java
License:Apache License
private void mergeDocumentHeader(Element root) throws SAXException, JDOMException, IOException, LaudatioException { // append document headers File documentHeaderDir = new File(inputDir, "DocumentHeader"); Preconditions.checkArgument(documentHeaderDir.isDirectory()); File[] documentHeaderFiles = documentHeaderDir.listFiles(new FilenameFilter() { @Override/* w w w . j a va2s . c o m*/ public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); Preconditions.checkArgument(documentHeaderFiles.length > 0); SAXBuilder sax = new SAXBuilder(); TEIValidator validator = documentSchemeURL == null ? new TEIDocumentValidator() : new FromURLValidator(documentSchemeURL); for (File f : documentHeaderFiles) { if (validator.validate(f)) { Document documentDoc = sax.build(f); // remove the pending text element documentDoc.getRootElement().removeChild("text", null); // append to our new root root.addContent(documentDoc.getRootElement().getChild("teiHeader", null).clone()); } else { System.err.println(validator.toString()); throw new LaudatioException("A document header is not valid"); } } }
From source file:de.huberlin.german.korpling.laudatioteitool.MergeTEI.java
License:Apache License
private void mergePreparationHeader(Element root) throws SAXException, JDOMException, IOException, LaudatioException { // append preparation headers File preparationHeaderDir = new File(inputDir, "PreparationHeader"); Preconditions.checkState(preparationHeaderDir.isDirectory()); File[] preparationHeaderFiles = preparationHeaderDir.listFiles(new FilenameFilter() { @Override/*from w ww .j a va2 s .co m*/ public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); Preconditions.checkState(preparationHeaderFiles.length > 0); SAXBuilder sax = new SAXBuilder(); TEIValidator validator = preparationSchemeURL == null ? new TEIPreparationValidator() : new FromURLValidator(preparationSchemeURL); for (File f : preparationHeaderFiles) { if (validator.validate(f)) { Document preparation = sax.build(f); // remove the pending text element preparation.getRootElement().removeChild("text", null); // append to our new root root.addContent(preparation.getRootElement().getChild("teiHeader", null).clone()); } else { System.err.println(validator.toString()); throw new LaudatioException("A preparation header ist not valid."); } } }
From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java
License:Apache License
public void split() throws LaudatioException { if (!outputDirectory.isDirectory() && !outputDirectory.mkdirs()) { throw new LaudatioException(messages.getString("COULD NOT CREATE OUTPUT DIRECTORY.")); }//w w w . java 2 s . c o m // check if input file exits if (!inputFile.isFile()) { throw new LaudatioException(messages.getString("INPUT FILE DOES NOT EXIST")); } // read in file SAXBuilder sax = new SAXBuilder(); try { Document doc = sax.build(inputFile); TEIValidator.Errors errors = new TEIValidator.Errors(); errors.putAll(extractMainCorpusHeader(doc)); errors.putAll(extractDocumentHeaders(doc)); errors.putAll(extractPreparationSteps(doc)); if (!errors.isEmpty()) { System.out.println(TEIValidator.formatParserExceptions(errors)); throw new LaudatioException("Source document was invalid"); } } catch (JDOMException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } catch (SAXException ex) { throw new LaudatioException(TEIValidator.getSAXParserError(ex)); } catch (IOException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } }
From source file:de.ing_poetter.binview.BinaryFormat.java
License:Open Source License
public static BinaryFormat loadFromFile(final File f) { final SAXBuilder builder = new SAXBuilder(); Document doc;/*from w w w. ja v a 2 s . c o m*/ try { doc = builder.build(f); Element root = null; root = doc.getRootElement(); if (false == ROOT_ELEMENT_NAME.equalsIgnoreCase(root.getName())) { System.err.println("Format has invalid root Element of " + root.getName()); return null; } final BinaryFormat res = new BinaryFormat(); final List<Element> vars = root.getChildren(); for (int i = 0; i < vars.size(); i++) { final Element curVar = vars.get(i); final Variable v = VariableFactory.createVariableFrom(curVar); res.addVariable(v); } return res; } catch (final JDOMException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } return null; }