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:cz.pecina.retro.memory.Snapshot.java

License:Open Source License

/**
 * Writes a hardware shapshot to a file.
 *
 * @param file output file//ww w.  j a  v  a 2s.  c  om
 */
public void write(final File file) {
    log.fine("Writing snapshot to a file, file: " + file.getName());
    final Element snapshot = new Element("snapshot");
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    snapshot.addNamespaceDeclaration(namespace);
    snapshot.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "snapshot-" + SNAPSHOT_XML_FILE_VERSION + ".xsd", namespace);
    snapshot.setAttribute("version", SNAPSHOT_XML_FILE_VERSION);
    hardware.marshal(snapshot);
    final Document doc = new Document(snapshot);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

From source file:cz.pecina.retro.memory.XML.java

License:Open Source License

/**
 * Writes a memory range to a file, with wrap-around.
 *
 * @param file               output file
 * @param startAddress       starting address
 * @param number             number of bytes
 * @param destinationAddress destination address
 *///www .j  a  v a2s .  c  o  m
public void write(final File file, final int startAddress, final int number, final int destinationAddress) {
    log.fine(
            String.format("Writing XML data to a file, file: %s, start address: %04x," + " number of bytes: %d",
                    file.getName(), startAddress, number));
    final Element tag = new Element("memory");
    Snapshot.buildBlockElement(sourceMemory, tag, startAddress, number);
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    tag.addNamespaceDeclaration(namespace);
    tag.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "memory-" + MEMORY_XML_FILE_VERSION + ".xsd", namespace);
    tag.setAttribute("version", MEMORY_XML_FILE_VERSION);
    tag.setAttribute("start", String.format("%04X", destinationAddress));
    final Document doc = new Document(tag);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

From source file:cz.pecina.retro.trec.XML.java

License:Open Source License

/**
 * Writes the tape to an XML file.//  w  w w .  ja  va2 s.  c  o  m
 *
 * @param file output file
 */
public void write(final File file) {
    log.fine("Writing tape data to an XML file, file: " + file);
    final Element tag = new Element("tape");
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    tag.addNamespaceDeclaration(namespace);
    tag.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "tape-" + TAPE_XML_FILE_VERSION + ".xsd", namespace);
    tag.setAttribute("version", TAPE_XML_FILE_VERSION);
    tag.setAttribute("rate", String.valueOf(tapeRecorderInterface.tapeSampleRate));
    tag.setAttribute("unit", "per sec");
    try {
        long currPos = -1;
        for (long start : tape.navigableKeySet()) {
            final long duration = tape.get(start);
            log.finest(String.format("Fetched: (%d, %d)", start, duration));
            if ((start > currPos) && (duration > 0)) {
                final Element pulse = new Element("pulse");
                pulse.setAttribute("start", String.valueOf(start));
                pulse.setAttribute("duration", String.valueOf(duration));
                tag.addContent(pulse);
                log.finest(String.format("Write: (%d, %d)", start, duration));
                currPos = start + duration;
            }
        }
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    final Document doc = new Document(tag);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

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

License:Open Source License

/**
 * The accelerator keys class. This class manages the accelerator keys. The user can define
 * own accelerator keys for each relevant action. Retrieving and setting this user defined
 * data is done by this class./*from w  w w.  j  a va 2  s.  c o m*/
 * <br>
 * <br>
 * An XML-File could look like this:<br>
 * <br>
 * &lt;acceleratorkeys&gt;<br>
 * &nbsp;&nbsp;&lt;key action=&quot;newEntry&quot;&gt;control n&lt;/key&gt;<br>
 * &nbsp;&nbsp;&lt;key action=&quot;openDocument&quot;&gt;control o&lt;/key&gt;<br>
 * &lt;/acceleratorkeys&gt;<br>
 */
public AcceleratorKeys() {
    // init the xml file which should store the accelerator keys
    acceleratorKeysMain = new Document(new Element("acceleratorkeys"));
    // init the xml file which should store the accelerator keys
    acceleratorKeysNewEntry = new Document(new Element("acceleratorkeys"));
    // init the xml file which should store the accelerator keys
    acceleratorKeysDesktop = new Document(new Element("acceleratorkeys"));
    // init the xml file which should store the accelerator keys
    acceleratorKeysSearchResults = new Document(new Element("acceleratorkeys"));
    // init a default acceleratotr table
    initAcceleratorKeys();
}

From source file:de.danielluedecke.zettelkasten.database.AutoKorrektur.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  .  ja v a 2 s.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 (autokorrektur != null && autokorrektur.getRootElement().getContentSize() > 0) {
        // create new backup doc
        backupdoc = new Document(new Element("backup_autokorrektur"));
        // copy content
        backupdoc.getRootElement().addContent(autokorrektur.getRootElement().cloneContent());
    }
    autokorrektur = new Document(new Element("autokorrektur"));
}

