List of usage examples for org.jdom2 Document Document
public Document(List<? extends Content> content)
Document
, with the supplied list of content, and a DocType
declaration only if the content contains a DocType instance. From source file:de.danielluedecke.zettelkasten.tasks.importtasks.ImportFromZkn.java
License:Open Source License
/** * //from w w w .j a v a 2s . c o m * @param app * @param parent * @param label * @param td * @param d * @param bm * @param dt * @param sr * @param ac * @param s * @param syn * @param stn * @param fp * @param a2u * @param appendit * @param rd * @param dts */ public ImportFromZkn(org.jdesktop.application.Application app, javax.swing.JDialog parent, javax.swing.JLabel label, TasksData td, Daten d, Bookmarks bm, DesktopData dt, SearchRequests sr, Settings s, File fp, boolean a2u, boolean appendit, String dts) { super(app); // init of the variable either passed as parameters or initiated the first time dataObj = d; taskinfo = td; bookmarksObj = bm; desktopObj = dt; searchrequestsObj = sr; settingsObj = s; parentDialog = parent; msgLabel = label; filepath = fp; atou = a2u; append = appendit; defaulttimestamp = dts; if (null == defaulttimestamp) { defaulttimestamp = Tools.getTimeStamp(); } taskinfo.setImportOk(true); // initiate the XML file dummyXML = new Document(new Element("zettelkasten")); // set default import message msgLabel.setText(resourceMap.getString("importDlgMsgImport")); }
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;/*from 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.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. //// ww w . ja v a 2s . c o m // TODO unique-Zettel-IDs durch Verweise auf entsprechende Zettel (Zettelnummer) ersetzen. // dies gilt fr: // - Schreibtischdaten // - Suchergebnisse // create dummy-documents, where the imported data is stored. Document zkn3Doc = new Document(new Element("zettelkasten")); Document author3Doc = new Document(new Element("authors")); Document keyword3Doc = new Document(new Element(Daten.ELEMENT_KEYWORD)); Document bookmark3Doc = new Document(new Element("bookmarks")); Document search3Doc = new Document(new Element("searches")); Document desktop3Doc = new Document(new Element("desktops")); Document desktopModifiedEntries3Doc = new Document(new Element("modifiedEntries")); Document meta3Doc = new Document(new Element("metainformation")); try { // it looks like the SAXBuilder is closing an input stream. So we have to // re-open the ZIP-file each time we want to retrieve an XML-file from it // this is necessary, because we want tot retrieve the zipped xml-files // *without* temporarily saving them to harddisk for (int cnt = 0; cnt < dataObj.getFilesToLoadCount(); cnt++) { // open the zip-file ZipInputStream zip = new ZipInputStream(new FileInputStream(filepath)); ZipEntry zentry; // now iterate the zip-file, searching for the requested file in it while ((zentry = zip.getNextEntry()) != null) { String entryname = zentry.getName(); // if the found file matches the requested one, start the SAXBuilder if (entryname.equals(dataObj.getFileToLoad(cnt))) { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(zip); // compare, which file we have retrieved, so we store the data // correctly on our data-object if (entryname.equals(Constants.metainfFileName)) { meta3Doc = doc; } if (entryname.equals(Constants.zknFileName)) { zkn3Doc = doc; } if (entryname.equals(Constants.authorFileName)) { author3Doc = doc; } if (entryname.equals(Constants.keywordFileName)) { keyword3Doc = doc; } if (entryname.equals(Constants.bookmarksFileName)) { bookmark3Doc = doc; } if (entryname.equals(Constants.searchrequestsFileName)) { search3Doc = doc; } if (entryname.equals(Constants.desktopFileName)) { desktop3Doc = doc; } if (entryname.equals(Constants.desktopModifiedEntriesFileName)) { desktopModifiedEntries3Doc = doc; } break; } catch (JDOMException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } } } zip.close(); } // retrieve version-element Element ver_el = meta3Doc.getRootElement().getChild("version"); // store fileformat-information String importedFileFormat = ""; // check whether it's null or not if (null == ver_el) { taskinfo.setImportOk(false); } else { // get data-version of imported file importedFileFormat = ver_el.getAttributeValue("id"); float lv = Float.parseFloat(importedFileFormat); // get fileversion of backward compatibility // float cv = Float.parseFloat(currentFileFormat); float cv = Float.parseFloat(Daten.backwardCompatibleVersion); // check whether the current data-version is newer than the loaded one taskinfo.setImportOk(lv >= cv); } // if we have not the right file-format, tell this the user... if (!taskinfo.isImportOk()) { // log error-message Constants.zknlogger.log(Level.WARNING, "Failed when importing Zettelkasten-data. Import-Fileversion: {0} Requested Fileversion: {1}", new Object[] { importedFileFormat, Daten.backwardCompatibleVersion }); // display error message box JOptionPane.showMessageDialog(null, resourceMap.getString("importDlgErrWrongFileFormat", Daten.backwardCompatibleVersion, importedFileFormat), resourceMap.getString("importDglErrTitle"), JOptionPane.PLAIN_MESSAGE); // leave thread return null; } // remove all entries with identical ID, because we can't have these entries twice // in the database. if the user wants to update entries (with same IDs), the synch feature // can be used. removeDoubleEntries(zkn3Doc); // get the length of the data final int len = zkn3Doc.getRootElement().getContentSize(); // reset the progressbar setProgress(0, 0, len); msgLabel.setText(resourceMap.getString("importDlgMsgEdit")); // // at first, add the description of the new importet zettelkasten // // get the child element Element el = meta3Doc.getRootElement().getChild(Daten.ELEMEMT_DESCRIPTION); // if we have any element, add description if (el != null) { dataObj.addZknDescription(el.getText()); } // // now, convert the old index-numbers of the authors and keywords // to the new numbers and add the entries to the existing data file // // go through all entries and prepare them and add them to the // main data file. especially the new author- and keyword-index-numbers // have to be prepared for (int cnt = 0; cnt < len; cnt++) { // get each child Element z = (Element) zkn3Doc.getRootElement().getContent(cnt); // we only need to convert the author- and keyword-index-numbers. // first we start with the author-index-numbers... // if the author-element is not empty... if (!z.getChild(Daten.ELEMENT_AUTHOR).getText().isEmpty()) { // ...get the autors indexnumbers String[] aun = z.getChild(Daten.ELEMENT_AUTHOR).getText().split(","); // create new stringbuilder that will contain the new index-numbers StringBuilder sb = new StringBuilder(""); // iterate the array for (int c = 0; c < aun.length; c++) { // get the related author-element from the author-file. // the needed author-index-number is stored as integer (string-value) // in the author-indexnumbers-array "aun". Element dummyauthor = (Element) author3Doc.getRootElement() .getContent(Integer.parseInt(aun[c]) - 1); // get the string value for that author String authorstring = dummyauthor.getText(); // if we have any author, go on.. if (!authorstring.isEmpty()) { // add author to the data file // and store the position of the new added author in the // variable authorPos int authorPos = dataObj.addAuthor(authorstring, 1); // store author position as string value sb.append(String.valueOf(authorPos)); sb.append(","); } } // truncate last comma if (sb.length() > 1) { sb.setLength(sb.length() - 1); } // set new author-index-numbers z.getChild(Daten.ELEMENT_AUTHOR).setText(sb.toString()); } // now that the authors are converted, we need to convert // the keyword-index-numbers // if the keyword-element is not empty... if (!z.getChild(Daten.ELEMENT_KEYWORD).getText().isEmpty()) { // ...get the keywords-index-numbers String[] kwn = z.getChild(Daten.ELEMENT_KEYWORD).getText().split(","); // create new stringbuilder that will contain the new index-numbers StringBuilder sb = new StringBuilder(""); // iterate the array for (int c = 0; c < kwn.length; c++) { // get the related keyword-element from the keyword-file. // the needed keyword-index-number is stored as integer (string-value) // in the keyword-indexnumbers-array "kwn". Element dummykeyword = (Element) keyword3Doc.getRootElement() .getContent(Integer.parseInt(kwn[c]) - 1); // get the string value for that keyword String keywordstring = dummykeyword.getText(); // if we have any keywords, go on.. if (!keywordstring.isEmpty()) { // add it to the data file // and store the position of the new added keyword in the // variable keywordPos int keywordPos = dataObj.addKeyword(keywordstring, 1); // store author position as string value sb.append(String.valueOf(keywordPos)); sb.append(","); } } // truncate last comma if (sb.length() > 1) { sb.setLength(sb.length() - 1); } // set new keyword-index-numbers z.getChild(Daten.ELEMENT_KEYWORD).setText(sb.toString()); } // update progressbar setProgress(cnt, 0, len); } // now that all entries are converted, append the data to the existing file dataObj.appendZknData(zkn3Doc); // TODO append desktop-data // TODO append search-data // append bookmarks bookmarksObj.appendBookmarks(dataObj, bookmark3Doc); } catch (IOException e) { Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); } return null; // return your result }
From source file:de.danielluedecke.zettelkasten.ZettelkastenView.java
License:Open Source License
/** * //from w ww . j a v a 2s .c om * @param exportlist * @param type */ private void exportList(LinkedList<String> exportlist, String type) { String formats = getResourceMap().getString("exportListFormat1") + "," + getResourceMap().getString("exportListFormat2") + "," + getResourceMap().getString("exportListFormat3"); if (type.equalsIgnoreCase("authors")) formats = formats + "," + getResourceMap().getString("exportListFormat4"); Object[] choice = formats.split(","); Object expo = JOptionPane.showInputDialog(getFrame(), getResourceMap().getString("exportListFormatMsg"), getResourceMap().getString("exportListFormatTitle"), JOptionPane.PLAIN_MESSAGE, null, choice, null); // check for valid return value or cancel-operation of user if (expo != null) { // convert object to string String exportformat = expo.toString(); // check for valid file extenstion if (exportformat.equalsIgnoreCase(getResourceMap().getString("exportListFormat4"))) exportformat = "bib"; // here we open a swing filechooser, in case the os ist no mac aqua File filepath = FileOperationsUtil.chooseFile(getFrame(), (settings.isMacAqua()) ? FileDialog.SAVE : JFileChooser.SAVE_DIALOG, JFileChooser.FILES_ONLY, null, null, getResourceMap().getString("exportListFormatTitle"), new String[] { "." + exportformat.toLowerCase() }, expo.toString(), settings); // if we have any valid if (filepath != null) { // init extension-string String ext = null; // retrieve fileextension, in case the user does not enter a fileextension later... if (exportformat.equals(getResourceMap().getString("exportListFormat1"))) ext = "." + getResourceMap().getString("exportListFormat1").toLowerCase(); if (exportformat.equals(getResourceMap().getString("exportListFormat2"))) ext = "." + getResourceMap().getString("exportListFormat2").toLowerCase(); if (exportformat.equals(getResourceMap().getString("exportListFormat3"))) ext = "." + getResourceMap().getString("exportListFormat3").toLowerCase(); if (exportformat.equals("bib")) ext = ".bib"; // check whether the user entered a file extension. if not, add "ext" as extension if (!filepath.getName().toLowerCase().endsWith(ext)) filepath = new File(filepath.getPath() + ext); // if file does not exist, create it - otherwise the getFilePath-method of // the settings-class would return "null" as filepath, if file doesn't exist if (!filepath.exists()) { try { filepath.createNewFile(); } catch (IOException ex) { Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); } } else { // file exists, ask user to overwrite it... int optionDocExists = JOptionPane.showConfirmDialog(getFrame(), getResourceMap().getString("askForOverwriteFileMsg"), getResourceMap().getString("askForOverwriteFileTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); // if the user does *not* choose to overwrite, quit... if (optionDocExists != JOptionPane.YES_OPTION) return; } // create variable that indicates errors... boolean errorOccured = false; // sort list aphabetically before exporting it Collections.sort(exportlist, new Comparer()); // here startes the export of xml-data if (exportformat.equals(getResourceMap().getString("exportListFormat1"))) { // create new document Document exportfile = new Document(new Element(type)); // create list-iterator Iterator<String> i = exportlist.iterator(); // iterate exportlist while (i.hasNext()) { // create new element Element e = new Element(Daten.ELEMENT_ENTRY); // at element from the list e.setText(i.next()); // add element to the document exportfile.getRootElement().addContent(e); } // save the xml-file try { // open the outputstream FileOutputStream fos = new FileOutputStream(filepath); // create a new XML-outputter with the pretty output format, // so the xml-file looks nicer XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); try { // save the main-export-file out.output(exportfile, fos); // close the output stream fos.close(); } catch (IOException e) { // log error-message Constants.zknlogger.log(Level.SEVERE, e.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } } catch (FileNotFoundException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } } else if (exportformat.equals("bib")) { ByteArrayOutputStream bout = null; OutputStream exportfile = null; try { bout = bibtex.saveFile(); // create filewriter exportfile = new FileOutputStream(filepath); // retrieve string String bibdata = bout.toString("UTF-8"); // write content exportfile.write(bibdata.getBytes(Charset.forName("UTF-8"))); } catch (FileNotFoundException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; } finally { try { if (bout != null) bout.close(); if (exportfile != null) exportfile.close(); } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage()); errorOccured = true; } } } else { // create stringbuilder for the final content StringBuilder finalcontent = new StringBuilder(""); // create list-iterator Iterator<String> i = exportlist.iterator(); // here startes the export of txt-data if (exportformat.equals(getResourceMap().getString("exportListFormat2"))) { // iterate exportlist and copy each list-element to the string, separated by new lines while (i.hasNext()) finalcontent.append(i.next()).append(System.getProperty("line.separator")); } // here startes the export of html-data else if (exportformat.equals(getResourceMap().getString("exportListFormat3"))) { // init html-page finalcontent.append("<html><head></head><body><ol>") .append(System.getProperty("line.separator")); // iterate exportlist and copy each list-element to the string, separated by new lines while (i.hasNext()) { // create dummy string to convert German umlauts String dummy = i.next(); // convert special chars to html dummy = dummy.replace("&", "&"); dummy = dummy.replace("\"", """); dummy = dummy.replace("", "ä"); dummy = dummy.replace("", "Ä"); dummy = dummy.replace("", "ö"); dummy = dummy.replace("", "Ö"); dummy = dummy.replace("", "ü"); dummy = dummy.replace("", "Ü"); dummy = dummy.replace("", "ß"); // append converted author to stringbuilder finalcontent.append("<li>").append(dummy).append("</li>") .append(System.getProperty("line.separator")); } // close html-page finalcontent.append(System.getProperty("line.separator")).append("</ol></body></html>"); } // init output-filewriter Writer exportfile = null; try { // create filewriter exportfile = new FileWriter(filepath); // and save file to disk exportfile.write(finalcontent.toString()); } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } finally { try { // finally, close filewrite if (exportfile != null) { exportfile.close(); } } catch (IOException ex) { // log error-message Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage()); errorOccured = true; // show error message JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("errorSavingMsg"), getResourceMap().getString("errorSavingTitle"), JOptionPane.PLAIN_MESSAGE); } } } // if an errors occured, show error-log if (errorOccured) { showErrorIcon(); } else { JOptionPane.showMessageDialog(getFrame(), getResourceMap().getString("exportOkMsg"), getResourceMap().getString("exportOkTitle"), JOptionPane.PLAIN_MESSAGE); } } } }
From source file:de.herm_detlef.java.application.io.Export.java
License:Apache License
private static Document createJdomDocument(ObservableList<ExerciseItem> exerciseItemList) { Namespace ns = Namespace.getNamespace(ApplicationConstants.XML_NAMESPACE); Element catalog = new Element(TAG.CATALOG.name(), ns); Document doc = new Document(catalog); Namespace xsi = Namespace.getNamespace("xsi", ApplicationConstants.XML_SCHEMA_INSTANCE); doc.getRootElement().addNamespaceDeclaration(xsi); doc.getRootElement().setAttribute("schemaLocation", ApplicationConstants.XML_SCHEMA_DEFINITION, xsi); int count = 0; for (ExerciseItem exItem : exerciseItemList) { Element item = new Element(TAG.ITEM.name(), ns); catalog.addContent(item);//from ww w . j a va 2 s.c om Element id = new Element(TAG.ID.name(), ns); id.addContent(String.valueOf(++count)); item.addContent(id); Element element = null; for (ItemPart itemPart : exItem.getExerciseItemParts()) { Object obj = itemPart.get(); if (obj == null) { // assert false : String.format( // "%s", // itemPart.getClass() ); // TODO continue; } if (itemPart instanceof QuestionText || itemPart instanceof QuestionText2) { isAnswerPart = false; if (!isQuestionPart) { element = new Element(TAG.QUESTION.name(), ns); item.addContent(element); isQuestionPart = true; } if (element == null) continue; if (itemPart instanceof QuestionText) { Element text = new Element(TAG.TEXT.name(), ns); element.addContent(text); text.addContent(((QuestionText) itemPart).getStr().get()); } if (itemPart instanceof QuestionText2) { Element text = new Element(TAG.TEXT2.name(), ns); element.addContent(text); text.addContent(((QuestionText2) itemPart).getStr().get()); } } else if (itemPart instanceof QuestionCode) { isAnswerPart = false; if (!isQuestionPart) { element = new Element(TAG.QUESTION.name(), ns); item.addContent(element); isQuestionPart = true; } if (element == null) continue; Element code = new Element(TAG.CODE.name(), ns); element.addContent(code); code.addContent(((QuestionCode) itemPart).getStr().get()); } else if (itemPart instanceof SingleChoiceAnswerText) { isQuestionPart = false; if (!isAnswerPart) { element = new Element(TAG.SINGLE_CHOICE_ANSWER.name(), ns); item.addContent(element); isAnswerPart = true; } if (element == null) continue; Element answer = new Element(TAG.TEXT.name(), ns); element.addContent(answer); if (((AnswerText) itemPart).isMarked()) { Attribute mark = new Attribute("mark", "true"); answer.setAttribute(mark); } answer.addContent(((SingleChoiceAnswerText) itemPart).getStr().get()); } else if (itemPart instanceof MultipleChoiceAnswerText) { isQuestionPart = false; if (!isAnswerPart) { element = new Element(TAG.MULTIPLE_CHOICE_ANSWER.name(), ns); item.addContent(element); isAnswerPart = true; } if (element == null) continue; Element answer = new Element(TAG.TEXT.name(), ns); element.addContent(answer); if (((AnswerText) itemPart).isMarked()) { Attribute mark = new Attribute("mark", "true"); answer.setAttribute(mark); } answer.addContent(((MultipleChoiceAnswerText) itemPart).getStr().get()); } else if (itemPart instanceof SolutionText) { isQuestionPart = false; isAnswerPart = false; element = new Element(TAG.SOLUTION.name(), ns); item.addContent(element); Element solution = new Element(TAG.TEXT.name(), ns); element.addContent(solution); solution.addContent(((SolutionText) itemPart).getStr().get()); } if (element == null) { assert false; return null; } } } return doc; }
From source file:de.huberlin.german.korpling.laudatioteitool.MergeTEI.java
License:Apache License
public void merge() throws LaudatioException { try {/*from ww w . ja va 2 s .co m*/ if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { throw new LaudatioException( messages.getString("COULD NOT CREATE MERGED OUTPUTFILE: I CAN'T CREATE THE DIRECTORIES")); } Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element root = new Element("teiCorpus", teiNS); Element documentRoot = new Element("teiCorpus", teiNS); Element preparationRoot = new Element("teiCorpus", teiNS); mergeMainCorpusHeader(root); mergeDocumentHeader(documentRoot); mergePreparationHeader(preparationRoot); root.addContent(documentRoot); documentRoot.addContent(documentRoot.getChildren().size(), preparationRoot); Document mergedDoc = new Document(root); // output the new XML XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(mergedDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN MERGED TEI"), outputFile.getPath()); } catch (SAXException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } catch (JDOMException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } catch (IOException ex) { throw new LaudatioException(ex.getLocalizedMessage()); } }
From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java
License:Apache License
private TEIValidator.Errors extractMainCorpusHeader(Document doc) throws LaudatioException, IOException, SAXException { TEIValidator validator = corpusSchemeURL == null ? new TEICorpusValidator() : new FromURLValidator(corpusSchemeURL); Element corpusHeader = doc.getRootElement().getChild("teiHeader", null); if (corpusHeader != null) { File corpusDir = new File(outputDirectory, "CorpusHeader"); if (!corpusDir.exists() && !corpusDir.mkdir()) { throw new LaudatioException( messages.getString("COULD NOT CREATE DIRECTORY") + corpusDir.getAbsolutePath()); }// w w w .j a v a 2 s.c om // create the subtree for the global corpus header Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element newRootForCorpus = new Element("TEI", teiNS); newRootForCorpus.addContent(corpusHeader.clone()); Document corpusDoc = new Document(newRootForCorpus); if (corpusSchemeURL == null) { corpusDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + TEICorpusValidator.DEFAULT_SCHEME_URL + "\"")); } else { corpusDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + corpusSchemeURL + "\"")); } // we need to append an empty "text" element after the header Element text = new Element("text", teiNS); text.setText(""); newRootForCorpus.addContent(text); // we work with the copy from now corpusHeader = newRootForCorpus.getChild("teiHeader", null); Preconditions.checkNotNull(corpusHeader, messages.getString("ERROR NO CORPUS TITLE GIVEN")); Preconditions.checkState("CorpusHeader".equals(corpusHeader.getAttributeValue("type"))); Preconditions.checkNotNull(corpusHeader.getChild("fileDesc", null), messages.getString("ERROR NO CORPUS TITLE GIVEN")); Preconditions.checkNotNull(corpusHeader.getChild("fileDesc", null).getChild("titleStmt", null), messages.getString("ERROR NO CORPUS TITLE GIVEN")); String title = corpusHeader.getChild("fileDesc", null).getChild("titleStmt", null) .getChildTextNormalize("title", null); Preconditions.checkNotNull(title, messages.getString("ERROR NO CORPUS TITLE GIVEN")); // save the file with the title as file name File outputFile = new File(corpusDir, title + ".xml"); XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(corpusDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN CORPUS HEADER"), outputFile.getPath()); validator.validate(outputFile); } return validator.getErrors(); }
From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java
License:Apache License
private TEIValidator.Errors extractDocumentHeaders(Document doc) throws LaudatioException, IOException, SAXException { TEIValidator validator = documentSchemeURL == null ? new TEIDocumentValidator() : new FromURLValidator(documentSchemeURL); File documentDir = new File(outputDirectory, "DocumentHeader"); if (!documentDir.exists() && !documentDir.mkdir()) { throw new LaudatioException( messages.getString("COULD NOT CREATE DIRECTORY") + documentDir.getAbsolutePath()); }/*from ww w. j ava 2 s. c om*/ Element documentRoot = Preconditions.checkNotNull(doc.getRootElement().getChild("teiCorpus", null)); for (Element docHeader : documentRoot.getChildren("teiHeader", null)) { Preconditions.checkState("DocumentHeader".equals(docHeader.getAttributeValue("type"))); // create the subtree for the global corpus header Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element tei = new Element("TEI", teiNS); tei.addContent(docHeader.clone()); Document newDoc = new Document(tei); if (documentSchemeURL == null) { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + TEIDocumentValidator.DEFAULT_SCHEME_URL + "\"")); } else { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + documentSchemeURL + "\"")); } // we need to append an empty "text" element after the header Element text = new Element("text", teiNS); text.setText(""); tei.addContent(text); Element fileDesc = Preconditions .checkNotNull(tei.getChild("teiHeader", null).getChild("fileDesc", null)); String outName = UUID.randomUUID().toString(); String id = fileDesc.getAttributeValue("id", Namespace.XML_NAMESPACE); if (id != null) { outName = id; } else { Element titleStmt = Preconditions.checkNotNull(fileDesc.getChild("titleStmt", null)); String title = titleStmt.getChildText("title", null); if (title != null) { outName = title; } } File outputFile = new File(documentDir, outName + ".xml"); XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(newDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN DOCUMENT HEADER"), outputFile.getPath()); validator.validate(outputFile); } return validator.getErrors(); }
From source file:de.huberlin.german.korpling.laudatioteitool.SplitTEI.java
License:Apache License
private TEIValidator.Errors extractPreparationSteps(Document doc) throws LaudatioException, IOException, SAXException { TEIValidator validator = preparationSchemeURL == null ? new TEIPreparationValidator() : new FromURLValidator(preparationSchemeURL); Multiset<String> knownPreparationTitles = HashMultiset.create(); File documentDir = new File(outputDirectory, "PreparationHeader"); if (!documentDir.exists() && !documentDir.mkdir()) { throw new LaudatioException( messages.getString("COULD NOT CREATE DIRECTORY") + documentDir.getAbsolutePath()); }//from w ww.j a va 2s . c o m Preconditions.checkNotNull(doc.getRootElement().getChild("teiCorpus", null)); Element preparationRoot = Preconditions .checkNotNull(doc.getRootElement().getChild("teiCorpus", null).getChild("teiCorpus", null)); for (Element preparationHeader : preparationRoot.getChildren("teiHeader", null)) { Preconditions.checkState("PreparationHeader".equals(preparationHeader.getAttributeValue("type"))); // create the subtree for the global corpus header Namespace teiNS = Namespace.getNamespace("http://www.tei-c.org/ns/1.0"); Element tei = new Element("TEI", teiNS); tei.addContent(preparationHeader.clone()); Document newDoc = new Document(tei); if (preparationSchemeURL == null) { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + TEIPreparationValidator.DEFAULT_SCHEME_URL + "\"")); } else { newDoc.addContent(0, new ProcessingInstruction("xml-model", "href=\"" + preparationSchemeURL + "\"")); } // we need to append an empty "text" element after the header Element text = new Element("text", teiNS); text.setText(""); tei.addContent(text); Element fileDesc = Preconditions .checkNotNull(tei.getChild("teiHeader", null).getChild("fileDesc", null)); String outName = UUID.randomUUID().toString(); Element titleStmt = Preconditions.checkNotNull(fileDesc.getChild("titleStmt", null)); Element title = Preconditions.checkNotNull(titleStmt.getChild("title", null)); String corresp = title.getAttributeValue("corresp"); if (corresp != null) { if (knownPreparationTitles.contains(corresp)) { knownPreparationTitles.add(corresp); outName = corresp + "_" + knownPreparationTitles.count(corresp); log.warn(messages.getString("MORE THAN ONE PREPARATION HEADER"), corresp); } else { outName = corresp; knownPreparationTitles.add(corresp); } } File outputFile = new File(documentDir, outName + ".xml"); XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(newDoc, new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); log.info(messages.getString("WRITTEN PREPARATION HEADER"), outputFile.getPath()); validator.validate(outputFile); } return validator.getErrors(); }
From source file:de.ing_poetter.binview.BinaryFormat.java
License:Open Source License
public void saveToFile(final File f) throws IOException { final Element root = new Element(ROOT_ELEMENT_NAME); for (int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final Element res = v.save(); root.addContent(res);/*from ww w .java2 s.com*/ } final Document doc = new Document(root); final XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); final FileOutputStream bout = new FileOutputStream(f); xout.output(doc, bout); bout.flush(); bout.close(); }