Example usage for org.jdom2 Element setAttribute

List of usage examples for org.jdom2 Element setAttribute

Introduction

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

Prototype

public Element setAttribute(final String name, final String value) 

Source Link

Document

This sets an attribute value for this element.

Usage

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

License:Open Source License

/**
 * This method sets a new index-word to the synonyms-line with the number {@code nr}.
 *
 * @param nr the number of the synonyms-line, where the index-word should be changed
 * @param indexword the new index-word, as string
 *//*  w ww  . j  a  v  a2  s .  c om*/
public void setIndexWord(int nr, String indexword) {
    // get element
    Element synonym = retrieveElement(nr);
    // set the original word as value-attribute to the "entry"-element
    synonym.setAttribute("indexword", indexword);
    setModified(true);
}

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;/*  w w w .  ja v a 2  s.  com*/
        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  a v a  2  s. co  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.hbrs.oryx.yawl.converter.handler.oryx.OryxAtomicTaskHandler.java

License:Open Source License

private void convertResourcing(final YAtomicTask task) throws ConversionException {

    String startInitiator = getShape().getProperty("startinitiator");
    String startInteraction = getShape().getProperty("startinteraction");
    String allocateInitiator = getShape().getProperty("allocateinitiator");
    String allocateInteraction = getShape().getProperty("allocateinteraction");
    String offerInitiator = getShape().getProperty("offerinitiator");
    String offerInteraction = getShape().getProperty("offerinteraction");
    String privilegesSource = getShape().getProperty("privileges");

    Element resourcingSpecs = new Element("resourcing", YAWLUtils.YAWL_NS);

    // Add in order Offer, Allocate, Start, Privileges to ensure exact same
    // result as on import
    if (offerInteraction != null) {
        Element offer = YAWLUtils
                .parseToElement("<offer xmlns=\"" + YAWLUtils.YAWL_NS + "\">" + offerInteraction + "</offer>")
                .detachRootElement();/*from ww w  .  j  a  v  a  2 s . com*/
        if (offerInitiator != null) {
            offer.setAttribute("initiator", offerInitiator);
        }
        resourcingSpecs.addContent(offer);
    }

    if (allocateInteraction != null) {
        Element allocate = YAWLUtils
                .parseToElement(
                        "<allocate xmlns=\"" + YAWLUtils.YAWL_NS + "\">" + allocateInteraction + "</allocate>")
                .detachRootElement();
        if (allocateInitiator != null) {
            allocate.setAttribute("initiator", allocateInitiator);
        }
        resourcingSpecs.addContent(allocate);
    }

    if (startInteraction != null) {
        Element start = YAWLUtils
                .parseToElement("<start xmlns=\"" + YAWLUtils.YAWL_NS + "\">" + startInteraction + "</start>")
                .detachRootElement();
        if (startInitiator != null) {
            start.setAttribute("initiator", startInitiator);
        }
        resourcingSpecs.addContent(start);
    }

    Element privileges = new Element("privileges", YAWLUtils.YAWL_NS);
    if (privilegesSource != null && !privilegesSource.isEmpty()) {
        privileges.addContent(YAWLUtils.parseToElement("<privileges>" + privilegesSource + "</privileges>")
                .getRootElement().cloneContent());
        resourcingSpecs.addContent(privileges);
    }

    if (resourcingSpecs.getChildren().size() > 0) {
        task.setResourcingSpecs(resourcingSpecs);
    }
}

From source file:de.hbrs.oryx.yawl.converter.layout.YAWLLayoutConverter.java

License:Open Source License

/**
 * If the viewport inside YAWL Editor is adjusted, then YAWL stores negative values in "bounds" element. For Oryx this has to be adjusted, simply
 * by setting each negative value to zero!
 * /*from   w  w  w.j  a  v  a 2  s  . co  m*/
 * @param boundsElement
 *            original "bounds" element of YAWL Net
 * @return Element containing only positive dimensions
 */