From source file:de.danielluedecke.zettelkasten.database.AutoKorrektur.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 #autokorrektur}.
 *//* w ww.  j av  a2 s  . c o  m*/
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
        autokorrektur = new Document(new Element("autokorrektur"));
        // and copy the content of the backup document to it
        autokorrektur.getRootElement().addContent(backupdoc.getRootElement().cloneContent());
    }
}

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

License:Open Source License

/**
 * clears the bookmarks data and creates empty root elements
 *///from   w  ww  .j  av a 2 s .  c om
public final void clear() {
    // create empty bookmakrs element
    bookmarks = new Document(new Element("bookmarks"));
    // create the two sub-parts. we have on the one hand the string labels
    // for the categories of the bookmarks. This element contains child-elements
    // with the string-elements
    Element cat = new Element("category");
    // on the other hand we have several bookmarks containing the bookmark-number
    // which are child-elements of the "bookmark" element
    Element bm = new Element("bookmark");
    // add both to the root-element
    bookmarks.getRootElement().addContent(cat);
    bookmarks.getRootElement().addContent(bm);
    // reset modified state
    modified = false;
}

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

License:Open Source License

/**
 * Initiates the global variables and creates empty JDom objects
 * <br><br>//from www  . j  av a  2 s  . c o  m
 * <b>Warning!</b> This method does <i>not</i> clear the filePath-variable, so
 * be sure you have set the filePath to null manually, if necessary.
 */
public final void initZettelkasten() {
    // reset all global variables
    modified = false;
    zknframe.resetBackupNecessary();
    zknFile = null;
    authorFile = null;
    keywordFile = null;
    metainfFile = null;
    zknFileExport = null;
    // init the history array
    history = new int[HISTORY_MAX];
    // current position in the history array refers to the first element
    historyPosition = 0;
    // indicates that we have one (initial) element
    historyCount = 1;
    // the one and only element is the first entry
    history[0] = 1;
    // no update to the tabbed panes in the main window when nothing is loaded
    keywordlistUpToDate = true;
    authorlistUpToDate = true;
    titlelistUpToDate = true;
    clusterlistUpToDate = true;
    attachmentlistUpToDate = true;
    // create "empty" XML JDom objects
    zknFile = new Document(new Element(DOCUMENT_ZETTELKASTEN));
    authorFile = new Document(new Element(DOCUMENT_AUTHORS));
    keywordFile = new Document(new Element(DOCUMENT_KEYWORDS));
    // prepare the metainformation-file
    metainfFile = new Document(new Element("metainformation"));
    // first create an attribute for the fileversion-number
    Element fileversion = new Element(ELEMENT_VERSION_INFO);
    fileversion.setAttribute("id", currentVersion);
    // and add it to the document
    metainfFile.getRootElement().addContent(fileversion);
    // than create an empty description and add it
    Element desc = new Element(ELEMEMT_DESCRIPTION);
    metainfFile.getRootElement().addContent(desc);
    // than create an empty atachment-path and add it
    Element attpath = new Element(ELEMENT_ATTACHMENT_PATH);
    metainfFile.getRootElement().addContent(attpath);
    // than create an empty atachment-path and add it
    Element imgpath = new Element(ELEMENT_IMAGE_PATH);
    metainfFile.getRootElement().addContent(imgpath);
    // init zettel-position-index
    zettelPos = 1;
    // reset references to first and last entry
    setFirstZettel(-1);
    setLastZettel(-1);
    // here we add all files which are stored in the zipped data-file in a list-array
    filesToLoad.clear();
    filesToLoad.add(Constants.metainfFileName);
    filesToLoad.add(Constants.zknFileName);
    filesToLoad.add(Constants.authorFileName);
    filesToLoad.add(Constants.keywordFileName);
    filesToLoad.add(Constants.bookmarksFileName);
    filesToLoad.add(Constants.searchrequestsFileName);
    filesToLoad.add(Constants.desktopFileName);
    filesToLoad.add(Constants.desktopModifiedEntriesFileName);
    filesToLoad.add(Constants.desktopNotesFileName);
    filesToLoad.add(Constants.synonymsFileName);
    filesToLoad.add(Constants.bibTexFileName);
    // reset list
    allLuhmannNumbers.clear();
}

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

