Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

In this page you can find the example usage for org.jdom2 Document Document.

Prototype

public Document(List<? extends Content> content) 

Source Link

Document

This will create a new Document, with the supplied list of content, and a DocType declaration only if the content contains a DocType instance.

Usage

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  w w.  j av a2 s  .  c om
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.SearchRequests.java

License:Open Source License

/**
 * Clears all search data./*from   ww  w. java  2s.com*/
 */
public final void clear() {
    // create new XML document
    searches = new Document(new Element("searches"));
    // reset last-used search result attribute
    searches.getRootElement().setAttribute("lastused", "-1");
    // set modified state
    modified = false;
}

From source file:de.danielluedecke.zettelkasten.database.Settings.java

License:Open Source License

/**
 * Inits all documents, i.e. creates new document elements
 *///ww w .j a va  2s .c om
private void initDocuments() {
    // first of all, create the empty documents
    settingsFile = new Document(new Element("settings"));
    foreignWordsFile = new Document(new Element("foreignwords"));
    // now fill the initoal elements
    fillElements();
}

From source file:de.danielluedecke.zettelkasten.database.StenoData.java

License:Open Source License

/**
 * Clears the XML document and creates a dummy-backup of the document, in case the original
 * XML-document contains data.//from w w w .j av a 2s . com
 */
public final void clear() {
    // check whether backup document exists, whether autokorrektur-document exists and whether
    // the autokorrektur-document has any data. only in this case we create a backup
    if (steno != null && steno.getRootElement().getContentSize() > 0) {
        // create new backup doc
        backupdoc = new Document(new Element("backup_steno"));
        // copy content
        backupdoc.getRootElement().addContent(steno.getRootElement().cloneContent());
    }
    steno = new Document(new Element("steno"));
}

From source file:de.danielluedecke.zettelkasten.database.StenoData.java

License:Open Source License

/**
 * In case we have a corrupted XML document with a backup document that has data
 * (see {@link #isDocumentOK() isDocumentOK()}), we can restore the backupped data
 * with this method.<br><br>
 * So, this method copies back the content of the {@link #backupdoc} to the
 * original XML document {@link #steno}.
 *///  w w w .ja  v  a  2 s.  c  om
public void restoreDocument() {
    // check whether we have a backup document that also contains data
    if ((backupdoc != null) && (backupdoc.getRootElement().getContentSize() > 0)) {
        // if we have it, create new main XML document
        steno = new Document(new Element("steno"));
        // and copy the content of the backup document to it
        steno.getRootElement().addContent(backupdoc.getRootElement().cloneContent());
    }
}

From source file:de.danielluedecke.zettelkasten.database.Synonyms.java

License:Open Source License

/**
 * Clears the XML document and creates a dummy-backup of the document, in case the original
 * XML-document contains data./* w  w w . j  a  v a 2  s  . c  o  m*/
 */
public final void clear() {
    // check whether backup document exists, whether autokorrektur-document exists and whether
    // the autokorrektur-document has any data. only in this case we create a backup
    if (synonymsFile != null && synonymsFile.getRootElement().getContentSize() > 1) {
        // create new backup doc
        backupdoc = new Document(new Element("backup_synonyms"));
        // copy content
        backupdoc.getRootElement().addContent(synonymsFile.getRootElement().cloneContent());
    }
    synonymsFile = new Document(new Element("synonyms"));
    // reset modified state
    modified = false;
}

From source file:de.danielluedecke.zettelkasten.database.Synonyms.java

License:Open Source License

/**
 * In case we have a corrupted XML document with a backup document that has data
 * (see {@link #isDocumentOK() isDocumentOK()}), we can restore the backupped data
 * with this method.<br><br>
 * So, this method copies back the content of the {@link #backupdoc} to the
 * original XML document {@link #synonymsFile}.
 *///from  w  ww  .  ja  va2  s.c  o  m
public void restoreDocument() {
    // check whether we have a backup document that also contains data
    if ((backupdoc != null) && (backupdoc.getRootElement().getContentSize() > 1)) {
        // if we have it, create new main XML document
        synonymsFile = new Document(new Element("synonyms"));
        // and copy the content of the backup document to it
        synonymsFile.getRootElement().addContent(backupdoc.getRootElement().cloneContent());
    }
}

