Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

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

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

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.j  ava2 s . c om
        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
}

From source file:de.danielluedecke.zettelkasten.tasks.importtasks.ImportFromZkn.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.

    // init of the xml element variables here, since they are
    // being used more often
    Element zettelkasten;/* w  w  w.j av  a  2  s .c  o m*/
    Element zettel;
    Element content;
    Element keywords;
    Element author;
    Element manlinks;
    Element remarks;
    Element timestamp;
    Element hyperlinks;
    Element title;
    Element luhmann;

    // get the filelength
    final long l = filepath.length();
    final long kbl = l / 1024;
    // this counter is used for indicating the position of the progressbar
    long counter = 0;
    // this variable stores the amount of entries before the import starts. this
    // is needed when appending data and correcting links like bookmarks etc.
    int oldcount = dataObj.getCount(Daten.ZKNCOUNT);
    // init the stringbuffer
    StringBuilder buffer = new StringBuilder("");
    // init the input stream.
    InputStream is;
    // and the input streamreader.
    InputStreamReader ips = null;
    // First of all read the file. The way how the file is
    // imported depends on the filetype. the switch command
    // is used to choose the right import routine
    //
    // here begins the import of old zettelkasten data (.zkn)
    //
    //
    // what we do here is importing an ascii file of old zettelkasten data
    // an adding the imported content to a dummy xml file/document. the old zettelkasten
    // data used simple ascii strings which were separated by zeros. each zero therefor
    // indicates the beginning of a new element (e.g. content, keywords, authors, title...)
    //
    // the header of the old datafile is skipped (see below), while the data is imported and
    // assigned to the right element via switch-command. we have an index counter which tells
    // the switch command which element of the datafile has been imported recently.
    //
    // init variables
    Document zkndoc;

    // TODO entfernen von Dubletten nur bei zkn3-Dateien, nicht bei alten ZKN-Dateien?

    // try to open the file
    try {
        is = new FileInputStream(filepath);
    } catch (FileNotFoundException fileNotFoundException) {
        // display error message box
        JOptionPane.showMessageDialog(null, resourceMap.getString("importDlgFileNotFound", filepath),
                resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE);
        // leave thread
        return null;
    }
    try {
        // when the input file is in ascii format, tell the input
        // stream to convert it into unicode
        if (atou) {
            ips = new InputStreamReader(is, "cp1252");
        }
        // else use default encoding
        else {
            ips = new InputStreamReader(is);
        }
    } catch (UnsupportedEncodingException e) {
        Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage());
    }
    // used for converting the imported, old zettelkasten data into the
    // new xml structure
    int authorPos;
    int keywordPos;
    String dummyString;
    // if we don't want to append the data, reset the zettelkastem
    if (!append) {
        resetDataFiles();
    }
    if (ips != null)
        try {
            // needed for skipping some information of the old file format which should
            // not be imported
            boolean skip = false;
            buffer.setLength(0);
            // the read bytes are stored in this variable
            int c;
            // every data part of the old zettelkasten data
            // is separated by a 0. the first part is the
            // file version. if this value is not "2.6", we have the data
            // in a too old fileformat, which cannot be importet
            while (!skip && (c = ips.read()) != -1) {
                // a zero indicates a new part/entry/string of the old
                // zettelkasten datafile which is imported. so each time we
                // find a zero, a new part of the data structure begins
                if (c != 0) {
                    // convert the integer value into a char value
                    char chr = (char) c;
                    buffer.append(chr);
                }
                // leave the loop
                else {
                    skip = true;
                }
                counter++;
                // when we have a very small data-file, don't count kilobytes,
                // but only bytes...
                if (l > 2048) {
                    setProgress(counter / 1024, 0, kbl);
                } else {
                    setProgress(counter, 0, l);
                }
            }
            // now we have to check, whether the imported data has the
            // correct format, indicated by the version number "2.6"
            // if not, show error message and leave thread
            if (!buffer.toString().contains("2.6")) {
                // log error-message
                Constants.zknlogger.log(Level.WARNING,
                        "Failed when importing older version of Zettelkasten-data. Data-format was older than Version 2.6!");
                // display error message box
                JOptionPane.showMessageDialog(null, resourceMap.getString("importDlgErrOldZknData"),
                        resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE);
                // return value that indicates that an error occured
                taskinfo.setImportOk(false);
                // leave thread
                return null;
            }
            // reset skip-value
            skip = false;
            buffer.setLength(0);
            // now comes a part with the filedescription of the old
            // zettelkasten file. this information is needed and should be
            // saved in the metainformation file.
            while (!skip && (c = ips.read()) != -1) {
                // as long as the delimiter-zero is not reached, read the bytes
                if (c != 0) {
                    // convert the integer value into a char value
                    char chr = (char) c;
                    if (Tools.isLegalJDOMChar(c)) {
                        buffer.append(chr);
                    }
                }
                // otherweise, transfer the buffer to the metainformation-xml-file
                // and leave the loop
                else {
                    try {
                        if (!append) {
                            dataObj.setZknDescription(buffer.toString());
                        } else {
                            dataObj.addZknDescription(buffer.toString());
                        }
                        skip = true;
                    }
                    // in case we have an illegal add exception...
                    catch (IllegalAddException e) {
                        // display errormessage
                        showErrorLogMsg(e.getLocalizedMessage());
                        // reset data files
                        resetDataFiles();
                        // leave task
                        return null;
                    }
                    // ...or an illegal data exception, show error log and leave thread here
                    catch (IllegalDataException e) {
                        // display errormessage
                        showErrorLogMsg(e.getLocalizedMessage());
                        // reset data files
                        resetDataFiles();
                        // leave task
                        return null;
                    }
                }
                counter++;
                // when we have a very small data-file, don't count kilobytes,
                // but only bytes...
                if (l > 2048) {
                    setProgress(counter / 1024, 0, kbl);
                } else {
                    setProgress(counter, 0, l);
                }
            }
            // reset skip-value
            skip = false;
            // and read the rest of the not needed information. we now
            // have the needed filedescription and saved it in the
            // metainformation file
            while (!skip && (c = ips.read()) != -1) {
                // a zero indicates a new part/entry/string of the old
                // zettelkasten datafile which is imported. so each time we
                // find a zero, a new part of the data structure begins
                if (0 == c) {
                    skip = true;
                }
                counter++;
                // when we have a very small data-file, don't count kilobytes,
                // but only bytes...
                if (l > 2048) {
                    setProgress(counter / 1024, 0, kbl);
                } else {
                    setProgress(counter, 0, l);
                }
            }

            // reset the string buffer so it contains only
            // new read data
            buffer.setLength(0);
            // this is an indicator which "counts" the separater-zeros,
            // which means that this variable indicates which part of an
            // entry is currently read (i.e. maintext, author, keywords...)
            int dataIndicator = 0;
            // get the root element of the temporary XML structure
            // this is used below to create new child elements of each entry
            zettelkasten = dummyXML.getRootElement();
            zettel = null;
            // read the file byte per byte
            while ((c = ips.read()) != -1) {
                // as long as the read char is no "separater" (zero),
                // it is appended to the string buffer.
                if (c != 0) {
                    // convert the integer value into a char value
                    char chr = (char) c;
                    // if char is a return character (new line), add a html-br-tag to
                    // the string buffer
                    if (13 == c) {
                        buffer.append("[br]");
                    }
                    // in windows-ascii, each new line command consists of two bytes:
                    // 13 and 10. If a 13 was found, the new line tag (<br>) is already
                    // set, so we skip the second bye here.
                    else if (10 == c) {
                    }
                    // else append the char to the buffer
                    else if (Tools.isLegalJDOMChar(c)) {
                        buffer.append(chr);
                    }

                } else {
                    try {
                        // every time when a new "zettel" begins, create the
                        // related child element in the XML structure
                        if (0 == dataIndicator) {
                            zettel = new Element("zettel");
                            zettelkasten.addContent(zettel);
                        }
                        // check for null reference
                        if (null == zettel) {
                            zettel = new Element("zettel");
                            zettelkasten.addContent(zettel);
                        }
                        // if the char is a zero, it marks the end of a part
                        // of an zettelkasten entry (e.g. maintext (conten), author, keyword, etc.
                        // which are all separated by zeros)
                        // now we have to create a new XML element to copy the content
                        // of the buffer to the temporary XML structure
                        switch (dataIndicator) {
                        // the content of the string buffer is the MAINTEXT (CONTENT)
                        // of an entry. copy string buffer to related XML child element
                        case 0:
                            content = new Element("content");
                            zettel.addContent(content);
                            // we have to update the list-format-elements from the
                            // old format. while in the old format a list was just surrounded
                            // by [l]-tags and each line was a new bullet point, we
                            // now surround <li>-elements arround each line. So from
                            // now on, a bullet point may contain several lines.
                            content.addContent(replaceListElements(buffer.toString()));
                            // increase dataIndicator, so next time buffer content
                            // is regarded as the next element, i.e. keyword infos
                            dataIndicator++;
                            break;
                        // the content of the string buffer are the KEYWORDS
                        // of an entry. copy string buffer to related XML child element
                        case 1:
                            keywords = new Element(Daten.ELEMENT_KEYWORD);
                            zettel.addContent(keywords);
                            keywords.addContent(buffer.toString().trim());
                            // increase dataIndicator, so next time buffer content
                            // is regarded as the next element, i.e. author infos
                            dataIndicator++;
                            break;
                        // the content of the string buffer are the AUTHOR INFOS
                        // of an entry. copy string buffer to related XML child element
                        case 2:
                            author = new Element(Daten.ELEMENT_AUTHOR);
                            zettel.addContent(author);
                            author.addContent(buffer.toString().trim());
                            // increase dataIndicator, so next time buffer content
                            // is regarded as the next element, i.e. RELATIONS/LINKS infos
                            dataIndicator++;
                            break;
                        // the content of the string buffer are the RELATIONS/LINK INFOS
                        // of an entry. These are NOT NEEDED, so skip them
                        case 3: // increase dataIndicator, so next time buffer content
                                // is regarded as the next element, i.e. OTHER REMARKS infos
                            dataIndicator++;
                            // reset buffer
                            buffer.setLength(0);
                            break;
                        // the content of the string buffer are the OTHER REMARKS
                        // of an entry. copy string buffer to related XML child element
                        case 4:
                            remarks = new Element("remarks");
                            zettel.addContent(remarks);
                            remarks.addContent(buffer.toString());
                            // increase dataIndicator, so next time buffer content
                            // is regarded as the next element, i.e. TIMESTAMP infos
                            dataIndicator++;
                            break;
                        // the content of the string buffer is the TIME STAMP
                        // of an entry. copy string buffer to related XML child element
                        case 5:
                            timestamp = new Element("timestamp");
                            zettel.addContent(timestamp);
                            timestamp.addContent(buffer.toString());
                            // increase dataIndicator, so next time buffer content
                            // is regarded as the next element, i.e. HYPERLINKS
                            dataIndicator++;
                            break;
                        // the content of the string buffer is the entry's HYPERLINKS
                        // of an entry. copy string buffer to related XML child element
                        case 6:
                            hyperlinks = new Element("hyperlinks");
                            zettel.addContent(hyperlinks);
                            hyperlinks.addContent(buffer.toString());
                            // increase dataIndicator, so next time buffer content
                            // is regarded as the next element, i.e. TITLE
                            dataIndicator++;
                            break;
                        // the content of the string buffer is the entry's TITLE
                        // of an entry. copy string buffer to related XML child element
                        case 7:
                            title = new Element("title");
                            zettel.addContent(title);
                            title.addContent(buffer.toString().trim());
                            // RESET the dataIndicator, because now starts the next entry
                            dataIndicator = 0;
                            break;
                        }
                        // reset buffer
                        buffer.setLength(0);
                    }
                    // in case we have an illegal-add-exception...
                    catch (IllegalAddException e) {
                        // display errormessage
                        showErrorLogMsg(e.getLocalizedMessage());
                        // reset data files
                        resetDataFiles();
                        // leave task
                        return null;
                    }
                    // ...or an illegal-data-exception, show error-log and leave thread
                    catch (IllegalDataException e) {
                        // display errormessage
                        showErrorLogMsg(e.getLocalizedMessage());
                        // reset data files
                        resetDataFiles();
                        // leave task
                        return null;
                    }
                }
                // increase the counter for the progress bar
                counter++;
                // when we have a very small data-file, don't count kilobytes,
                // but only bytes...
                if (l > 2048) {
                    setProgress(counter / 1024, 0, kbl);
                } else {
                    setProgress(counter, 0, l);
                }
            }
            /*
             * Now that we have imported the data into a xml document, we have to
             * transfer this document into the CData class, which stores the original
             * zettelkasten data.
             *
             * We have to do some conversions here. First of all, the keywords have to be
             * extracted and the keyword datafile (see "Document keywordFile" in "CData.java")
             * has to be created with these extracted keywords. The keyword strings in this
             * dummy xml structure are then replaced by the index numbers (i.e. element-position)
             * of the related keywords in the keywordFile.
             *
             * After that, the same procedure has to be applied to the author elements.
             *
             * Finally, the timestamp has to be converted.
             */
            // get a list with all entry-elements of the importet data
            List<?> importetList = dummyXML.getRootElement().getContent();
            // and an iterator for the loop below
            Iterator<?> iterator = importetList.iterator();
            // get the size of the xml structure which was created from the importet
            // file, i.e. get the amount of entries to be converted
            int ifl = importetList.size();
            // reset the progressbar
            setProgress(0, 0, ifl);
            counter = 0;
            // set new import message, telling that data conversion is proceeded
            msgLabel.setText(resourceMap.getString("importDlgMsgConvert"));
            // create a new dummy document, where we store the converted data
            // afterwards we simply copy this document into the dataObj (Daten)
            // via "setZknData()"
            zkndoc = new Document(new Element(Daten.DOCUMENT_ZETTELKASTEN));
            zettelkasten = zkndoc.getRootElement();
            // iteration of the dummyXML file, i.e. going through every importet
            // entry and transfer it to the "Daten" class object.
            while (iterator.hasNext()) {
                // get each entry-element
                Element entry = (Element) iterator.next();
                // create a new element "zettel"
                zettel = new Element(Daten.ELEMENT_ZETTEL);
                // and add it to the document
                zettelkasten.addContent(zettel);
                // add unique ID
                zettel.setAttribute(Daten.ATTRIBUTE_ZETTEL_ID,
                        Tools.createZknID(settingsObj.getFileName()) + String.valueOf(counter));
                // now we have to add the contents (content, authors, title, remark etc.)
                // of this entry (zettel) to each sub element of a zettel
                //
                // first of all, the title
                //
                title = new Element(Daten.ELEMENT_TITLE);
                zettel.addContent(title);
                title.setText(entry.getChild(Daten.ELEMENT_TITLE).getText());
                //
                // now comes the content
                //
                content = new Element(Daten.ELEMENT_CONTENT);
                zettel.addContent(content);
                content.setText(entry.getChild(Daten.ELEMENT_CONTENT).getText());
                //
                // now comes the author
                //
                // extract the author
                // first, get the author string of the imported data
                dummyString = entry.getChild(Daten.ELEMENT_AUTHOR).getText();
                // create empty string buffer which stores the index numbers
                // of the converted authors
                StringBuilder newau = new StringBuilder("");
                // proceed only, if authors exist
                if (!dummyString.isEmpty()) {
                    // split author-values at line separator, in case we have several authors
                    // in one entry...
                    String[] authorparts = dummyString.split("\\[br\\]");
                    // iterate array
                    for (String ap : authorparts) {
                        // trim leading and trailing spaces
                        ap = ap.trim();
                        // check whether we have any author at all...
                        if (!ap.isEmpty()) {
                            // add it to the data file
                            // and store the position of the new added author in the
                            // variable authorPos
                            authorPos = dataObj.addAuthor(ap, 1);
                            // append author index number
                            newau.append(String.valueOf(authorPos));
                            // separator for the the index numbers, since more authors
                            // and thus more index numbers might be stored in the author element
                            newau.append(",");
                        }
                    }
                    // shorten the stringbuffer by one char, since we have a
                    // superfluous comma char (see for-loop above)
                    if (newau.length() > 1) {
                        newau.setLength(newau.length() - 1);
                    }
                }
                // create author element
                author = new Element(Daten.ELEMENT_AUTHOR);
                zettel.addContent(author);
                // store author position as string value
                author.setText(newau.toString());
                //
                // now come the keywords
                //
                dummyString = entry.getChild(Daten.ELEMENT_KEYWORD).getText();
                // create empty string buffer which stores the index numbers
                // of the converted keywords
                StringBuilder newkw = new StringBuilder("");
                // proceed only, if keywords exist
                if (!dummyString.isEmpty()) {
                    // create a regular expression, that separates the keyword string at each comma.
                    // furthermore, commas within double-quotes ("") are not treated as separator-char,
                    // so the user can search for sentences that include commas as well. and finally, the
                    // quotes are removed, since we don't need them...
                    Matcher mat = Pattern.compile("(\"(.*?)\"|([^,]+)),?").matcher(dummyString);
                    // create a new list that will contain each found pattern (i.e. searchterm)
                    List<String> result = new ArrayList<String>();
                    while (mat.find()) {
                        result.add(mat.group(2) == null ? mat.group(3) : mat.group(2));
                    }
                    // and copy the list to our array...
                    String[] kws = result.toArray(new String[result.size()]);
                    // convert each keyword string
                    // therefor, iterate the array
                    for (String kw : kws) {
                        // trim leading and trailing spaces
                        kw = kw.trim();
                        // only copy keyword, if we have one...
                        if (!kw.isEmpty()) {
                            // add it to the data file
                            // and store the position of the new added keyword in the
                            // variable keywordPos
                            keywordPos = dataObj.addKeyword(kw, 1);
                            // append the index number in the string buffer
                            newkw.append(String.valueOf(keywordPos));
                            // separator for the the index numbers, since more keywords
                            // and thus more index numbers might be stored in the keyword element
                            newkw.append(",");
                        }
                    }
                    // shorten the stringbuffer by one char, since we have a
                    // superfluous comma char (see for-loop above)
                    if (newkw.length() > 1) {
                        newkw.setLength(newkw.length() - 1);
                    }
                }
                // create keyword element
                keywords = new Element(Daten.ELEMENT_KEYWORD);
                zettel.addContent(keywords);
                // store keyword index numbers
                keywords.setText(newkw.toString());
                //
                // now comes the manual links to other entries
                //
                manlinks = new Element(Daten.ELEMENT_MANLINKS);
                zettel.addContent(manlinks);
                manlinks.setText("");
                //
                // now comes the hyperlinks
                //
                hyperlinks = new Element(Daten.ELEMENT_ATTACHMENTS);
                zettel.addContent(hyperlinks);
                // the hyperlinks in the old data format are separated
                // by ";", so parse them into an array and add a new
                // sub element for each hyperlink entry
                dummyString = entry.getChild("hyperlinks").getText();
                // only add children, if we have text...
                if (!dummyString.isEmpty()) {
                    // when the operating-system is *not* windows, convert
                    // backslashes to slashes
                    if (!PlatformUtil.isWindows()) {
                        dummyString = dummyString.replace("\\", System.getProperty("file.separator"));
                    }
                    // parse the single hyperlinks into a string array
                    String[] hls = dummyString.split(";");
                    // add each hyperlink string
                    // therefor, iterate the array
                    for (int hcnt = 0; hcnt < hls.length; hcnt++) {
                        Element sublink = new Element(Daten.ELEMENT_ATTCHILD);
                        sublink.setText(hls[hcnt]);
                        hyperlinks.addContent(sublink);
                    }
                }
                //
                // now comes the remarks
                //
                remarks = new Element(Daten.ELEMENT_REMARKS);
                zettel.addContent(remarks);
                remarks.setText(entry.getChild("remarks").getText().trim());
                //
                // now comes the timestamp
                //
                // init the dummy variables
                String tsDay;
                String tsMonth = "";
                String tsYear;
                String tsHour;
                String tsMinute;
                // first get the old timestamp-string
                String ts = entry.getChild("timestamp").getText();
                // if no value exists, clear timestamp
                if (null == ts) {
                    ts = "";
                }
                // when we have an old value, convert it...
                if (!ts.isEmpty()) {
                    // we might have two parts, the created and the edited value, divided by ";"
                    // the format is as following:
                    // "Erstellt am: Sonntag, den 03. November 2008, um 07:28 Uhr;"
                    String[] tsParts = ts.split(";");
                    // go through array
                    for (int tscount = 0; tscount < tsParts.length; tscount++) {
                        // now look for the occurence of the day
                        int start = tsParts[tscount].indexOf(", den ");
                        // if it was found, proceed
                        if (start != -1) {
                            try {
                                // and copy the two digits after that occurence to the day-string
                                // 6 positions after the occurence of ", den " starts the day in the string
                                // and it's 2 chars long, so we +6 and +8 here.
                                tsDay = tsParts[tscount].substring(start + 6, start + 8);
                                // now look for the next space after the month-string
                                // after +8 comes a space sign, and after that starts the month. so we look
                                // for the first space after "+10"
                                int end = tsParts[tscount].indexOf(" ", start + 10);
                                // and compare the month and copy it
                                if (tsParts[tscount].substring(start + 10, end).equalsIgnoreCase("januar")) {
                                    tsMonth = "01";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("februar")) {
                                    tsMonth = "02";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("mrz")) {
                                    tsMonth = "03";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("april")) {
                                    tsMonth = "04";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("mai")) {
                                    tsMonth = "05";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("juni")) {
                                    tsMonth = "06";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("juli")) {
                                    tsMonth = "07";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("august")) {
                                    tsMonth = "08";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("september")) {
                                    tsMonth = "09";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("oktober")) {
                                    tsMonth = "10";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("november")) {
                                    tsMonth = "11";
                                } else if (tsParts[tscount].substring(start + 10, end)
                                        .equalsIgnoreCase("dezember")) {
                                    tsMonth = "12";
                                }
                                // now check out the year
                                // exactly 3 chars after the end-value we shoukd have the lower two digits of
                                // the year, i.e. "07" for "2007" and so on
                                tsYear = tsParts[tscount].substring(end + 3, end + 5);
                                // now look for the occurence of the time
                                start = tsParts[tscount].indexOf(", um ");
                                // 5 positions after that we have the hour, as two-digit-value
                                tsHour = tsParts[tscount].substring(start + 5, start + 7);
                                // 3 positions after the hour (2 digits hour, one ":") we find the minutes
                                tsMinute = tsParts[tscount].substring(start + 8, start + 10);
                                // so now we should have the complete created- or editedt-timestamp
                                // and set the string for the created-subchild
                                if (0 == tscount) {
                                    dataObj.setTimestampCreated(zettel,
                                            tsYear + tsMonth + tsDay + tsHour + tsMinute);
                                } else {
                                    dataObj.setTimestampEdited(zettel,
                                            tsYear + tsMonth + tsDay + tsHour + tsMinute);
                                }
                            } catch (IndexOutOfBoundsException ex) {
                                // set creation and modification timestamp, where the
                                // creation date is a default timestamp and no edit timestamp
                                // is used
                                dataObj.setTimestamp(zettel, defaulttimestamp, "");
                            }
                        } else {
                            // set creation and modification timestamp, where the
                            // creation date is a default timestamp and no edit timestamp
                            // is used
                            dataObj.setTimestamp(zettel, defaulttimestamp, "");
                        }
                    }
                } else {
                    // set creation and modification timestamp, where the
                    // creation date is a default timestamp and no edit timestamp
                    // is used
                    dataObj.setTimestamp(zettel, defaulttimestamp, "");
                }
                //
                // now comes the luhmann number
                //
                luhmann = new Element(Daten.ELEMENT_TRAILS);
                zettel.addContent(luhmann);
                luhmann.setText("");
                // update the progressbar
                counter++;
                setProgress(counter, 0, ifl);
            }
            // now that all data is converted into the variable zkndoc...
            if (!append) {
                // set this document as main zkn data...
                dataObj.setZknData(zkndoc);
                // update first/last attributes
                dataObj.db_updateEntryOrderReferences();
            }
            // resp. append the zkndoc to the maindata
            else {
                // append imported entries.
                dataObj.appendZknData(zkndoc);
            }
            // we're done! :-)
        } catch (IOException ex) {
            // tell user that opening/importing the source file failed
            Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage());
            // display error message box
            JOptionPane.showMessageDialog(null, resourceMap.getString("importDlgErrCorruptedFile"),
                    resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE);
            // return value that indicates that an error occured
            taskinfo.setImportOk(false);
            // if import of main data failed, leave
        } finally {
            try {
                ips.close();
            } catch (IOException ex) {
                Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage());
            }
        }

    //
    //
    // here begins the import of old bookmark data (.zkl)
    //
    //
    /*
     *
     * !!! IMPORT OF BOOKMARKS STARTS HERE !!!
     *
     * now where we have finished importing the main data
     * we should go on with importing the bookmarks
     *
     */

    // TODO Fehler beim Import? Ein Lesezeichen hatte keine Kategorie,
    // hier Standardkategorie setzen...

    // change file extension
    filepath = new File(FileOperationsUtil.setFileExtension(filepath, ".zkl"));
    // init the stringbuffer
    buffer = new StringBuilder("");
    try {
        is = new FileInputStream(filepath);
        // when the input file is in ascii format, tell the input
        // stream to convert it into unicode
        try {
            if (atou) {
                ips = new InputStreamReader(is, "cp1252");
            } else {
                ips = new InputStreamReader(is);
            }
        } catch (UnsupportedEncodingException e) {
            Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
            ips = new InputStreamReader(is);
        }

        try {
            // needed for skipping some information of the old file format which should
            // not be imported
            boolean skip = false;
            buffer.setLength(0);
            // the read bytes are stored in this variable
            int c;
            // every data part of the old zettelkasten data
            // is separated by a 0. the first part is the
            // file version. if this value is not "2.6", we have the data
            // in a too old fileformat, which cannot be importet
            while (!skip && (c = ips.read()) != -1) {
                // a zero indicates a new part/entry/string of the old
                // zettelkasten datafile which is imported. so each time we
                // find a zero, a new part of the data structure begins
                if (c != 0) {
                    // convert the integer value into a char value
                    char chr = (char) c;
                    buffer.append(chr);
                }
                // leave the loop
                else {
                    skip = true;
                }
            }
            // now we have to check, whether the imported data has the
            // correct format, indicated by the version number "2.7"
            // if not, show error message and leave thread
            if (!buffer.toString().contains("2.7")) {
                // display error message box
                JOptionPane.showMessageDialog(null, resourceMap.getString("importDlgErrOldBookmarkData"),
                        resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE);
                // leave thread
                return null;
            }
            // reset skip-value
            skip = false;
            // reset buffer-value
            buffer.setLength(0);
            // now comes a part with the categories of the bookmarks. they
            // are saved as one single string, separated by commas. so we have
            // to split the string at each comma after reading
            while (!skip && (c = ips.read()) != -1) {
                // as long as the delimiter-zero is not reached, read the bytes
                if (c != 0) {
                    // convert the integer value into a char value
                    char chr = (char) c;
                    buffer.append(chr);
                }
                // otherweise, transfer the buffer to the metainformation-xml-file
                // and leave the loop
                else {
                    skip = true;
                }
            }
            // parse the categories to a string array
            // we will have to use this array later, when adding the bookmarks
            String[] catarray = buffer.toString().split(",");
            // reset skip-value
            skip = false;
            // reset buffer-value
            buffer.setLength(0);
            // now comes a part with the bookmarks. they
            // are saved as one single string, separated by commas. so we have
            // to split the string at each comma after reading. the first part
            // contains the entry-number, the second the reference to the category.
            // we retrieve the category-label from the above read array "catarray"
            while (!skip && (c = ips.read()) != -1) {
                // as long as the delimiter-zero is not reached, read the bytes
                if (c != 0) {
                    // convert the integer value into a char value
                    char chr = (char) c;
                    if (Tools.isLegalJDOMChar(c)) {
                        buffer.append(chr);
                    }
                }
                // otherwise leave the loop
                else {
                    skip = true;
                }
            }
            // parse the buffer to an string-array, which then contains the bookmarks
            // and category-index-numbers
            String[] bmarray = buffer.toString().split(",");
            // first check, whether any categories are used. if not, add
            // a default-category
            if (catarray.length < 1) {
                bookmarksObj.addCategory(resourceMap.getString("defaultBookmarkCategory"));
            }
            // init the catstring, used below
            String catstring;
            // now go through all importet bookmarks and add them to the
            // bookmark-class. increase loop-counter by 2, since we have to read
            // two following array-entries: X=number, X+1=category-index
            for (int cnt = 0; cnt < bmarray.length; cnt += 2) {
                // get the entry-number which is bookmarked
                int bmindex = Integer.parseInt(bmarray[cnt]);
                // get the category's index-number
                int catindex = Integer.parseInt(bmarray[cnt + 1]);
                // if the category-index-number is out of bounds set default category
                if (catindex < 0 || catindex >= catarray.length) {
                    catstring = resourceMap.getString("defaultBookmarkCategory");
                }
                // else retrieve the category-name from the catarray
                else {
                    catstring = catarray[catindex];
                }
                // if the data was appended, add amount of old entries to the
                // bookmark-number, since the new entry-numbers are "shifted"...
                if (append) {
                    bmindex = bmindex + oldcount;
                }
                // now add the data to the bookmark-class. we have no comments yet,
                // so we will pass an empty string for that parameter
                bookmarksObj.addBookmark(bmindex, catstring, "");
            }
            // actually, we should have done everything by now. :-)
        } catch (IOException ex) {
            // tell user that opening/importing the bookmak-file failed
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
            // display error message box
            JOptionPane.showMessageDialog(null, resourceMap.getString("importDlgErrOldBookmarkData"),
                    resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE);
        } finally {
            try {
                ips.close();
            } catch (IOException ex) {
                Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage());
            }
        }
    } catch (FileNotFoundException fileNotFoundException) {
        // if no bookmark file was found, simply go on
    }
    return null; // return your result
}

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.
    ////from  w  ww. j  a  va2  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.importtasks.ImportFromZkx.java