License:Open Source License

/**
 * This method is used in the {@link de.danielluedecke.zettelkasten.tasks.export.ExportToZknTask} class
 * to prepare the entries that should be exported. This method converts entry-number-references
 * into the related entry-IDs using the {@link #getZettelID(int) getZettelID(int)} method.
 * //from  www  .  j  ava  2  s.com
 * @param entrynumbers
 * @return
 */
public boolean createExportEntries(ArrayList<Integer> entrynumbers) {
    // check for valid parameter
    if (entrynumbers != null && entrynumbers.size() > 0) {
        // create "empty" XML JDom objects
        zknFileExport = new Document(new Element(DOCUMENT_ZETTELKASTEN));
        for (Integer entrynumber : entrynumbers) {
            // create new zettel element
            // and clone content from requested zettel to our element
            Element zettel = (Element) retrieveZettel(entrynumber).clone();
            // 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 {
                                String authorID = getAuthorID(Integer.parseInt(fn));
                                // replace author number with author ID inside footnote
                                content = content.substring(0, pos + 4) + authorID + content.substring(end);
                            } catch (NumberFormatException ex) {
                                // log error
                                Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
                                Constants.zknlogger.log(Level.WARNING,
                                        "Could not convert author number into author ID!");
                            }
                        } 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 author ID from related footnote number
                            try {
                                String zetID = getZettelID(Integer.parseInt(ml));
                                // replace manual link number with entry ID
                                content = content.substring(0, pos + 3) + zetID + content.substring(end);
                            } catch (NumberFormatException ex) {
                                // log error
                                Constants.zknlogger.log(Level.WARNING,
                                        "Could not convert manual link number into related entry ID!");
                            }
                        } 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);
            //
            // here we change the entry's luhmann-numbers (trailing entries) and the
            // entry's manual links with the unique IDs
            //
            replaceAttributeNrWithID(zettel);
            // add each entry-element to the export-document
            zknFileExport.getRootElement().addContent(zettel);
        }
        // set first and last zettel
        zknFileExport.getRootElement().setAttribute(ATTRIBUTE_FIRST_ZETTEL, "");
        zknFileExport.getRootElement().setAttribute(ATTRIBUTE_LAST_ZETTEL, "");
        return true;
    }
    return false;
}

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

License:Open Source License

/**
 * /*from  w ww  . java  2  s  .  co  m*/
 */
public final void clear() {
    // create empty documents
    desktop = new Document(new Element("desktops"));
    modifiedEntries = new Document(new Element("modifiedEntries"));
    desktopNotes = new Document(new Element("desktopNotes"));
    currentDesktop = -1;
    modified = false;
}