List of usage examples for org.jdom2 Document getRootElement
public Element getRootElement()
Element
for this Document
From source file:de.danielluedecke.zettelkasten.database.Daten.java
License:Open Source License
/** * This method appends a document with zettelkasten-data to an existing * document.<br><br>/*w w w . j a v a2 s . co m*/ * This method is used when importing data. The imported data is appended * to an existing, opened data file. * * @param zkd the zettelkasten-data in xml-document-format */ public void appendZknData(Document zkd) { // get current count, so we know at which position new entry were added // to the XML-document int currentpos = getCount(ZKNCOUNT); // create zettel element Element zettel; // dummy variable boolean mod = false; // remove each element. we need to use the remove-content-method, because // this detached the element from its former parent, so it can be added // to the new main-data-file // check whether we have any content left... while (zkd.getRootElement().getContentSize() > 0) { // try to remove/detach the child-element if ((zettel = (Element) zkd.getRootElement().removeContent(0)) != null) { // check whether the imported entry is empty or not if (zettel.getChild(ELEMENT_CONTENT) != null && !zettel.getChild(ELEMENT_CONTENT).getText().isEmpty()) { try { zknFile.getRootElement().addContent(zettel); // set modified flag mod = true; } catch (IllegalDataException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); } catch (IllegalAddException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); } } } } // check whether we have added any new entries // if so, re-convert IDs to numbers if (mod) { // go through all new added entries for (int cnt = currentpos + 1; cnt <= getCount(ZKNCOUNT); cnt++) { // retrieve each new added entry zettel = retrieveZettel(cnt); // set back reference to current last entry setPrevZettel(cnt, getLastZettel()); // set pointer from current last entry to this new imported/added entry setNextZettel(getLastZettel(), cnt); // set pointer from first entry to this entry setPrevZettel(getFirstZettel(), cnt); // set next pointer from this entry to first entry setNextZettel(cnt, getFirstZettel()); // set this entry as new last entry setLastZettel(cnt); // // here we change the entry's luhmann-numbers (trailing entries) and the // entry's manual links with the unique IDs // replaceAttributeIDWithNr(zettel); // // here we convert back the author IDs in footnote references // to the related author index numbers... // // retrieve content of entry and convert all author footnotes, which // contain author-index-numbers, into the related author-IDs. String content = zettel.getChild(ELEMENT_CONTENT).getText(); // check for footnotes int pos = 0; while (pos != -1) { // find the html-tag for the footnote pos = content.indexOf(Constants.FORMAT_FOOTNOTE_OPEN, pos); // if we found something... if (pos != -1) { // find the closing quotes int end = content.indexOf("]", pos + 2); // if we found that as well... if (end != -1) { try { // extract footnote-number String fn = content.substring(pos + 4, end); // retrieve author ID from related footnote number try { int authorNr = getAuthorNumberFromID(fn); // replace author number with author ID inside footnote content = content.substring(0, pos + 4) + String.valueOf(authorNr) + content.substring(end); } catch (NumberFormatException ex) { // log error Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); Constants.zknlogger.log(Level.WARNING, "Could not convert author ID into author number!"); } } catch (IndexOutOfBoundsException ex) { } // and add it to the linked list, if it doesn't already exist // set pos to new position pos = end; } else { pos = pos + 4; } } } // check for manual links pos = 0; while (pos != -1) { // find the html-tag for the manual link pos = content.indexOf(Constants.FORMAT_MANLINK_OPEN, pos); // if we found something... if (pos != -1) { // find the closing quotes int end = content.indexOf("]", pos + 2); // if we found that as well... if (end != -1) { try { // extract manual-link--number String ml = content.substring(pos + 3, end); // retrieve entry ID from related manual link number try { int zetNr = getZettelNumberFromID(ml); // replace author number with author ID inside footnote content = content.substring(0, pos + 3) + String.valueOf(zetNr) + content.substring(end); } catch (NumberFormatException ex) { // log error Constants.zknlogger.log(Level.WARNING, "Could not convert entry ID into related manual link number!"); } } catch (IndexOutOfBoundsException ex) { } // and add it to the linked list, if it doesn't already exist // set pos to new position pos = end; } else { pos = pos + 3; } } } // set back changes zettel.getChild(ELEMENT_CONTENT).setText(content); } } // change modified state if (mod) { setModified(true); } }
From source file:de.danielluedecke.zettelkasten.database.Daten.java
License:Open Source License
/** * This function retrieves an element of a xml document at a given * position. used for other methods like getAuthor or * getKeyword.<br><br>/*www . ja v a2s.c om*/ * <b>Caution!</b> The position {@code pos} is a value from <b>1</b> to * {@link #getCount(int) getCount()} - in contrary * to usual array handling where the range is from 0 to (size-1). * * @param doc the xml document where to look for elements. use following parameters:<br> * - {@link #authorFile authorFile}<br> * - {@link #keywordFile keywordFile}<br> * - {@link #zknFile zknFile} * @param pos the position of the element. must be a value from <b>1</b> to * {@link #getCount(int) getCount()}. * @return the element if a match was found, otherwise {@code null} */ private Element retrieveElement(Document doc, int pos) { // create a list of all elements from the given xml file try { List<?> elementList = doc.getRootElement().getContent(); // and return the requestet Element try { return (Element) elementList.get(pos - 1); } catch (IndexOutOfBoundsException e) { return null; } } catch (IllegalStateException e) { Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage()); return null; } }
From source file:de.danielluedecke.zettelkasten.database.Daten.java
License:Open Source License
/** * This method searches the keyword-xml-file or author-xml-file for empty elements and returns the * number of the first empty element, if any. empty elements occur, when the user * deletes a keyword or author. in this case, to keep the permanent index-number of the other * keywords and authors, the keyword-/author-element is not completely removed, but only the text is * removed.//from www.jav a2s. c o m * * @param the xml-document (either <i>keywordFile</i> or <i>authorFile</i>) * @return the number of the first empty element, or -1 if no empty element was found */ private int retrieveFirstEmptyElement(Document doc) { // create a list of all elements from the given xml file try { List<?> elementList = doc.getRootElement().getContent(); // and an iterator for the loop below Iterator<?> iterator = elementList.iterator(); // counter for the return value if a found author matches the parameter int cnt = 1; // iterare all elements while (iterator.hasNext()) { Element el = (Element) iterator.next(); // if author matches the parameter string, return the position if (el.getText().isEmpty()) { return cnt; } // else increase counter cnt++; } // if no author was found, return -1 return -1; } catch (IllegalStateException e) { Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage()); return -1; } }
From source file:de.danielluedecke.zettelkasten.database.Daten.java
License:Open Source License
/** * This method returns the size of one of the xml data files. Following constants should * be used as parameters:<br>/* www.ja v a2 s . c o m*/ * ZKNCOUNT<br> * KWCOUNT<br> * AUCOUNT<br> * * @param what (uses constants, see global field definition at top of source) * @return the size of the requested data file */ public int getCount(int what) { Document doc; // check which file to count switch (what) { case ZKNCOUNT: doc = zknFile; break; case KWCOUNT: doc = keywordFile; break; case AUCOUNT: doc = authorFile; break; default: doc = zknFile; break; } // return XML file size return doc.getRootElement().getContentSize(); }
From source file:de.danielluedecke.zettelkasten.database.DesktopData.java
License:Open Source License
/** * This method archives the desktop-data of the desktop with the name {@code name} to a * zipped xml-file. The file contains the desktop-data, the modifed-entries-data for those entries * that appear on the desktop and the saved desktop-notes. * * @param name the name of the desktop that should be archived. * @return the archived document as XML-focument, or {@code null} if an error occured. *//*w ww. j a va 2s . c o m*/ public Document archiveDesktop(String name) { // create new document Document archive = new Document(new Element("archivedDesktop")); // add desktop-element of desktop that should be archived Element deskel = getDesktopElement(name); // if we found a valid value, go on if (deskel != null) { try { // set name attribute archive.getRootElement().setAttribute("name", name); // create desktop-element Element content_desktop = new Element("desktop"); // clone content from current desktop content_desktop.addContent(deskel.cloneContent()); // add element to archive-file archive.getRootElement().addContent(content_desktop); // now retrieve desktop-notes Element noteel = getDesktopNotes(name); // if we found a valid value, go on if (noteel != null) { // create notes-element Element content_notes = new Element("desktopNotes"); // clone content from current desktop-notes content_notes.addContent(noteel.cloneContent()); // add content archive.getRootElement().addContent(content_notes); } // now retrieve all timestamps from the archived desktop // and look for modified entries... // create new list that will contain the timestamps timestampList = new ArrayList<String>(); // fill list with all entry-numbers. since we have sub-bullets/levels, we // recursevly go through the desktop-data retrieveDesktopEntriesTimestamps(deskel); // if we have any results, go on... if (timestampList.size() > 0) { // create base element Element modifiedel = new Element("modifiedEntries"); // add all modified entries that appear on the archived desktop String[] timestamps = timestampList.toArray(new String[timestampList.size()]); for (String ts : timestamps) { // retrieve modifed entry Element me_dummy = retrieveModifiedEntryElementFromTimestamp(ts); // check for valid value if (me_dummy != null) { // crate new modified-entry-element Element me = new Element(ELEMENT_ENTRY); // set timestamp-attribute me.setAttribute(ATTR_TIMESTAMP, ts); // and add modified text me.setText(me_dummy.getText()); // and add content modifiedel.addContent(me); } } archive.getRootElement().addContent(modifiedel); } } catch (IllegalNameException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); return null; } catch (IllegalDataException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); return null; } catch (IllegalAddException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); return null; } } return archive; }
From source file:de.danielluedecke.zettelkasten.database.DesktopData.java
License:Open Source License
/** * This method imports an archived desktop-file and appends it to the current desktop-data. * desktop-content, desktop-notes and modifed entries are being added. * @param archive the archive-file as xml-Document * @return one of the following return values:<br> * <ul>/*from w ww.j a v a 2 s. co m*/ * <li>{@link #IMPORT_ARCHIVE_OK IMPORT_ARCHIVE_OK} in case the import was successful</li> * <li>{@link #IMPORT_ARCHIVE_ERR_DESKTOPNAME_EXISTS IMPORT_ARCHIVE_ERR_DESKTOPNAME_EXISTS} in case * the desktop-name already exists, so the user is asked to enter another name</li>> * <li>{@link #IMPORT_ARCHIVE_ERR_OTHER IMPORT_ARCHIVE_ERR_OTHER} in case a general error occured</li> * </ul> */ public int importArchivedDesktop(Document archive) { // get imported desktopname String name = archive.getRootElement().getAttributeValue("name"); // check whether we have any name at all. if not, return false if (null == name || name.isEmpty()) return IMPORT_ARCHIVE_ERR_DESKTOPNAME_EXISTS; // first of all, go through all desktops and check whether the name // already exist, to avoid double naming... // when such a desktopname as "name" already exists, return false for (int cnt = 0; cnt < getCount(); cnt++) if (name.equalsIgnoreCase(getDesktopName(cnt))) return IMPORT_ARCHIVE_ERR_DESKTOPNAME_EXISTS; // create new element Element d = new Element("desktop"); try { // set the desktop's name as attribute d.setAttribute("name", name); // get desktop-content from archive d.addContent(archive.getRootElement().getChild("desktop").cloneContent()); // add the element to the desktop desktop.getRootElement().addContent(d); // set currentDesktop index to the new desktop-element currentDesktop = desktop.getRootElement().getContentSize() - 1; // also add new desktop-notes-element Element desk = new Element("desktop"); // set name attribute desk.setAttribute("name", name); // create notes elements Element n1 = new Element("notes1"); Element n2 = new Element("notes2"); Element n3 = new Element("notes3"); // get notes-child Element noteschild = archive.getRootElement().getChild("desktopNotes"); // check whether we have any content if (noteschild != null) { // get and add notes... Element nc1 = noteschild.getChild("notes1"); if (nc1 != null) n1.setText(nc1.getText()); // get and add notes... Element nc2 = noteschild.getChild("notes2"); if (nc2 != null) n2.setText(nc2.getText()); // get and add notes... Element nc3 = noteschild.getChild("notes3"); if (nc3 != null) n3.setText(nc3.getText()); } // add notes-sub-elements desk.addContent(n1); desk.addContent(n2); desk.addContent(n3); // add element to desktop-notes desktopNotes.getRootElement().addContent(desk); // finally, add modified entries... List<Element> modent = archive.getRootElement().getChild("modifiedEntries").getChildren(); // create iterator Iterator<Element> modit = modent.iterator(); // and add all mofied entries while (modit.hasNext()) { // get element Element mod = modit.next(); // and add modified entry addModifiedEntry(mod.getAttributeValue(ATTR_TIMESTAMP), mod.getText()); } setModified(true); } catch (IllegalNameException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); return IMPORT_ARCHIVE_ERR_OTHER; } catch (IllegalDataException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); return IMPORT_ARCHIVE_ERR_OTHER; } catch (IllegalAddException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); return IMPORT_ARCHIVE_ERR_OTHER; } return IMPORT_ARCHIVE_OK; }
From source file:de.danielluedecke.zettelkasten.database.Synonyms.java
License:Open Source License
public void appendSynonyms(Document syndoc) { int count = syndoc.getRootElement().getContentSize(); for (int i = 0; i < count; i++) { String[] synline = getSynonymLine(syndoc, i, false); addSynonym(synline);//w w w. java2 s .c om } }
From source file:de.danielluedecke.zettelkasten.database.Synonyms.java
License:Open Source License
private Element retrieveElement(Document doc, int pos) { // create a list of all elements from the given xml file try {//from w w w. ja v a2s . co m List<?> elementList = doc.getRootElement().getContent(); // and return the requestet Element try { return (Element) elementList.get(pos); } catch (IndexOutOfBoundsException e) { return null; } } catch (IllegalStateException e) { Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage()); return null; } }
From source file:de.danielluedecke.zettelkasten.DesktopFrame.java
License:Open Source License
@Action public void importArchivedDesktop() { // create document Document archive = new Document(); // retrieve last used importdirectory File importdir = settingsObj.getFilePath(); // let user choose filepath File filepath = FileOperationsUtil.chooseFile(this, (settingsObj.isMacAqua()) ? FileDialog.LOAD : JFileChooser.OPEN_DIALOG, JFileChooser.FILES_ONLY, (null == importdir) ? null : importdir.getPath(), (null == importdir) ? null : importdir.getName(), resourceMap.getString("openArchiveTitle"), new String[] { ".zip" }, "Zip", settingsObj); // if we have a valid file, go on if (filepath != null && filepath.exists()) { try {/* ww w . j av a2 s.c om*/ // open the zip-file ZipInputStream zip = new ZipInputStream(new FileInputStream(filepath)); 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(Constants.archivedDesktopFileName)) { try { SAXBuilder builder = new SAXBuilder(); archive = builder.build(zip); break; } catch (JDOMException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } } } zip.close(); // tell about success Constants.zknlogger.log(Level.INFO, "Desktop archive successfully opened."); } catch (IOException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); // show error message dialog JOptionPane.showMessageDialog(this, resourceMap.getString("openArchiveDlgErr"), resourceMap.getString("openArchiveDlgTitle"), JOptionPane.PLAIN_MESSAGE); // and show error log zknframe.showErrorIcon(); return; } // init variables that indicate the success of the import-progress boolean finished = false; // we have a loop here, because the desktop-name of the imported archiv might already exist. // in this case, the user can retry with new names, until a new name was entered, or the // user cancels the action while (!finished) { // import archive int result = desktopObj.importArchivedDesktop(archive); // here we go on in case the desktop-name of the imported archive // already exists. in this case, the user shoould rename the archive if (DesktopData.IMPORT_ARCHIVE_ERR_DESKTOPNAME_EXISTS == result) { // desktop-name already existed, so desktop was not added... JOptionPane.showMessageDialog(this, resourceMap.getString("errDesktopNameExistsMsg", archive.getRootElement().getAttributeValue("name")), resourceMap.getString("errDesktopNameExistsTitle"), JOptionPane.PLAIN_MESSAGE); // user-input for new desktop-description String newDeskName = (String) JOptionPane.showInputDialog(this, resourceMap.getString("newDesktopMsg"), resourceMap.getString("newDesktopTitle"), JOptionPane.PLAIN_MESSAGE); // check for valid-return value, or if the user cancelled the action if (newDeskName != null && !newDeskName.isEmpty()) { // if everything was ok, set new name archive.getRootElement().setAttribute("name", newDeskName); } else { // else user has cancelled process JOptionPane.showMessageDialog(this, resourceMap.getString("openArchiveCancelled"), resourceMap.getString("openArchiveDlgTitle"), JOptionPane.PLAIN_MESSAGE); return; } } else if (DesktopData.IMPORT_ARCHIVE_ERR_OTHER == result) { // tell user about problem JOptionPane.showMessageDialog(this, resourceMap.getString("openArchiveError"), resourceMap.getString("openArchiveDlgTitle"), JOptionPane.PLAIN_MESSAGE); // and show error log zknframe.showErrorIcon(); return; } else if (DesktopData.IMPORT_ARCHIVE_OK == result) { // everything is ok, so quit while-loop finished = true; } } // show success JOptionPane.showMessageDialog(this, resourceMap.getString("openArchiveOK"), resourceMap.getString("openArchiveTitle"), JOptionPane.PLAIN_MESSAGE); // and update combo box updateComboBox(false); } }
From source file:de.danielluedecke.zettelkasten.tasks.export.ExportToXmlTask.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 // if no file exists, exit task if (null == filepath) { showOkMessage = false;/*from www.ja v a 2 s . c o m*/ return null; } // check whether file already exists if (filepath.exists()) { // file exists, ask user to overwrite it... int optionDocExists = JOptionPane.showConfirmDialog(null, resourceMap.getString("askForOverwriteFileMsg", "", filepath.getName()), resourceMap.getString("askForOverwriteFileTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); // if the user does *not* choose to overwrite, quit... if (optionDocExists != JOptionPane.YES_OPTION) { // don't show "export was OK" message in main frame showOkMessage = false; return null; } } int contentsize; int counter; // first of all, create a new, empty xml-document Document exportDoc = new Document(new Element("zettelkasten")); // yet everything is ok... exportOk = true; // create a list of all elements from the main xml file try { // get the size of the export data, used for progressbar contentsize = exportentries.size(); // go through all elements of the data file for (counter = 0; counter < exportentries.size(); counter++) { // add the headline to our final export document exportDoc.getRootElement().addContent(exportEntries(counter)); // update progress bar setProgress(counter, 0, contentsize); } } catch (IllegalStateException e) { // log error-message Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); // show warning message box JOptionPane.showMessageDialog(null, resourceMap.getString("errorExportMsg"), resourceMap.getString("errorExportTitle"), JOptionPane.PLAIN_MESSAGE); // and change indicator exportOk = false; } // // now that we've created our xml-document, we can // export it to a file // try { // show status text msgLabel.setText(resourceMap.getString("msg2")); // 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(exportDoc, fos); // close the output stream fos.close(); } catch (IOException e) { // log error-message Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); // and change indicator exportOk = false; } // if the user chose to export the keywords and authors as separate // file, do so if (!allinone) { // // first we export the keyword file // // prepare the filepath StringBuilder fp = new StringBuilder(filepath.toString()); // get position of file extension int ext = fp.lastIndexOf("."); // insert an appendix befor the file extenstion fp.insert(ext, "_keywords"); // create a new file File file_keywords = new File(fp.toString()); // open the outputstream fos = new FileOutputStream(file_keywords); // create a new XML-outputter with the pretty output format, // so the xml-file looks nicer out = new XMLOutputter(Format.getPrettyFormat()); try { // save the main-export-file out.output(dataObj.getKeywordData(), fos); // close the output stream fos.close(); } catch (IOException e) { // log error-message Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); // and change indicator exportOk = false; } // // now we export the author file // // prepare the filepath fp = new StringBuilder(filepath.toString()); // get position of file extension ext = fp.lastIndexOf("."); // insert an appendix befor the file extenstion fp.insert(ext, "_authors"); // create a new file File file_authors = new File(fp.toString()); // open the outputstream fos = new FileOutputStream(file_authors); // create a new XML-outputter with the pretty output format, // so the xml-file looks nicer out = new XMLOutputter(Format.getPrettyFormat()); try { // save the main-export-file out.output(dataObj.getAuthorData(), fos); // close the output stream fos.close(); } catch (IOException e) { // log error-message Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); // and change indicator exportOk = false; } } } catch (FileNotFoundException e) { // log error-message Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage()); // show warning message JOptionPane.showMessageDialog(null, resourceMap.getString("errorExportMsg"), resourceMap.getString("errorExportTitle"), JOptionPane.PLAIN_MESSAGE); // and change indicator exportOk = false; } catch (SecurityException e) { // log error-message Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); // show warning message JOptionPane.showMessageDialog(null, resourceMap.getString("errorNoAccessMsg"), resourceMap.getString("errorNoAccessTitle"), JOptionPane.PLAIN_MESSAGE); // and change indicator exportOk = false; } // if the user requested a bibtex-export, do this now if (exportbibtex) { // show status text msgLabel.setText(resourceMap.getString("msgBibtextExport")); // write bibtex file ExportTools.writeBibTexFile(dataObj, bibtexObj, exportentries, filepath, resourceMap); } return null; // return your result }