License:Open Source License

/**
 * //from  w w w  .j  a v a  2  s .co  m
 * @param zdoc 
 */
private void removeDoubleEntries(Document zdoc) {
    // set new import message, telling that data conversion is proceeded
    msgLabel.setText(resourceMap.getString("importDlgMsgRemoveDouble"));
    // create a list of all elements from the given xml file
    List<?> elementList = zdoc.getRootElement().getContent();
    // reset the progressbar
    setProgress(0, 0, elementList.size());
    // the outer loop for the imported data
    for (int cnt = 0; cnt < elementList.size(); cnt++) {
        // get element of imported data file
        Element importentry = (Element) elementList.get(cnt);
        // now add id to zettel-element
        String id = importentry.getAttributeValue(Daten.ATTRIBUTE_ZETTEL_ID);
        // check for valid value
        if (id != null && !id.isEmpty()) {
            // check whether Zettel with unique ID already exists
            // in the current database
            if (dataObj.findZettelFromID(id) != -1) {
                // if yes, remove double entry from imported document
                zdoc.getRootElement().getContent().remove(cnt);
                // add number of removed entry to list. remember that
                // the entry-number adds on to our counter, which starts
                // at zero.
            }
        }
        setProgress(cnt, 0, elementList.size());
    }
}

From source file:de.danielluedecke.zettelkasten.ZettelkastenView.java

