List of usage examples for org.jdom2 Element getChild
public Element getChild(final String cname)
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 .ja va 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.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 ww w . j av a 2 s . co 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.knewcleus.openradar.gui.flightplan.FpXml_1_0.java
License:Open Source License
public static String getCallSign(Element eFlightPlan) { return eFlightPlan.getChild("header").getChildText("callsign"); }
From source file:de.knewcleus.openradar.gui.flightplan.FpXml_1_0.java
License:Open Source License
public static FlightPlanData parseXml(AirportData airportData, GuiRadarContact contact, Element eFlightPlan) { /*//from w w w.j a v a2 s . 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> */ String flightCode = eFlightPlan.getChild("header").getChildText("flight"); String callsign = eFlightPlan.getChild("header").getChildText("callsign"); String owner = eFlightPlan.getChild("header").getChildText("owner"); String handover = eFlightPlan.getChild("header").getChildText("handover"); String squawk = eFlightPlan.getChild("header").getChildText("squawk"); String assignedRunway = eFlightPlan.getChild("header").getChildText("assignedRunway"); String assignedAlt = eFlightPlan.getChild("header").getChildText("assignedAlt"); String assignedRoute = eFlightPlan.getChild("header").getChildText("assignedRoute"); String state = eFlightPlan.getChild("header").getChildText("status"); boolean fgcomSupport = "true".equals(eFlightPlan.getChild("header").getChildText("fgcom")); String flags = eFlightPlan.getChild("header").getChildText("flags"); String type = eFlightPlan.getChild("data").getChildText("type"); String aircraft = eFlightPlan.getChild("data").getChildText("aircraft"); String trueAirspeed = eFlightPlan.getChild("data").getChildText("trueAirspeed"); String departure = eFlightPlan.getChild("data").getChildText("departure"); String departureTime = eFlightPlan.getChild("data").getChildText("departureTime"); String cruisingAlt = eFlightPlan.getChild("data").getChildText("cruisingAlt"); String route = eFlightPlan.getChild("data").getChildText("route"); String destination = eFlightPlan.getChild("data").getChildText("destination"); String alternateDest = eFlightPlan.getChild("data").getChildText("alternateDest"); String estFlightTime = eFlightPlan.getChild("data").getChildText("estFlightTime"); String fuelTime = eFlightPlan.getChild("data").getChildText("fuelTime"); String pilot = eFlightPlan.getChild("data").getChildText("pilot"); String soulsOnBoard = eFlightPlan.getChild("data").getChildText("soulsOnBoard"); String remarks = eFlightPlan.getChild("data").getChildText("remarks"); FlightPlanData fp; // FlightPlanData existingFp = contact.getFlightPlan(); // // if(existingFp!=null) { // String formerHandover = existingFp.getHandover(); //// String formerOwner = existingFp.getOwner(); // // existingFp.update(flightCode, callsign, owner, handover, squawk, assignedAlt, state, type, aircraft, trueAirspeed, departure, departureTime, // cruisingAlt, route, destination, alternateDest, estFlightTime, fuelTime, pilot, soulsOnBoard, remarks); //move to fpexchangemanager // if(airportData.getCallSign().equals(owner)) { // // OR has been restarted, the contact is still owned by me // contact.setAlignment(Alignment.LEFT); // } // if(airportData.getCallSign().equals(handover)) { // // Contact has been offered to me // contact.setAlignment(Alignment.CENTER); // } // if(!airportData.getCallSign().equals(owner) & contact.getAlignment()==Alignment.LEFT) { // // HANDOVER finalization contact is not owned by me anymore // contact.setAlignment(Alignment.RIGHT); // } // if(airportData.getCallSign().equals(formerHandover) && ("".equals(handover) || null==handover) && contact.getAlignment()==Alignment.CENTER) { // contact.setAlignment(Alignment.RIGHT); // } // // fp=existingFp; // } else { { fp = new FlightPlanData(airportData, contact, flightCode, callsign, owner, handover, squawk, assignedRunway, assignedAlt, assignedRoute, state, flags, type, aircraft, trueAirspeed, departure, departureTime, cruisingAlt, route, destination, alternateDest, estFlightTime, fuelTime, pilot, soulsOnBoard, remarks); } contact.setFgComSupport(fgcomSupport); return fp; }
From source file:de.knewcleus.openradar.view.groundnet.GroundnetReader.java
License:Open Source License
private void readGroundnetXml() { SAXBuilder builder = new SAXBuilder(); InputStream xmlInputStream = null; try {//from w w w .j a v a 2 s. c om xmlInputStream = getZipArchiveFileInputStream("data/airports.zip", airportCode); Document document = (Document) builder.build(xmlInputStream); Element rootNode = document.getRootElement(); // read parking list List<Element> list = rootNode.getChild("parkingList").getChildren("Parking"); for (Element p : list) { String index = p.getAttributeValue("index"); String type = p.getAttributeValue("type"); String name = p.getAttributeValue("name"); String number = p.getAttributeValue("number"); String lat = p.getAttributeValue("lat"); String lon = p.getAttributeValue("lon"); String heading = p.getAttributeValue("heading"); String radius = p.getAttributeValue("radius"); String airlineCodes = p.getAttributeValue("airlineCodes"); ParkPos pos = new ParkPos(index, type, name, number, lat, lon, heading, radius, airlineCodes); parkPosList.add(pos); mapTaxiPoints.put(index, pos); } // read nodes list = rootNode.getChild("TaxiNodes").getChildren("node"); for (Element p : list) { String index = p.getAttributeValue("index"); String lat = p.getAttributeValue("lat"); String lon = p.getAttributeValue("lon"); boolean isOnRunway = !"0".equals(p.getAttributeValue("isOnRunway")); String holdPointType = p.getAttributeValue("holdPointType"); TaxiPoint point = new TaxiPoint(index, lat, lon, isOnRunway, holdPointType); mapTaxiPoints.put(index, point); } // read segments list = rootNode.getChild("TaxiWaySegments").getChildren("arc"); for (Element a : list) { String beginPoint = a.getAttributeValue("begin"); String endPoint = a.getAttributeValue("end"); boolean isPushBackRoute = !"0".equals(a.getAttributeValue("isPushBackRoute")); String name = a.getAttributeValue("name"); TaxiWaySegment seg = new TaxiWaySegment(name, mapTaxiPoints.get(beginPoint), mapTaxiPoints.get(endPoint), isPushBackRoute); taxiwaySegmentList.add(seg); } } catch (Exception e) { log.error(e.getMessage()); } finally { if (xmlInputStream != null) { try { xmlInputStream.close(); zipArchive.close(); } catch (IOException e) { } } } }
From source file:de.nava.informa.parsers.Atom_0_3_Parser.java
License:Open Source License
/** * @see de.nava.informa.core.ChannelParserIF#parse(de.nava.informa.core.ChannelBuilderIF, org.jdom2.Element) *//*from w w w . ja v a 2 s . c om*/ public ChannelIF parse(ChannelBuilderIF cBuilder, Element channel) throws ParseException { if (cBuilder == null) { throw new RuntimeException("Without builder no channel can " + "be created."); } Date dateParsed = new Date(); Namespace defNS = ParserUtils.getDefaultNS(channel); if (defNS == null) { defNS = Namespace.NO_NAMESPACE; LOGGER.info("No default namespace found."); } // RSS 1.0 Dublin Core Module namespace Namespace dcNS = ParserUtils.getNamespace(channel, "dc"); if (dcNS == null) { LOGGER.debug("No namespace for dublin core found"); dcNS = defNS; } LOGGER.debug("start parsing."); // get version attribute String formatVersion = "0.3"; if (channel.getAttribute("version") != null) { formatVersion = channel.getAttribute("version").getValue().trim(); LOGGER.debug("Atom version " + formatVersion + " specified in document."); } else { LOGGER.info("No format version specified, using default."); } // --- read in channel information // Lower the case of these tags to simulate case-insensitive parsing ParserUtils.matchCaseOfChildren(channel, new String[] { "title", "description", "tagline", "ttl", "modified", "author", "generator", "copyright", "link", "entry" }); // title element ChannelIF chnl = cBuilder.createChannel(channel, channel.getChildTextTrim("title", defNS)); // TODO: support attributes: type, mode chnl.setFormat(ChannelFormat.ATOM_0_3); // language String language = channel.getAttributeValue("lang", Namespace.XML_NAMESPACE); if (language != null) { chnl.setLanguage(language); } // description element if (channel.getChild("description") != null) { chnl.setDescription(channel.getChildTextTrim("description", defNS)); } else { // fallback chnl.setDescription(channel.getChildTextTrim("tagline", defNS)); } // ttl in dc namespace Element ttl = channel.getChild("ttl", dcNS); if (ttl != null) { String ttlString = ttl.getTextTrim(); if (ttlString != null) { chnl.setTtl(Integer.parseInt(ttlString)); } } // lastbuild element : modified ? Element modified = channel.getChild("modified", defNS); if (modified != null) { chnl.setPubDate(ParserUtils.getDate(modified.getTextTrim())); } // TODO : issued value /* if (modified != null) { modified = channel.getChild("issued", defNS); chnl.setLastBuildDate (ParserUtils.getDate(modified.getTextTrim())); } */ // author element Element author = channel.getChild("author", defNS); if (author != null) { ParserUtils.matchCaseOfChildren(author, "name"); chnl.setCreator(author.getChildTextTrim("name", defNS)); } // generator element Element generator = channel.getChild("generator", defNS); if (generator != null) { chnl.setGenerator(generator.getTextTrim()); } // copyright element Element copyright = channel.getChild("copyright", defNS); if (copyright != null) { chnl.setCopyright(getCopyright(copyright)); } // n link elements // TODO : type attribut of link (text, application...) List links = channel.getChildren("link", defNS); Iterator i = links.iterator(); while (i.hasNext()) { Element linkElement = (Element) i.next(); // use first 'alternate' link String rel = linkElement.getAttributeValue("rel"); String href = linkElement.getAttributeValue("href"); if ((rel != null) && (href != null) && rel.equals("alternate")) { URL linkURL = ParserUtils.getURL(href); chnl.setSite(linkURL); break; } // TODO: further extraction of link information } // 1..n entry elements List items = channel.getChildren("entry", defNS); i = items.iterator(); while (i.hasNext()) { Element item = (Element) i.next(); // Lower the case of these tags to simulate case-insensitive parsing ParserUtils.matchCaseOfChildren(item, new String[] { "title", "link", "content", "summary", "issued", "subject" }); // get title element // TODO : deal with type attribut Element elTitle = item.getChild("title", defNS); String strTitle = "<No Title>"; if (elTitle != null) { strTitle = getTitle(elTitle); LOGGER.debug("Parsing title " + elTitle.getTextTrim() + "->" + strTitle); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Entry element found (" + strTitle + ")."); } // get link element String strLink = AtomParserUtils.getItemLink(item, defNS); // get description element String strDesc = getDescription(item, defNS); // generate new news item (link to article) ItemIF curItem = cBuilder.createItem(item, chnl, strTitle, strDesc, ParserUtils.getURL(strLink)); curItem.setFound(dateParsed); // get issued element (required) Element elIssued = item.getChild("issued", defNS); if (elIssued == null) { // [adewale@gmail.com, 01-May-2005] Fix for blogs which have // 'created' dates, but not 'issued' dates -- in clear contravention // of the Atom 0.3 spec. Element elCreated = item.getChild("created", defNS); if (elCreated != null) { curItem.setDate(ParserUtils.getDate(elCreated.getTextTrim())); } } else { curItem.setDate(ParserUtils.getDate(elIssued.getTextTrim())); } // get subject element Element elSubject = item.getChild("subject", dcNS); if (elSubject != null) { // TODO: Mulitple subject elements not handled currently curItem.setSubject(elSubject.getTextTrim()); } } // set to current date chnl.setLastUpdated(dateParsed); return chnl; }
From source file:de.nava.informa.parsers.Atom_1_0_Parser.java
License:Open Source License
/** * @see de.nava.informa.core.ChannelParserIF#parse(de.nava.informa.core.ChannelBuilderIF, org.jdom2.Element) *//*from w ww . j ava2 s. com*/ public ChannelIF parse(ChannelBuilderIF cBuilder, Element channel) throws ParseException { if (cBuilder == null) { throw new RuntimeException("Without builder no channel can " + "be created."); } Date dateParsed = new Date(); Namespace defNS = ParserUtils.getDefaultNS(channel); if (defNS == null) { defNS = Namespace.NO_NAMESPACE; LOGGER.info("No default namespace found."); } else if ((defNS.getURI() == null) || !defNS.getURI().equals("http://www.w3.org/2005/Atom")) { LOGGER.warn("Namespace is not really supported, still trying assuming Atom 1.0 format"); } LOGGER.debug("start parsing."); // --- read in channel information // Lower the case of these tags to simulate case-insensitive parsing ParserUtils.matchCaseOfChildren(channel, new String[] { "title", "subtitle", "updated", "published", "author", "generator", "rights", "link", "entry" }); // TODO icon and logo: Feed element can have upto 1 logo and icon. // TODO id: Feed and all entries have a unique id string. This can // be the URL of the website. Supporting this will require API change. // TODO: Feed can optionally have category information // title element ChannelIF chnl = cBuilder.createChannel(channel, channel.getChildTextTrim("title", defNS)); chnl.setFormat(ChannelFormat.ATOM_1_0); // description element if (channel.getChild("subtitle") != null) { chnl.setDescription(channel.getChildTextTrim("subtitle", defNS)); } // TODO: should we use summary element? // lastbuild element : updated ? Element updated = channel.getChild("updated", defNS); if (updated != null) { chnl.setPubDate(ParserUtils.getDate(updated.getTextTrim())); } // author element List authors = channel.getChildren("author", defNS); chnl.setCreator(getAuthorString(authors, defNS)); // TODO we are ignoring contributors information // generator element Element generator = channel.getChild("generator", defNS); if (generator != null) { chnl.setGenerator(generator.getTextTrim()); } // TODO generator can have URI and version information // copyright element Element rights = channel.getChild("rights", defNS); if (rights != null) { chnl.setCopyright(AtomParserUtils.getValue(rights, getMode(rights))); } List links = channel.getChildren("link", defNS); Iterator i = links.iterator(); URL linkUrl = null; while (i.hasNext()) { Element linkElement = (Element) i.next(); // use first 'alternate' link // if rel is not present, use first link without rel String rel = linkElement.getAttributeValue("rel"); String href = linkElement.getAttributeValue("href"); // TODO we need to handle relative links also if ((rel == null) && (href != null) && (linkUrl == null)) { linkUrl = ParserUtils.getURL(href); } else if ((rel != null) && (href != null) && rel.equals("alternate")) { linkUrl = ParserUtils.getURL(href); break; } } if (linkUrl != null) { chnl.setSite(linkUrl); } List items = channel.getChildren("entry", defNS); i = items.iterator(); while (i.hasNext()) { Element item = (Element) i.next(); // Lower the case of these tags to simulate case-insensitive parsing ParserUtils.matchCaseOfChildren(item, new String[] { "title", "link", "content", "summary", "published", "author" }); // TODO entry, if copied from some other feed, may have source element // TODO each entry can have its own rights declaration // get title element Element elTitle = item.getChild("title", defNS); String strTitle = "<No Title>"; if (elTitle != null) { strTitle = AtomParserUtils.getValue(elTitle, getMode(elTitle)); LOGGER.debug("Parsing title " + elTitle.getTextTrim() + "->" + strTitle); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Entry element found (" + strTitle + ")."); } // get link element String strLink = AtomParserUtils.getItemLink(item, defNS); // get description element String strDesc = getDescription(item, defNS); // generate new news item (link to article) ItemIF curItem = cBuilder.createItem(item, chnl, strTitle, strDesc, ParserUtils.getURL(strLink)); //TODO enclosure data curItem.setFound(dateParsed); List itemAuthors = item.getChildren("author", defNS); curItem.setCreator(getAuthorString(itemAuthors, defNS)); // get published element Element elIssued = item.getChild("published", defNS); if (elIssued == null) { // published element may not be present (but updated should be) Element elUpdated = item.getChild("updated", defNS); // TODO there should be some way to determining which one are we // returning if (elUpdated != null) { curItem.setDate(ParserUtils.getDate(elUpdated.getTextTrim())); } } else { curItem.setDate(ParserUtils.getDate(elIssued.getTextTrim())); } // get list of category elements List elCategoryList = item.getChildren("category", defNS); // categories present will be stored here Collection<CategoryIF> categories = new ArrayList<>(); // multiple category elements may be present for (Object elCategoryItem : elCategoryList) { Element elCategory = (Element) elCategoryItem; // notice: atom spec. forbids to have category "term" (="subject") // set as inner text of category tags, so we have to read it from // the "term" attribute if (elCategory != null) { // TODO: what if we have more than one category element present? // subject would be overwritten each loop and therefore represent only // the last category read, so does this make any sense? // TODO: what about adding functionality for accessing "label" or "scheme" attributes? // if set, a label should be displayed instead of the value set in term // we keep this line not to break up things which // use getSubject() to read an item category curItem.setSubject(elCategory.getAttributeValue("term")); CategoryIF c = new Category(elCategory.getAttributeValue("term")); // add current category to category list categories.add(c); } } // assign categories curItem.setCategories(categories); } // set to current date chnl.setLastUpdated(dateParsed); return chnl; }
From source file:de.nava.informa.parsers.OPML_1_1_Parser.java
License:Open Source License
static Collection<FeedIF> parse(Element root) { Collection<FeedIF> feedColl = new ArrayList<>(); Date dateParsed = new Date(); logger.debug("start parsing."); // Lower the case of these tags to simulate case-insensitive parsing ParserUtils.matchCaseOfChildren(root, "body"); // Get the head element (only one should occur) // Element headElem = root.getChild("head"); // String title = headElem.getChildTextTrim("title"); // Get the body element (only one occurs) Element bodyElem = root.getChild("body"); // 1..n outline elements ParserUtils.matchCaseOfChildren(bodyElem, "outline"); List feeds = bodyElem.getChildren("outline"); for (Object feed1 : feeds) { Element feedElem = (Element) feed1; // get title attribute Attribute attrTitle = feedElem.getAttribute("title"); String strTitle = "[No Title]"; if (attrTitle != null) { strTitle = attrTitle.getValue(); }/*w w w . j a v a 2 s . c o m*/ FeedIF feed = new Feed(strTitle); if (logger.isDebugEnabled()) { logger.debug("Feed element found (" + strTitle + ")."); } // get text attribute Attribute attrText = feedElem.getAttribute("text"); String strText = "[No Text]"; if (attrText != null) { strText = attrText.getValue(); } feed.setText(strText); // get attribute type (for example: 'rss') Attribute attrType = feedElem.getAttribute("type"); String strType = "text/xml"; if (attrType != null) { strType = attrType.getValue(); } feed.setContentType(strType); // TODO: handle attribute version (for example: 'RSS') // get attribute xmlUrl Attribute attrXmlUrl = feedElem.getAttribute("xmlUrl"); if (attrXmlUrl != null && attrXmlUrl.getValue() != null) { feed.setLocation(ParserUtils.getURL(attrXmlUrl.getValue())); } // get attribute htmllUrl Attribute attrHtmlUrl = feedElem.getAttribute("htmlUrl"); if (attrHtmlUrl != null && attrHtmlUrl.getValue() != null) { feed.setSite(ParserUtils.getURL(attrHtmlUrl.getValue())); } // set current date feed.setDateFound(dateParsed); // add feed to collection feedColl.add(feed); } return feedColl; }
From source file:de.nava.informa.parsers.RSS_0_91_Parser.java
License:Open Source License
/** * @see de.nava.informa.core.ChannelParserIF#parse(de.nava.informa.core.ChannelBuilderIF, org.jdom2.Element) *///from ww w .j a va 2s. c om public ChannelIF parse(ChannelBuilderIF cBuilder, Element root) throws ParseException { if (cBuilder == null) { throw new RuntimeException("Without builder no channel can " + "be created."); } Date dateParsed = new Date(); logger.debug("start parsing."); // Get the channel element (only one occurs) ParserUtils.matchCaseOfChildren(root, "channel"); Element channel = root.getChild("channel"); if (channel == null) { logger.warn("Channel element could not be retrieved from feed."); throw new ParseException("No channel element found in feed."); } // --- read in channel information ParserUtils.matchCaseOfChildren(channel, new String[] { "title", "description", "link", "language", "item", "image", "textinput", "copyright", "rating", "pubDate", "lastBuildDate", "docs", "managingEditor", "webMaster", "cloud" }); // 1 title element ChannelIF chnl = cBuilder.createChannel(channel, channel.getChildTextTrim("title")); chnl.setFormat(ChannelFormat.RSS_0_91); // 1 description element chnl.setDescription(channel.getChildTextTrim("description")); // 1 link element chnl.setSite(ParserUtils.getURL(channel.getChildTextTrim("link"))); // 1 language element chnl.setLanguage(channel.getChildTextTrim("language")); // 1..n item elements List items = channel.getChildren("item"); Iterator i = items.iterator(); while (i.hasNext()) { Element item = (Element) i.next(); ParserUtils.matchCaseOfChildren(item, new String[] { "title", "link", "description", "source", "enclosure" }); // get title element Element elTitle = item.getChild("title"); String strTitle = "<No Title>"; if (elTitle != null) { strTitle = elTitle.getTextTrim(); } if (logger.isDebugEnabled()) { logger.debug("Item element found (" + strTitle + ")."); } // get link element Element elLink = item.getChild("link"); String strLink = ""; if (elLink != null) { strLink = elLink.getTextTrim(); } // get description element Element elDesc = item.getChild("description"); String strDesc = ""; if (elDesc != null) { strDesc = elDesc.getTextTrim(); } // generate new RSS item (link to article) ItemIF rssItem = cBuilder.createItem(item, chnl, strTitle, strDesc, ParserUtils.getURL(strLink)); rssItem.setFound(dateParsed); // get source element (an RSS 0.92 element) Element source = item.getChild("source"); if (source != null) { String sourceName = source.getTextTrim(); Attribute sourceAttribute = source.getAttribute("url"); if (sourceAttribute != null) { String location = sourceAttribute.getValue().trim(); ItemSourceIF itemSource = cBuilder.createItemSource(rssItem, sourceName, location, null); rssItem.setSource(itemSource); } } // get enclosure element (an RSS 0.92 element) Element enclosure = item.getChild("enclosure"); if (enclosure != null) { URL location = null; String type = null; int length = -1; Attribute urlAttribute = enclosure.getAttribute("url"); if (urlAttribute != null) { location = ParserUtils.getURL(urlAttribute.getValue().trim()); } Attribute typeAttribute = enclosure.getAttribute("type"); if (typeAttribute != null) { type = typeAttribute.getValue().trim(); } Attribute lengthAttribute = enclosure.getAttribute("length"); if (lengthAttribute != null) { try { length = Integer.parseInt(lengthAttribute.getValue().trim()); } catch (NumberFormatException e) { logger.warn(e); } } ItemEnclosureIF itemEnclosure = cBuilder.createItemEnclosure(rssItem, location, type, length); rssItem.setEnclosure(itemEnclosure); } } // 0..1 image element Element image = channel.getChild("image"); if (image != null) { ParserUtils.matchCaseOfChildren(image, new String[] { "title", "url", "link", "width", "height", "description" }); ImageIF rssImage = cBuilder.createImage(image.getChildTextTrim("title"), ParserUtils.getURL(image.getChildTextTrim("url")), ParserUtils.getURL(image.getChildTextTrim("link"))); Element imgWidth = image.getChild("width"); if (imgWidth != null) { try { rssImage.setWidth(Integer.parseInt(imgWidth.getTextTrim())); } catch (NumberFormatException e) { logger.warn(e); } } Element imgHeight = image.getChild("height"); if (imgHeight != null) { try { rssImage.setHeight(Integer.parseInt(imgHeight.getTextTrim())); } catch (NumberFormatException e) { logger.warn(e); } } Element imgDescr = image.getChild("description"); if (imgDescr != null) { rssImage.setDescription(imgDescr.getTextTrim()); } chnl.setImage(rssImage); } // 0..1 textinput element Element txtinp = channel.getChild("textinput"); if (txtinp != null) { ParserUtils.matchCaseOfChildren(txtinp, new String[] { "title", "description", "name", "link" }); TextInputIF rssTextInput = cBuilder.createTextInput(txtinp.getChild("title").getTextTrim(), txtinp.getChild("description").getTextTrim(), txtinp.getChild("name").getTextTrim(), ParserUtils.getURL(txtinp.getChild("link").getTextTrim())); chnl.setTextInput(rssTextInput); } // 0..1 copyright element Element copyright = channel.getChild("copyright"); if (copyright != null) { chnl.setCopyright(copyright.getTextTrim()); } // 0..1 rating element Element rating = channel.getChild("rating"); if (rating != null) { chnl.setRating(rating.getTextTrim()); } // 0..1 pubDate element Element pubDate = channel.getChild("pubDate"); if (pubDate != null) { chnl.setPubDate(ParserUtils.getDate(pubDate.getTextTrim())); } // 0..1 lastBuildDate element Element lastBuildDate = channel.getChild("lastBuildDate"); if (lastBuildDate != null) { chnl.setLastBuildDate(ParserUtils.getDate(lastBuildDate.getTextTrim())); } // 0..1 docs element Element docs = channel.getChild("docs"); if (docs != null) { chnl.setDocs(docs.getTextTrim()); } // 0..1 managingEditor element Element managingEditor = channel.getChild("managingEditor"); if (managingEditor != null) { chnl.setCreator(managingEditor.getTextTrim()); } // 0..1 webMaster element Element webMaster = channel.getChild("webMaster"); if (webMaster != null) { chnl.setPublisher(webMaster.getTextTrim()); } // 0..1 cloud element Element cloud = channel.getChild("cloud"); if (cloud != null) { String _port = cloud.getAttributeValue("port"); int port = -1; if (_port != null) { try { port = Integer.parseInt(_port); } catch (NumberFormatException e) { logger.warn(e); } } chnl.setCloud( cBuilder.createCloud(cloud.getAttributeValue("domain"), port, cloud.getAttributeValue("path"), cloud.getAttributeValue("registerProcedure"), cloud.getAttributeValue("protocol"))); } chnl.setLastUpdated(dateParsed); // 0..1 skipHours element // 0..1 skipDays element return chnl; }
From source file:de.openVJJ.basic.Module.java
License:Open Source License
/** * @see de.openVJJ.basic.Plugable#setConfig(org.jdom2.Element) *///w ww . jav a 2s . c o m @Override public void setConfig(Element element) { super.setConfig(element); Map<Integer, Plugable> plugabelNrMap = new HashMap<Integer, Plugable>(); Element plugablesElement = element.getChild(ELEMENT_NAME_PLUGABLES); if (plugablesElement != null) { for (Element plugableElement : plugablesElement.getChildren(ELEMENT_NAME_PLUGABLE)) { String plugableClass = plugableElement.getAttributeValue(ELEMENT_ATTRIBUTE_PLUGABLE_CLASS); Plugable plugable = null; if (plugableClass != null) { try { Class<?> c = Class.forName(plugableClass); Object classInstance = c.newInstance(); plugable = (Plugable) classInstance; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } if (plugable == null) { System.err.println("Was not abel to create instance of Plugabe"); continue; } String plugableNr = plugableElement.getAttributeValue(ELEMENT_ATTRIBUTE_PLUGABLE_NR); if (plugableNr != null) { plugabelNrMap.put(Integer.parseInt(plugableNr), plugable); } addPlugable(plugable); Element plugableElementConfig = plugableElement.getChild(ELEMENT_NAME_PLUGABLE_CONFIG); if (plugableElementConfig != null) { plugable.setConfig(plugableElementConfig); } } } Element connectionsElement = element.getChild(ELEMENT_NAME_CONNECTIONS); if (connectionsElement != null) { for (Element connectionElement : connectionsElement.getChildren(ELEMENT_NAME_CONNECTION)) { String inNRString = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_IN_PLUGABLE_NR); Plugable inPlugable = null; if (inNRString != null) { inPlugable = plugabelNrMap.get(Integer.parseInt(inNRString)); } String outNRString = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_OUT_PLUGABLE_NR); Plugable outPlugable = null; if (outNRString != null) { outPlugable = plugabelNrMap.get(Integer.parseInt(outNRString)); } String inName = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_IN_NAME); String outName = connectionElement.getAttributeValue(ELEMENT_ATTRIBUTE_OUT_NAME); if (inPlugable == null || outPlugable == null || inName == null || outName == null) { System.err.println("Connection not fully defined: " + inNRString + ":" + inName + " -> " + outNRString + ":" + outName); continue; } Connection outCon = outPlugable.getConnection(outName); inPlugable.setInput(inName, outCon); } } }