private Element fixNetBoundsElement(final Element boundsElement) {
    Element clonedElement = boundsElement.clone();
    clonedElement.setAttribute("x", fixBoundsAttribute(boundsElement.getAttributeValue("x")));
    clonedElement.setAttribute("y", fixBoundsAttribute(boundsElement.getAttributeValue("y")));
    clonedElement.setAttribute("h", fixBoundsAttribute(boundsElement.getAttributeValue("h")));
    clonedElement.setAttribute("w", fixBoundsAttribute(boundsElement.getAttributeValue("w")));
    return clonedElement;
}

From source file:de.intranda.goobi.plugins.sru.SRUHelper.java

License:Open Source License

public static Node parseHaabResult(GbvMarcSruImport opac, String catalogue, String schema, String searchField,
        String searchValue, String resultString, String packing, String version, boolean ignoreAnchor)
        throws IOException, JDOMException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
    builder.setFeature("http://xml.org/sax/features/validation", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document doc = builder.build(new StringReader(resultString), "utf-8");
    Element record = getRecordWithoutSruHeader(doc);
    if (record == null) {
        opac.setHitcount(0);/*from ww w . j a  v  a 2 s  .  c om*/
        return null;
    }
    opac.setHitcount(1);
    boolean isPeriodical = false;
    boolean isManuscript = false;
    boolean isCartographic = false;
    boolean isMultiVolume = false;
    boolean isFSet = false;

    String anchorPpn = null;
    String otherAnchorPpn = null;
    String otherAnchorEpn = null;

    String otherPpn = null;
    String currentEpn = null;
    String otherEpn = null;
    boolean foundMultipleEpns = false;

    // generate an answer document
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    org.w3c.dom.Document answer = docBuilder.newDocument();
    org.w3c.dom.Element collection = answer.createElement("collection");
    answer.appendChild(collection);

    boolean shelfmarkFound = false;
    List<Element> data = record.getChildren();
    for (Element el : data) {
        if (el.getName().equalsIgnoreCase("leader")) {
            String value = el.getText();
            if (value.length() < 24) {
                value = "00000" + value;
            }
            char c6 = value.toCharArray()[6];
            char c7 = value.toCharArray()[7];
            char c19 = value.toCharArray()[19];
            if (c6 == 'a' && (c7 == 's' || c7 == 'd')) {
                isPeriodical = true;
            } else if (c6 == 't') {
                isManuscript = true;
            } else if (c6 == 'e') {
                isCartographic = true;
            }
            if (c19 == 'b' || c19 == 'c') {
                isFSet = true;
            }

        }
        if (el.getName().equalsIgnoreCase("datafield")) {
            String tag = el.getAttributeValue("tag");
            List<Element> subfields = el.getChildren();
            boolean isCurrentEpn = false;
            for (Element sub : subfields) {
                String code = sub.getAttributeValue("code");
                // anchor identifier
                if (tag.equals("773") && code.equals("w")) {
                    if (ignoreAnchor) {
                        sub.setText("");
                    } else if (isFSet || isPeriodical) {
                        isMultiVolume = true;
                        anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    }
                } else if (tag.equals("800") && code.equals("w")) {
                    isMultiVolume = true;
                    anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                } else if (isManuscript && tag.equals("810") && code.equals("w")) {
                    isMultiVolume = true;
                    anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                } else if (tag.equals("830") && code.equals("w")) {
                    if (isCartographic || (isFSet && anchorPpn == null)) {
                        isMultiVolume = true;
                        anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    }
                } else if (tag.equals("776") && code.equals("w")) {
                    if (otherPpn == null) {
                        // found first/only occurrence
                        otherPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    } else {
                        otherPpn = null;
                        foundMultipleEpns = true;
                    }

                } else if (tag.equals("954")) {
                    if (code.equals("b")) {
                        if (searchField.equals("pica.epn")) {
                            // remove wrong epns
                            currentEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                            isCurrentEpn = true;
                            if (!searchValue.trim().equals(currentEpn)) {
                                sub.setAttribute("code", "invalid");
                                for (Element exemplarData : subfields) {
                                    if (exemplarData.getAttributeValue("code").equals("d")) {
                                        exemplarData.setAttribute("code", "invalid");
                                    }
                                }
                            }
                        } else {
                            if (currentEpn == null) {
                                isCurrentEpn = true;
                                currentEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                            } else {
                                foundMultipleEpns = true;
                            }
                        }
                    } else if (code.equals("d")) {
                        if (!shelfmarkFound && isCurrentEpn) {
                            shelfmarkFound = true;
                        } else {
                            sub.setAttribute("code", "invalid");
                        }
                    }
                }
            }
        }
    }

    //  search for pica.zdb for periodca
    // get digital epn from digital ppn record
    if (otherPpn != null) {
        String otherResult = SRUHelper.search(catalogue, schema, isPeriodical ? "pica.zdb" : "pica.ppn",
                otherPpn, packing, version);
        Document otherDocument = new SAXBuilder().build(new StringReader(otherResult), "utf-8");
        if (otherDocument != null) {
            Element otherRecord = getRecordWithoutSruHeader(otherDocument);
            if (otherRecord == null) {
                Helper.setFehlerMeldung("import_OtherEPNNotFound");
            } else {

                List<Element> controlList = otherRecord.getChildren("controlfield", MARC);
                for (Element field : controlList) {
                    if (field.getAttributeValue("tag").equals("001")) {
                        otherPpn = field.getText();
                    }
                }

                List<Element> fieldList = otherRecord.getChildren("datafield", MARC);
                for (Element field : fieldList) {
                    String tag = field.getAttributeValue("tag");

                    List<Element> subfields = field.getChildren();
                    for (Element sub : subfields) {
                        String code = sub.getAttributeValue("code");
                        // anchor identifier
                        if (tag.equals("773") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (tag.equals("800") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (isManuscript && tag.equals("810") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "");
                        } else if (isCartographic && tag.equals("830") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (tag.equals("954") && code.equals("b")) {
                            if (otherEpn == null) {
                                otherEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                            } else {
                                foundMultipleEpns = true;
                                otherEpn = null;
                            }
                        }

                    }
                }
            }
            if (otherPpn != null) {
                Element datafield = new Element("datafield", MARC);
                datafield.setAttribute("tag", "ppnDigital");
                datafield.setAttribute("ind1", "");
                datafield.setAttribute("ind2", "");

                Element subfield = new Element("subfield", MARC);
                subfield.setAttribute("code", "a");
                subfield.setText(otherPpn);
                datafield.addContent(subfield);
                data.add(datafield);
            }
            if (otherEpn != null && !foundMultipleEpns) {
                Element datafield = new Element("datafield", MARC);
                datafield.setAttribute("tag", "epnDigital");
                datafield.setAttribute("ind1", "");
                datafield.setAttribute("ind2", "");

                Element subfield = new Element("subfield", MARC);
                subfield.setAttribute("code", "a");
                subfield.setText(otherEpn);
                datafield.addContent(subfield);
                data.add(datafield);
            }
        }
    }
    org.w3c.dom.Element marcRecord = getRecord(answer, data, opac);

    if (isMultiVolume) {
        // get anchor record
        String anchorResult = SRUHelper.search(catalogue, schema, "pica.ppn", anchorPpn, packing, version);
        Document anchorDoc = new SAXBuilder().build(new StringReader(anchorResult), "utf-8");

        Element anchorRecord = getRecordWithoutSruHeader(anchorDoc);

        if (anchorRecord != null) {
            List<Element> anchorData = anchorRecord.getChildren();

            // get EPN/PPN digital for anchor
            String otherAnchorResult = SRUHelper.search(catalogue, schema,
                    isPeriodical ? "pica.zdb" : "pica.ppn", otherAnchorPpn, packing, version);
            Document otherAnchorDoc = new SAXBuilder().build(new StringReader(otherAnchorResult), "utf-8");
            Element otherAnchorRecord = getRecordWithoutSruHeader(otherAnchorDoc);

            if (otherAnchorRecord == null) {
                Helper.setFehlerMeldung("import_OtherEPNNotFound");
            } else {

                List<Element> controlList = otherAnchorRecord.getChildren("controlfield", MARC);
                for (Element field : controlList) {
                    if (field.getAttributeValue("tag").equals("001")) {
                        otherAnchorPpn = field.getText();
                    }
                }

                List<Element> fieldList = otherAnchorRecord.getChildren("datafield", MARC);
                for (Element field : fieldList) {
                    if (field.getAttributeValue("tag").equals("954")) {
                        List<Element> subfields = field.getChildren();
                        for (Element sub : subfields) {
                            String code = sub.getAttributeValue("code");
                            if (code.equals("b")) {
                                if (otherAnchorEpn == null) {
                                    otherAnchorEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP",
                                            "");
                                    ;
                                } else {
                                    foundMultipleEpns = true;
                                }
                            }
                        }
                    }
                }

                if (otherAnchorPpn != null) {
                    Element datafield = new Element("datafield", MARC);
                    datafield.setAttribute("tag", "ppnDigital");
                    datafield.setAttribute("ind1", "");
                    datafield.setAttribute("ind2", "");

                    Element subfield = new Element("subfield", MARC);
                    subfield.setAttribute("code", "a");
                    subfield.setText(otherAnchorPpn);
                    datafield.addContent(subfield);
                    anchorData.add(datafield);
                }

                if (otherAnchorEpn != null && !foundMultipleEpns) {
                    Element datafield = new Element("datafield", MARC);
                    datafield.setAttribute("tag", "epnDigital");
                    datafield.setAttribute("ind1", "");
                    datafield.setAttribute("ind2", "");

                    Element subfield = new Element("subfield", MARC);
                    subfield.setAttribute("code", "a");
                    subfield.setText(otherAnchorEpn);
                    datafield.addContent(subfield);
                    anchorData.add(datafield);
                }
            }
            org.w3c.dom.Element anchorMarcRecord = getRecord(answer, anchorData, opac);

            collection.appendChild(anchorMarcRecord);
        }

    }

    if (foundMultipleEpns) {
        Helper.setFehlerMeldung("import_foundMultipleEPNs");
    }

    collection.appendChild(marcRecord);
    return answer.getDocumentElement();
}

From source file:de.intranda.goobi.plugins.sru.SRUHelper.java

License:Open Source License

private static org.w3c.dom.Element getRecord(org.w3c.dom.Document answer, List<Element> data,
        IOpacPlugin plugin) {/* w  w  w.  java  2 s .c  o  m*/
    org.w3c.dom.Element marcRecord = answer.createElement("record");
    // fix for wrong leader in SWB
    org.w3c.dom.Element leader = null;
    String author = "";
    String title = "";
    for (Element datafield : data) {
        if (datafield.getName().equals("leader") && leader == null) {
            leader = answer.createElement("leader");
            marcRecord.appendChild(leader);
            String ldr = datafield.getText();
            if (ldr.length() < 24) {
                ldr = "00000" + ldr;
            }
            Text text = answer.createTextNode(ldr);
            leader.appendChild(text);

            // get the leader field as a datafield
            org.w3c.dom.Element leaderDataField = answer.createElement("datafield");
            leaderDataField.setAttribute("tag", "leader");
            leaderDataField.setAttribute("ind1", " ");
            leaderDataField.setAttribute("ind2", " ");

            org.w3c.dom.Element subfield = answer.createElement("subfield");
            leaderDataField.appendChild(subfield);
            subfield.setAttribute("code", "a");
            Text dataFieldtext = answer.createTextNode(datafield.getText());
            subfield.appendChild(dataFieldtext);
            marcRecord.appendChild(leaderDataField);

        } else if (datafield.getName().equals("controlfield")) {
            org.w3c.dom.Element field = answer.createElement("controlfield");

            Text text = answer.createTextNode(datafield.getText());
            field.appendChild(text);

            String tag = datafield.getAttributeValue("tag");
            field.setAttribute("tag", tag);
            marcRecord.appendChild(field);

            // get the controlfields as datafields
            org.w3c.dom.Element leaderDataField = answer.createElement("datafield");
            leaderDataField.setAttribute("tag", tag);
            leaderDataField.setAttribute("ind1", " ");
            leaderDataField.setAttribute("ind2", " ");

            org.w3c.dom.Element subfield = answer.createElement("subfield");
            leaderDataField.appendChild(subfield);
            subfield.setAttribute("code", "a");
            Text dataFieldtext = answer.createTextNode(datafield.getText());
            subfield.appendChild(dataFieldtext);
            marcRecord.appendChild(leaderDataField);

        } else if (datafield.getName().equals("datafield")) {
            String tag = datafield.getAttributeValue("tag");
            String ind1 = datafield.getAttributeValue("ind1");
            String ind2 = datafield.getAttributeValue("ind2");

            org.w3c.dom.Element field = answer.createElement("datafield");
            marcRecord.appendChild(field);

            field.setAttribute("tag", tag);
            field.setAttribute("ind1", ind1);
            field.setAttribute("ind2", ind2);
            List<Element> subfields = datafield.getChildren();

            for (Element sub : subfields) {
                org.w3c.dom.Element subfield = answer.createElement("subfield");
                field.appendChild(subfield);
                String code = sub.getAttributeValue("code");
                subfield.setAttribute("code", code);
                Text text = answer.createTextNode(sub.getText());
                subfield.appendChild(text);

                if (tag.equals("100") && code.equals("a")) {
                    author = sub.getText();
                }

                // main title, create sorting title
                if (tag.equals("245") && code.equals("a")) {
                    org.w3c.dom.Element sorting = answer.createElement("subfield");
                    field.appendChild(sorting);
                    sorting.setAttribute("code", "x");
                    String subtext = sub.getText();
                    if (!ind2.trim().isEmpty()) {
                        int numberOfNonfillingCharacter = new Integer(ind2).intValue();
                        subtext = subtext.substring(numberOfNonfillingCharacter);
                    }
                    title = subtext;
                    Text sortingtext = answer.createTextNode(subtext);
                    sorting.appendChild(sortingtext);

                }
            }
        }
    }
    plugin.setAtstsl(plugin.createAtstsl(title, author));
    return marcRecord;
}

From source file:de.knewcleus.openradar.gui.flightplan.FlightPlanExchangeManager.java

License:Open Source License

private String buildXml(FlightPlanData fpd) {
    Document doc = new Document();
    Element root = new Element("flightplanList");
    doc.addContent(root);//from w  ww .  j a  v a  2  s.  co m

    try {
        root.setAttribute("version", "1.0");
        Element elementFp = FpXml_1_0.createXml(fpd);
        if (elementFp != null) {
            root.addContent(elementFp);
        }
    } catch (Exception ex) {
        log.error("Problem to create flightplan...", ex);
    }
    StringWriter sw = new StringWriter();
    try {
        // XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat());
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        sw = new StringWriter();
        outputter.output(doc, sw);
    } catch (Exception e) {
        log.error("Problem to create XML output...", e);
    }

    return sw.toString();
}

From source file:de.knewcleus.openradar.gui.flightplan.FpXml_1_0.java

License:Open Source License

public static Element createXml(FlightPlanData fp) {
    /*//w  w  w  . j  a  v  a 2s  .  c  o  m
     * <header> <flight>unique number of flightplan</flight> <callsign>callsign of aiplane</callsign>
     * <owner>callsign of owning ATC</owner> <handover>optional callsign of next ATC</handover>
     * <squawk>assignedSquawk</squawk> <assignedAlt>XML decimal</assignedAlt>
     * <status>filed,active,closed,expired</status> </header> <data> <type>VFR/IFR</type> <aircraft>ICAO of
     * aircraft</aircraft> <trueAirspeed>travel air speed of aircraft</trueAirspeed> <departure>departure
     * airport</departure> <departureTime>XML date+time</departureTime> <cruisingAlt>XML decimal</cruisingAlt>
     * <route>comma separated list of navaid codes</route> <destination>destination airport</destination>
     * <alternateDest>comma separated alternative destination airports</alternateDest>
     * <estFlightTime>hours:minutes</estFlightTime> <fuelTime>hours:minutes</fuelTime> <pilot>Name of Pilot</pilot>
     * <sob>number of souls on board</sob> <remarks></remarks> </data>
     */
    GuiRadarContact contact = fp.getContact();

    Element eFlightPlan = new Element("flightplan");

    try {
        eFlightPlan.setAttribute("version", "1.0");

        // header

        Element eFpHeader = new Element("header");
        eFlightPlan.addContent(eFpHeader);

        Element eFlight = new Element("flight");
        if (fp.getFlightCode() != null) {
            eFlight.setText(fp.getFlightCode());
        }
        eFpHeader.addContent(eFlight);

        Element eCallsign = new Element("callsign");
        if (fp.getCallsign() != null) {
            eCallsign.setText(fp.getCallsign());
        }
        eFpHeader.addContent(eCallsign);

        Element eOwner = new Element("owner");
        if (fp.getOwner() != null) {
            eOwner.setText(fp.getOwner());
        }
        eFpHeader.addContent(eOwner);

        Element eHandover = new Element("handover");
        if (fp.getHandover() != null) {
            eHandover.setText(fp.getHandover());
        }
        eFpHeader.addContent(eHandover);

        Element eSquawk = new Element("squawk");
        if (fp.getSquawk() != null) {
            eSquawk.setText(fp.getSquawk());
        }
        eFpHeader.addContent(eSquawk);

        Element eAssignedRunway = new Element("assignedRunway");
        if (fp.getAssignedRunway() != null) {
            eAssignedRunway.setText(fp.getAssignedRunway());
        }
        eFpHeader.addContent(eAssignedRunway);

        Element eAssignedAlt = new Element("assignedAlt");
        if (fp.getAssignedAltitude() != null) {
            eAssignedAlt.setText(fp.getAssignedAltitude());
        }
        eFpHeader.addContent(eAssignedAlt);

        Element eAssignedRoute = new Element("assignedRoute");
        if (fp.getAssignedRoute() != null) {
            eAssignedRoute.setText(fp.getAssignedRoute());
        }
        eFpHeader.addContent(eAssignedRoute);

        Element eState = new Element("status");
        if (fp.getFpStatus() != null) {
            eState.setText(fp.getFpStatus().toString());
        }
        eFpHeader.addContent(eState);

        Element eFgCom = new Element("fgcom");
        eFgCom.setText(contact.hasFgComSupport() ? "true" : "false");
        eFpHeader.addContent(eFgCom);

        Element eFlags = new Element("flags");
        if (fp.getFlags() != null) {
            eFlags.setText(fp.getFlags());
        }
        eFpHeader.addContent(eFlags);

        // data

        Element eFpData = new Element("data");
        eFlightPlan.addContent(eFpData);

        Element eType = new Element("type");
        if (fp.getType() != null) {
            eType.setText(fp.getType());
        }
        eFpData.addContent(eType);

        Element eAircraft = new Element("aircraft");
        if (fp.getAircraft() != null) {
            eAircraft.setText(fp.getAircraft());
        }
        eFpData.addContent(eAircraft);

        Element eTrueAirspeed = new Element("trueAirspeed");
        if (fp.getTrueAirspeed() != null) {
            eTrueAirspeed.setText(fp.getTrueAirspeed());
        }
        eFpData.addContent(eTrueAirspeed);

        Element eDeparture = new Element("departure");
        if (fp.getDepartureAirport() != null) {
            eDeparture.setText(fp.getDepartureAirport());
        }
        eFpData.addContent(eDeparture);

        Element eDepartureTime = new Element("departureTime");
        if (fp.getDeparture() != null) {
            eDepartureTime.setText(fp.getDeparture());
        }
        eFpData.addContent(eDepartureTime);

        Element eCruisingAlt = new Element("cruisingAlt");
        if (fp.getCruisingAltitude() != null) {
            eCruisingAlt.setText(fp.getCruisingAltitude());
        }
        eFpData.addContent(eCruisingAlt);

        Element eRoute = new Element("route");
        if (fp.getRoute() != null) {
            eRoute.setText(fp.getRoute());
        }
        eFpData.addContent(eRoute);

        Element eDestination = new Element("destination");
        if (fp.getDestinationAirport() != null) {
            eDestination.setText(fp.getDestinationAirport());
        }
        eFpData.addContent(eDestination);

        Element eAlternateDest = new Element("alternateDest");
        if (fp.getAlternativeDestinationAirports() != null) {
            eAlternateDest.setText(fp.getAlternativeDestinationAirports());
        }
        eFpData.addContent(eAlternateDest);

        Element eEstFlightTime = new Element("estFlightTime");
        if (fp.getEstimatedFlightTime() != null) {
            eEstFlightTime.setText(fp.getEstimatedFlightTime());
        }
        eFpData.addContent(eEstFlightTime);

        Element eFuelTime = new Element("fuelTime");
        if (fp.getEstimatedFuelTime() != null) {
            eFuelTime.setText(fp.getEstimatedFuelTime());
        }
        eFpData.addContent(eFuelTime);

        Element ePilot = new Element("pilot");
        if (fp.getPilotName() != null) {
            ePilot.setText(fp.getPilotName());
        }
        eFpData.addContent(ePilot);

        Element eSoulsOnBoard = new Element("soulsOnBoard");
        eSoulsOnBoard.setText("" + fp.getSoulsOnBoard());

        eFpData.addContent(eSoulsOnBoard);

        Element eRemarks = new Element("remarks");
        if (fp.getRemarks() != null) {
            eRemarks.setText(fp.getRemarks());
        }
        eFpData.addContent(eRemarks);

    } catch (Exception e) {
        log.error("Problem to create XML for flightplan " + fp.getFlightCode(), e);
        eFlightPlan = null;
    }
    return eFlightPlan;
}

From source file:de.mud.flash.FlashTerminal.java

License:Open Source License

/**
 * Redraw a sinle line by looking at chunks and formatting them.
 * /* w  w  w  . jav a  2  s  .  c om*/
 * @param l
 *            the current line
 * @param base
 *            the "window"-base within the buffer
 * @return an element with the formatted line
 */
private Element redrawLine(int l, int base) {
    Element line = new Element("line");
    line.setAttribute("row", "" + l);

    // determine the maximum of characters we can print in one go
    for (int c = 0; c < buffer.width; c++) {
        int addr = 0;
        int currAttr = buffer.charAttributes[base + l][c];

        while ((c + addr < buffer.width) && ((buffer.charArray[base + l][c + addr] < ' ')
                || (buffer.charAttributes[base + l][c + addr] == currAttr))) {
            if (buffer.charArray[base + l][c + addr] < ' ') {
                buffer.charArray[base + l][c + addr] = ' ';
                buffer.charAttributes[base + l][c + addr] = 0;
                continue;
            }
            addr++;
        }

        if (addr > 0) {
            String tmp = new String(buffer.charArray[base + l], c, addr);
            // create new text node and make sure we insert &nbsp; (160)
            Text text = new Text(tmp.replace(' ', (char) 160));
            Element chunk = null;
            if ((currAttr & 0xfff) != 0) {
                if ((currAttr & VDUBuffer.BOLD) != 0) {
                    chunk = addChunk(new Element("B"), chunk, text);
                }
                if ((currAttr & VDUBuffer.UNDERLINE) != 0) {
                    chunk = addChunk(new Element("U"), chunk, text);
                }
                if ((currAttr & VDUBuffer.INVERT) != 0) {
                    chunk = addChunk(new Element("I"), chunk, text);
                }
                if ((currAttr & VDUBuffer.COLOR_FG) != 0) {
                    String fg = color[((currAttr & VDUBuffer.COLOR_FG) >> 4) - 1];
                    Element font = new Element("FONT").setAttribute("COLOR", fg);
                    chunk = addChunk(font, chunk, text);
                }
                /*
                 * if ((currAttr & buffer.COLOR_BG) != 0) { Color bg =
                 * color[((currAttr & buffer.COLOR_BG) >> 8) - 1]; }
                 */
            }
            if (chunk == null) {
                line.addContent(text);
            } else {
                line.addContent(chunk);
            }
        }
        c += addr - 1;
    }
    return line;
}