License:Open Source License

/**
 * /*from   www . j  ava 2s . co  m*/
 * @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("&", "&amp;");
                        dummy = dummy.replace("\"", "&quot;");
                        dummy = dummy.replace("", "&auml;");
                        dummy = dummy.replace("", "&Auml;");
                        dummy = dummy.replace("", "&ouml;");
                        dummy = dummy.replace("", "&Ouml;");
                        dummy = dummy.replace("", "&uuml;");
                        dummy = dummy.replace("", "&Uuml;");
                        dummy = dummy.replace("", "&szlig;");
                        // 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   w w w.ja  va2 s . co m*/
    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.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java

License:Creative Commons License

/**
 * Run DFS on EObject reference tree/*from w  w  w  . j a  va 2  s. co  m*/
 * 
 * @param object
 * @param node
 * @param alreadyHandled
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected static void dfs(EObject object, Element node, Set<EObject> alreadyHandled,
        Map<String, Namespace> namespaces) throws Exception {

    if (alreadyHandled.contains(object))
        return;
    else {
        alreadyHandled.add(object);
    }

    // traverse references and append them to the document
    for (EReference ref : object.eClass().getEAllReferences()) {
        if (ref.isTransient())
            continue;

        if (ref.isMany()) {
            int id = 0;

            for (EObject content : ((List<EObject>) object.eGet(ref))) {
                if (!(content.eClass().getEPackage() instanceof EcorePackage)) {
                    Document n = createDocFromEObject(content, namespaces);
                    dfs(content, n.getRootElement(), alreadyHandled, namespaces);
                    if (!ref.isContainment()) {
                        updateMember(node, ref, id, content, n);
                        id++;
                    }
                }
            }
        } else {
            EObject content = ((EObject) object.eGet(ref));
            if (content != null && !(content.eClass().getEPackage() instanceof EcorePackage)) {
                Document n = createDocFromEObject(content, namespaces);
                dfs(content, n.getRootElement(), alreadyHandled, namespaces);
                if (!ref.isContainment())
                    updateMember(node, ref, 0, content, n);
            }
        }
    }
}