From source file:de.danielluedecke.zettelkasten.database.Synonyms.java

License:Open Source License

/**
 * Sets the document, e.g. after loading the settings
 * @param d the document with the synonyms-data
 *///from www  .j a  v  a2 s .c om
public void setDocument(Document d) {
    synonymsFile = d;
    // check whether backup document exists, whether autokorrektur-document exists and whether
    // the autokorrektur-document has any data. only in this case we create a backup
    if (synonymsFile != null && synonymsFile.getRootElement().getContentSize() > 1) {
        // create new backup doc
        backupdoc = new Document(new Element("backup_synonyms"));
        // copy content
        backupdoc.getRootElement().addContent(synonymsFile.getRootElement().cloneContent());
    }
}

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;//w  ww  . ja  v a2 s.co  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
}

From source file:de.danielluedecke.zettelkasten.tasks.export.ExportToZknTask.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 w w  w  .ja  v a 2  s  . co 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;
        }
    }
    // yet everything is ok...
    exportOk = true;
    // create list with all export entries...
    ArrayList<Integer> entrylist = new ArrayList<Integer>();
    // go through all elements of the data file
    for (int cnt = 0; cnt < exportentries.size(); cnt++) {
        try {
            // retrieve zettelnumber
            int zettelnummer = Integer.parseInt(exportentries.get(cnt).toString());
            // and add it to list.
            entrylist.add(zettelnummer);
        } catch (NumberFormatException e) {
        }
    }
    // sort array
    Collections.sort(entrylist);
    // create document for exporting the entries
    dataObj.createExportEntries(entrylist);
    // create export-XML-file for bookmarks
    Document bookmarks = new Document(new Element("bookmarks"));
    // iterate all bookmarks
    for (int cnt = 0; cnt < bookmarksObj.getCount(); cnt++) {
        // retrieve each bookmarked entry number
        int bookmarkpos = bookmarksObj.getBookmarkEntry(cnt);
        // check whether bookmarked entry is in export list
        if (entrylist.contains(bookmarkpos)) {
            // create new bookmark element
            Element bookmark = new Element("bookmark");
            // add zettel-id as attribute
            bookmark.setAttribute("id", dataObj.getZettelID(bookmarkpos));
            // add bookmark-category as attribute
            bookmark.setAttribute("cat", bookmarksObj.getBookmarkCategoryAsString(cnt));
            // add comment as text
            bookmark.setText(bookmarksObj.getComment(cnt));
            // add element to XML file
            bookmarks.getRootElement().addContent(bookmark);
        }
    }

    // TODO suchergebnisse nummern in id's umwandeln und mitexportieren
    // TODO schreibtisch-Daten: zettel-nummern in id's umwandeln und mitexportieren

    // export data to zkn3-file
    try {
        // open the outputstream
        ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(filepath));
        // I first wanted to use a pretty output format, so advanced users who
        // extract the data file can better watch the xml-files. but somehow, this
        // lead to an error within the method "retrieveElement" in the class "CDaten.java",
        // saying the a org.jdom.text cannot be converted to org.jdom.element?!?
        // XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
        XMLOutputter out = new XMLOutputter();
        // show status text
        msgLabel.setText(resourceMap.getString("msg2"));
        // save metainformation
        zip.putNextEntry(new ZipEntry(Constants.metainfFileName));
        out.output(dataObj.getMetaInformationData(), zip);
        // save main data.
        zip.putNextEntry(new ZipEntry(Constants.zknFileName));
        out.output(dataObj.retrieveExportDocument(), zip);
        // save authors
        zip.putNextEntry(new ZipEntry(Constants.authorFileName));
        out.output(dataObj.getAuthorData(), zip);
        // save keywords
        zip.putNextEntry(new ZipEntry(Constants.keywordFileName));
        out.output(dataObj.getKeywordData(), zip);
        // save bookmarks
        zip.putNextEntry(new ZipEntry(Constants.bookmarksFileName));
        out.output(bookmarks, zip);
        // close zip-stream
        zip.close();
    } catch (IOException e) {
        // log error-message
        Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
        // change error-indicator
        exportOk = false;
    } catch (SecurityException e) {
        // log error-message
        Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
        // change error-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
}