From source file:de.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java

License:Creative Commons License

/**
 * Serialize an object to XML using standard EMF
 * // w  ww  .j  av  a 2  s.  c  o  m
 * @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.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java

License:Creative Commons License

/**
 * Update member contents with resolved data
 * // w ww.  ja v a2s  .com
 * @param node
 * @param memberReference
 * @param memberDocument
 * @return
 * @throws Exception
 */
private static Element updateMember(Element node, EReference memberReference, int id, EObject memberObject,
        Document memberDocument) throws Exception {
    Namespace namespace = node.getNamespace(modelMetaData.getNamespace(memberReference));

    List<Element> children = null;
    if (namespace == null) {
        children = node.getChildren(modelMetaData.getName(memberReference));
    } else
        throw new IllegalArgumentException();
    if (id < children.size()) {
        // Inserting resolved contents to the member
        Element element = children.get(id);
        Element clone = memberDocument.getRootElement().clone();
        clone.setName(memberReference.getName());
        node.setContent(node.indexOf(element), clone);
        // Setting xsi:type
        clone.setAttribute("type",
                memberObject.eClass().getEPackage().getName() + ":" + memberObject.eClass().getName(),
                node.getNamespace("xsi"));
    }

    return node;
}

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);
        }/* w w w  .j  a  v a 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();
}