Revision: fa5d56c3e290 Branch: rt2091-tPagesGui Author: Corey Knapp <cknapp.code@xxxxxxxxx> Date: Thu Feb 26 18:17:58 2015 UTC Log: Inserts properly formatted XML into document https://code.google.com/p/brailleblaster/source/detail?r=fa5d56c3e290 Modified: /src/main/org/brailleblaster/perspectives/braille/Manager.java/src/main/org/brailleblaster/perspectives/braille/document/BrailleDocument.java
/src/main/org/brailleblaster/tpages/TPagesDialog.java /src/main/org/brailleblaster/tpages/TPagesGenerator.java =======================================--- /src/main/org/brailleblaster/perspectives/braille/Manager.java Fri Feb 13 20:32:12 2015 UTC +++ /src/main/org/brailleblaster/perspectives/braille/Manager.java Thu Feb 26 18:17:58 2015 UTC
@@ -682,6 +682,10 @@ text.refreshStyle(list.getCurrent()); braille.refreshStyle(list.getCurrent()); } + + public void insertTPage(Element tPageRoot){ + + } private void handleMergeElement(Message message){ MergeElementHandler meh = new MergeElementHandler(this, vi, list); =======================================--- /src/main/org/brailleblaster/perspectives/braille/document/BrailleDocument.java Fri Jan 30 18:10:06 2015 UTC +++ /src/main/org/brailleblaster/perspectives/braille/document/BrailleDocument.java Thu Feb 26 18:17:58 2015 UTC
@@ -889,6 +889,40 @@ return mergedElement; } + public void addTPage(Element tPageRoot){ + // TODO: needs to check for existing tpage node and replace it + addNamespace(tPageRoot); + Element fmNode = findFrontMatter(doc.getRootElement()); + + if(fmNode!=null){ + fmNode.insertChild(tPageRoot,0); + } + } + + public void editTPage(Element newTPage, Element prevTPage){ + addNamespace(newTPage); + Element fmNode = findFrontMatter(doc.getRootElement()); + + if(fmNode!=null){ + fmNode.removeChild(prevTPage); + fmNode.insertChild(newTPage, 0); + } + } + + private Element findFrontMatter(Element parent){ + Element returnElement = null; + Elements children = parent.getChildElements(); + for(int i = 0; i < children.size(); i++){ + if(children.get(i).getLocalName().equalsIgnoreCase("frontmatter")){ + returnElement = children.get(i); + break; + } else { + returnElement = findFrontMatter(children.get(i)); + } + } + return returnElement; + } + public void addID(Element e){ idCount++;e.addAttribute(new Attribute("id", BBIni.getInstanceID() + "_" + idCount));
=======================================--- /src/main/org/brailleblaster/tpages/TPagesDialog.java Mon Feb 23 20:58:07 2015 UTC +++ /src/main/org/brailleblaster/tpages/TPagesDialog.java Thu Feb 26 18:17:58 2015 UTC
@@ -1,7 +1,6 @@ package org.brailleblaster.tpages; import java.util.HashMap; - import org.brailleblaster.perspectives.braille.Manager; import org.brailleblaster.tpages.TPagesGenerator; import org.eclipse.swt.SWT; @@ -48,6 +47,8 @@ HashMap<String, String> xmlmap;Group titleGroup, authorGroup, printGroup, publisherGroup, transcriberGroup, volumesGroup;
Boolean changed = false; + Boolean existingTPage = false; + nu.xom.Element prevTPage = null; final String WINDOW_TITLE = "Transcriber-Generated Pages";public TPagesDialog(Shell parent, int style, Manager brailleViewController){
@@ -61,10 +62,13 @@ xmlmap = tpGenerator.getXmlMap(); createContents(); - if(m.getLastTPage()!=null){ - if(tpGenerator.checkForFile(m.getLastTPage())){ - openFromXml(m.getLastTPage()); - } + nu.xom.Element tPageRoot = tpGenerator.getTPageElement(m.getDoc()); + + if(tPageRoot!=null){ + existingTPage = true; + prevTPage = (nu.xom.Element) tPageRoot.getParent(); + xmlmap = tpGenerator.pullFromElement(tPageRoot); + xmlmap.put("template", tpGenerator.elementToTemplate(tPageRoot)); } updateContents(); shlTPages.setText(WINDOW_TITLE); @@ -131,7 +135,7 @@ public void widgetSelected(SelectionEvent e){ if(m.getDocumentName()!=null){if(m.getDocumentName().toLowerCase().substring(m.getDocumentName().length()-4).equals(".xml")){
- tpGenerator.autoPopulate(m.getDocumentName()); + tpGenerator.autoPopulate(m.getDoc()); updateContents(); } } @@ -443,7 +447,7 @@ @Override public void widgetSelected(SelectionEvent e) { - templateText.insert("(" + xmlList.getSelection()[0] + ")"); + templateText.insert("<" + xmlList.getSelection()[0] + ">"); xmlList.deselectAll(); } @@ -480,7 +484,7 @@ } }); - Button openButton = new Button(shlTPages, SWT.PUSH); + /*Button openButton = new Button(shlTPages, SWT.PUSH); buttonData = new GridData(SWT.CENTER, SWT.BEGINNING, false, false, 1, 1); buttonData.widthHint = 100; buttonData.heightHint = 30; @@ -538,7 +542,7 @@ public void widgetDefaultSelected(SelectionEvent arg0) { } - }); + });*/ Label spacingLabel2 = new Label(shlTPages, SWT.NONE);GridData spacingLabelData = new GridData(SWT.CENTER, SWT.BEGINNING, false, false, 1, 1);
@@ -549,7 +553,7 @@ buttonData = new GridData(SWT.RIGHT, SWT.BEGINNING, false, false, 1, 1); buttonData.widthHint = 120; buttonData.heightHint = 30; - generateButton.setText("Generate T-Pages"); + generateButton.setText("Insert"); generateButton.setLayoutData(buttonData); generateButton.addSelectionListener(new SelectionListener() { @@ -560,13 +564,12 @@ @Override public void widgetSelected(SelectionEvent arg0) { saveCurrentGroup(); - FileDialog saveFile = new FileDialog(shlTPages, SWT.SAVE); - saveFile.setFilterExtensions(new String[] {"*.xml"}); - String result = saveFile.open(); - if(result!=null){ - m.setLastTPage(result); - tpGenerator.generateTPage(templateText.getText(), result); + if(existingTPage){+ m.document.editTPage(tpGenerator.getTPageParent(templateText.getText()), prevTPage);
+ } else {+ m.document.addTPage(tpGenerator.getTPageParent(templateText.getText()));
} + m.refresh(); } }); @@ -658,13 +661,6 @@ stringToTable(xmlmap.get("specialsymbols"), symbolsTable); } - private boolean openFromXml(String filepath){ - if(filepath!=null){ - if(tpGenerator.openTPageXML(filepath)) - return true; - } - return false; - } private GridData newTpData(int columns){return new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, columns, 1);
} @@ -857,7 +853,7 @@ } } - /*Used when creating tpage xml file*/ + /*Used when creating tpage xml element */ private String tableToString(Table table){ String returnString = ""; @@ -878,9 +874,10 @@ return returnString; } - /*Used when reading xml file*/ + /*Used when reading from tpage xml element*/ private void stringToTable(String string, Table table){ + table.removeAll(); if(string.contains("||")){String[] splitString = string.split("\\|\\|"); // "|" has to be escaped because it is a regex character
for(String newString : splitString){ =======================================--- /src/main/org/brailleblaster/tpages/TPagesGenerator.java Mon Feb 23 20:58:07 2015 UTC +++ /src/main/org/brailleblaster/tpages/TPagesGenerator.java Thu Feb 26 18:17:58 2015 UTC
@@ -1,113 +1,38 @@ package org.brailleblaster.tpages; import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.brailleblaster.BBIni; +import nu.xom.Document; +import nu.xom.Element; +import nu.xom.Nodes; +import nu.xom.Elements; +import nu.xom.XPathContext; +import nu.xom.Attribute; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentType; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.NodeList; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; -/* - * Handles reading from and writing to XML - */ +/* Handles creation of XML elements */ public class TPagesGenerator { String programDataPath;String[] xmlElements = {"booktitle", "gradelevel", "subtitle", "seriesname", "editionname", "authors", "translator", "publisherpermission", "publisher", "publisherlocation", "publisherwebsite", "copyrighttext", "reproductionnotice", "isbn13", "isbn10", "printhistory", "transcriptionyear", "transcriber", "tgs", "affiliation", "totalvolumes", "volumenumber", "customizedbraille", - "braillepageinfo", "printpageinfo", "transcribernotes", "template", "specialsymbols"}; - String copyright, isbn13 = "", isbn10 = "", printHistoryGuess, titleGuess, authorGuess, publisherGuess, websiteGuess; - final String defaultTemplate = "(booktitle): (gradelevel)\n(subtitle)\n(seriesname)\n(editionname)\n(authors)\n(linebreak)\n(publisherpermission)" - + "\n(publisher)\n(publisherwebsite)\n(linebreak)\n(copyrighttext)\n(reproductionnotice)\nTranscription of:\n" - + " ISBN-13: (isbn13)\n ISBN-10: (isbn10)\n(printhistory)\nTranscribed (transcriptionyear) by\n(transcriber)\n" - + "(linebreak)\n(totalvolumes)\n(volumenumber)\n(customizedbraille)\n(braillepageinfo)\n(printpageinfo)\n(linebreak)\n";
+ "braillepageinfo", "printpageinfo", "transcribernotes", "template"};+ String copyright, isbn13 = "", isbn10 = "", printHistoryGuess, titleGuess, authorGuess = "", publisherGuess, websiteGuess; + final String defaultTemplate = "<booktitle>: <gradelevel>\n<subtitle>\n<seriesname>\n<editionname>\n<authors>\n<linebreak>\n<publisherpermission>" + + "\n<publisher>\n<publisherwebsite>\n<linebreak>\n<copyrighttext>\n<reproductionnotice>\nTranscription of:\n" + + " ISBN-13: <isbn13>\n ISBN-10: <isbn10>\n<printhistory>\nTranscribed <transcriptionyear> by\n<transcriber>\n" + + "<linebreak>\n<totalvolumes>\n<volumenumber>\n<customizedbraille>\n<braillepageinfo>\n<printpageinfo>\n<linebreak>\n";
private HashMap<String, String> xmlmap; public TPagesGenerator(){ programDataPath = BBIni.getProgramDataPath(); xmlmap = getEmptyXmlMap(); - } - - /* - * Reload previously made T-Page - */ - public boolean openTPageXML(String filename){ - try{ - if(checkForFile(filename)){ - File file = new File(filename); -- DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document doc = docBuilder.parse(file); - doc.getDocumentElement().normalize(); - if(doc.getFirstChild().getNodeType() == Node.ELEMENT_NODE){ - Element rootE = (Element)doc.getFirstChild(); - if(!doc.getFirstChild().getNodeName().equals("dtbook")){ - if(!rootE.getAttribute("type").equals("tpage")) - return false; - } - } - for (int i = 0; i < xmlElements.length; i++){- xmlmap.put(xmlElements[i], doc.getElementsByTagName(xmlElements[i]).item(0).getTextContent());
- } - String tempAuthorString = "";- for (int q = 0; q < doc.getElementsByTagName("author").getLength(); q++){ - tempAuthorString += ";" + doc.getElementsByTagName("author").item(q).getTextContent();
- }- while(tempAuthorString.length() > 0 && (tempAuthorString.charAt(0)==' ' || tempAuthorString.charAt(0)==';')){
- tempAuthorString = tempAuthorString.substring(1); - } - xmlmap.put("authors", tempAuthorString); - if(xmlmap.get("booktitle").contains(": ")) - xmlmap.put("booktitle", xmlmap.get("booktitle").replace(": ", "")); - xmlmap.put("isbn13", xmlmap.get("isbn13").replace(" ISBN-13: ", "")); - xmlmap.put("isbn10", xmlmap.get("isbn10").replace(" ISBN-10: ", "")); - if(xmlmap.get("transcriptionyear").contains("Transcribed")){- xmlmap.put("transcriptionyear", xmlmap.get("transcriptionyear").replace("Transcribed ", "")); - xmlmap.put("transcriptionyear", xmlmap.get("transcriptionyear").replace(" by", ""));
- } - xmlmap.put("transcriber", xmlmap.get("transcriber").replace(" ", ""));- xmlmap.put("tgs", xmlmap.get("tgs").replace("Tactile Graphics by ", "")); //This will need to change when I properly format it
- if(xmlmap.get("template")==null || xmlmap.get("template").equals("")){ - xmlmap.put("template", defaultTemplate); - } - - } else { - return false; - } - - - } catch(ParserConfigurationException e){ - e.printStackTrace(); - return false; - } catch(IOException e){ - e.printStackTrace(); - return false; - }catch (SAXException e){ - e.printStackTrace(); - return false; - } - - return true; + testXmlMap(); } public boolean checkForFile(String filename){ @@ -119,499 +44,408 @@ } } - /* - * User is using T-Pages for the first time. - */ - public boolean createNewTPageXML(String filename){ - try{- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document doc = docBuilder.newDocument();- DocumentType docType = doc.getImplementation().createDocumentType("doctype", "-//NISO//DTD dtbook 2005-3//EN", "http://www.daisy.org/z3986/2005/dtbook-2005-3.dtd";);
- - Element rootElement = doc.createElement("dtbook"); - rootElement.setAttribute("type", "tpage"); - doc.appendChild(rootElement); - - Element bookElement = doc.createElement("book"); - rootElement.appendChild(bookElement); - - Element level1Element = doc.createElement("level1"); - bookElement.appendChild(level1Element); - - Element level2Element = doc.createElement("level2"); - level1Element.appendChild(level2Element); - - Element titleInfo = doc.createElement("titleinfo"); - level2Element.appendChild(titleInfo); - - Element ptag = newPTag(doc, titleInfo); - - Element title = doc.createElement("booktitle"); - ptag.appendChild(title); - Element gradeLevel = doc.createElement("gradelevel"); - ptag.appendChild(gradeLevel); - - newPTag(doc, titleInfo).appendChild(doc.createElement("subtitle")); - - newPTag(doc, titleInfo).appendChild(doc.createElement("seriesname")); - - newPTag(doc, titleInfo).appendChild(doc.createElement("editionname")); - - Element linebreak = doc.createElement("p");- linebreak.setTextContent(" "); //This is a non-breaking space. Coincidentally, this is a terrible line of code.
- level2Element.appendChild(linebreak); - - Element authorInfo = doc.createElement("authorinfo"); - level2Element.appendChild(authorInfo); - - newPTag(doc, authorInfo).appendChild(doc.createElement("authors")); - - newPTag(doc, authorInfo).appendChild(doc.createElement("translator")); - - Element linebreak2 = doc.createElement("p"); - linebreak2.setTextContent(" "); - level2Element.appendChild(linebreak2); - - Element publisherInfo = doc.createElement("publisherinfo"); - level2Element.appendChild(publisherInfo); - - Element ptag2 = newPTag(doc, publisherInfo); - ptag2.appendChild(doc.createElement("publisherpermission")); - ptag2.appendChild(doc.createElement("publisher")); -- newPTag(doc, publisherInfo).appendChild(doc.createElement("publisherlocation")); - newPTag(doc, publisherInfo).appendChild(doc.createElement("publisherwebsite"));
- - Element linebreak3 = doc.createElement("p"); - linebreak3.setTextContent(" "); - level2Element.appendChild(linebreak3); - - Element printInfo = doc.createElement("printinfo"); - level2Element.appendChild(printInfo); - - Element ptag3 = newPTag(doc, printInfo); - ptag3.appendChild(doc.createElement("copyrighttext")); -- newPTag(doc, printInfo).appendChild(doc.createElement("reproductionnotice"));
- newPTag(doc, printInfo).appendChild(doc.createElement("isbn13")); - newPTag(doc, printInfo).appendChild(doc.createElement("isbn10")); - newPTag(doc, printInfo).appendChild(doc.createElement("printhistory")); - - Element linebreak4 = doc.createElement("p"); - linebreak4.setTextContent(" "); - level2Element.appendChild(linebreak4); - - Element transcriptionInfo = doc.createElement("transcriptioninfo"); - level2Element.appendChild(transcriptionInfo); -- newPTag(doc, transcriptionInfo).appendChild(doc.createElement("transcriptionyear")); - newPTag(doc, transcriptionInfo).appendChild(doc.createElement("transcriber"));
- newPTag(doc, transcriptionInfo).appendChild(doc.createElement("tgs"));- newPTag(doc, transcriptionInfo).appendChild(doc.createElement("affiliation"));
-- newPTag(doc, transcriptionInfo).appendChild(doc.createElement("totalvolumes")); - newPTag(doc, transcriptionInfo).appendChild(doc.createElement("volumenumber")); - newPTag(doc, transcriptionInfo).appendChild(doc.createElement("customizedbraille")); - newPTag(doc, transcriptionInfo).appendChild(doc.createElement("braillepageinfo")); - newPTag(doc, transcriptionInfo).appendChild(doc.createElement("printpageinfo"));
- - Element linebreak5 = doc.createElement("p"); - linebreak5.setTextContent(" "); - level2Element.appendChild(linebreak5); - - Element level2ElementSS = doc.createElement("level2"); - level1Element.appendChild(level2ElementSS); - - Element ssHeader = doc.createElement("p"); - ssHeader.setTextContent("Special Symbols"); - level2ElementSS.appendChild(ssHeader);- newPTag(doc, level2ElementSS).appendChild(doc.createElement("specialsymbols"));
- - Element level2ElementTN = doc.createElement("level2"); - level1Element.appendChild(level2ElementTN); - - Element tnHeader = doc.createElement("p"); - tnHeader.setTextContent("Transcriber Notes"); - level2ElementTN.appendChild(tnHeader);- newPTag(doc, level2ElementTN).appendChild(doc.createElement("transcribernotes"));
-- newPTag(doc, level2ElementTN).appendChild(doc.createElement("template"));
- - TransformerFactory tFactory = TransformerFactory.newInstance(); - Transformer transformer = tFactory.newTransformer(); - DOMSource source = new DOMSource(doc); - StreamResult result = new StreamResult(new File(filename)); - transformer.setOutputProperty(OutputKeys.INDENT, "yes");- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount";, "2"); - transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId()); - transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
- transformer.transform(source, result); - - } catch(ParserConfigurationException e){ - e.printStackTrace(); - return false; - } catch(TransformerException e){ - e.printStackTrace(); - return false; + public void testXmlMap(){ + for(int i = 0; i < xmlElements.length; i++){ + xmlmap.put(xmlElements[i], "Testing" + i); } - return true; + xmlmap.put("specialsymbols", "a|Testing"); + xmlmap.put("transcribernotes", "Testing"); + xmlmap.put("template", defaultTemplate); } - public boolean generateTPage(String template, String filename){ - for (String xmlElement : xmlElements){- template = template.replaceAll("\\Q(" + xmlElement + ")\\E", xmlmap.get(xmlElement));
+ /* Auto-Fill button is pressed */ + public void autoPopulate(Document document){ + String nameSpace = document.getRootElement().getNamespaceURI(); + XPathContext context = new XPathContext("dtb", nameSpace); + Nodes metaNodes = document.query("//dtb:meta[@name]", context); + for(int i = 0; i < metaNodes.size(); i++){ + Element metaElement = (Element)metaNodes.get(i);+ if(metaElement.getAttribute("name").getValue().equalsIgnoreCase("dc:title")){
+ titleGuess = metaElement.getAttributeValue("content"); + }+ if(metaElement.getAttribute("name").getValue().equalsIgnoreCase("dc:creator")){
+ authorGuess += ";" + metaElement.getAttributeValue("content"); + }+ if(metaElement.getAttribute("name").getValue().equalsIgnoreCase("dc:publisher")){
+ publisherGuess = metaElement.getAttributeValue("content"); + } } - try{- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document doc = docBuilder.newDocument();- DocumentType docType = doc.getImplementation().createDocumentType("doctype", "-//NISO//DTD dtbook 2005-3//EN", "http://www.daisy.org/z3986/2005/dtbook-2005-3.dtd";);
- - Element rootElement = doc.createElement("dtbook"); - rootElement.setAttribute("type", "tpage"); - doc.appendChild(rootElement); - - Element bookElement = doc.createElement("book"); - rootElement.appendChild(bookElement); - - Element level1Element = doc.createElement("level1"); - bookElement.appendChild(level1Element); - - String[] splitTemplate = template.split("\\r?\\n"); - for(String line : splitTemplate){ - Element newElement = doc.createElement("p"); - newElement.setTextContent(line); - level1Element.appendChild(newElement); + if(titleGuess==null){ + Nodes docTitleNode = document.query("//dtb:doctitle", context); + if(docTitleNode.size()>0){ + titleGuess = docTitleNode.get(0).getValue(); } - - TransformerFactory tFactory = TransformerFactory.newInstance(); - Transformer transformer = tFactory.newTransformer(); - DOMSource source = new DOMSource(doc); - StreamResult result = new StreamResult(new File(filename)); - transformer.setOutputProperty(OutputKeys.INDENT, "yes");- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount";, "2"); - transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId()); - transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
- transformer.transform(source, result); - - } catch(ParserConfigurationException e){ - e.printStackTrace(); - return false; - } catch(TransformerException e){ - e.printStackTrace(); - return false; } - return true; - } - - private Element newPTag(Document doc, Element parent){ - Element ptag = doc.createElement("p"); - parent.appendChild(ptag); - return ptag; - } -- public boolean saveNewTPage(String filename, HashMap<String, String> newXmlMap){
- File file = new File(filename); - if(!checkForFile(filename)) - createNewTPageXML(filename); - try{- DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document doc = docBuilder.parse(file); - - for(int i = 0; i < xmlElements.length; i++){ - if(newXmlMap.get(xmlElements[i])==null) - newXmlMap.put(xmlElements[i], ""); //Initialize any empty fields + if(authorGuess.length()==0){ + Nodes docAuthorNode = document.query("//dtb:docauthor", context); + if(docAuthorNode.size()>0){ + authorGuess = docAuthorNode.get(0).getValue(); } -- doc.getElementsByTagName("booktitle").item(0).setTextContent(newXmlMap.get("booktitle")); - doc.getElementsByTagName("gradelevel").item(0).setTextContent(newXmlMap.get("gradelevel")); - doc.getElementsByTagName("subtitle").item(0).setTextContent(newXmlMap.get("subtitle")); - doc.getElementsByTagName("seriesname").item(0).setTextContent(newXmlMap.get("seriesname")); - doc.getElementsByTagName("editionname").item(0).setTextContent(newXmlMap.get("editionname"));
- doc.getElementsByTagName("authors").item(0).setTextContent(""); - String[] authors = newXmlMap.get("authors").split(";"); - for (String tempAuthor : authors){ - Element newAuthor = doc.createElement("author"); - newAuthor.setTextContent(tempAuthor);- newPTag(doc, (Element)doc.getElementsByTagName("authors").item(0)).appendChild(newAuthor);
+ } + String subtitle = ""; + if(!titleGuess.equals("")){ + if(titleGuess.contains(":")){ //There is probably a subtitle + subtitle = titleGuess.substring(titleGuess.indexOf(":") + 2);+ while(subtitle.charAt(0)==' '){ // Remove spaces from beginning of subtitle
+ subtitle = subtitle.substring(1); + } + titleGuess = titleGuess.substring(0, titleGuess.indexOf(":")); }- doc.getElementsByTagName("translator").item(0).setTextContent(newXmlMap.get("translator")); - doc.getElementsByTagName("publisherpermission").item(0).setTextContent(newXmlMap.get("publisherpermission")); - doc.getElementsByTagName("publisher").item(0).setTextContent(newXmlMap.get("publisher")); - doc.getElementsByTagName("publisherlocation").item(0).setTextContent(newXmlMap.get("publisherlocation")); - doc.getElementsByTagName("publisherwebsite").item(0).setTextContent(newXmlMap.get("publisherwebsite")); - doc.getElementsByTagName("copyrighttext").item(0).setTextContent(newXmlMap.get("copyrighttext")); - doc.getElementsByTagName("reproductionnotice").item(0).setTextContent(newXmlMap.get("reproductionnotice")); - doc.getElementsByTagName("isbn13").item(0).setTextContent(newXmlMap.get("isbn13")); - doc.getElementsByTagName("isbn10").item(0).setTextContent(newXmlMap.get("isbn10")); - doc.getElementsByTagName("printhistory").item(0).setTextContent(newXmlMap.get("printhistory")); - doc.getElementsByTagName("transcriptionyear").item(0).setTextContent(newXmlMap.get("transcriptionyear")); - doc.getElementsByTagName("transcriber").item(0).setTextContent(newXmlMap.get("transcriber")); - doc.getElementsByTagName("tgs").item(0).setTextContent(newXmlMap.get("tgs")); - doc.getElementsByTagName("affiliation").item(0).setTextContent(newXmlMap.get("affiliation")); - doc.getElementsByTagName("totalvolumes").item(0).setTextContent(newXmlMap.get("totalvolumes")); - doc.getElementsByTagName("volumenumber").item(0).setTextContent(newXmlMap.get("volumenumber")); - doc.getElementsByTagName("customizedbraille").item(0).setTextContent(newXmlMap.get("customizedbraille")); - doc.getElementsByTagName("braillepageinfo").item(0).setTextContent(newXmlMap.get("braillepageinfo")); - doc.getElementsByTagName("printpageinfo").item(0).setTextContent(newXmlMap.get("printpageinfo")); - doc.getElementsByTagName("transcribernotes").item(0).setTextContent(newXmlMap.get("transcribernotes")); - doc.getElementsByTagName("template").item(0).setTextContent(newXmlMap.get("template")); - doc.getElementsByTagName("specialsymbols").item(0).setTextContent(newXmlMap.get("specialsymbols"));
-- TransformerFactory transformerFactory = TransformerFactory.newInstance();
- Transformer transformer = transformerFactory.newTransformer(); - DOMSource source = new DOMSource(doc); - StreamResult result = new StreamResult(new File(filename)); - transformer.transform(source, result); - - } catch(ParserConfigurationException e){ - e.printStackTrace(); - return false; - } catch(IOException e){ - e.printStackTrace(); - return false; - }catch (SAXException e){ - e.printStackTrace(); - return false; - }catch(TransformerException e){ - e.printStackTrace(); - return false; + while(titleGuess.charAt(0)==' '){ + titleGuess = titleGuess.substring(1); + } + } + if(!authorGuess.equals("")){ + if(authorGuess.contains("by")){ + authorGuess = authorGuess.substring(authorGuess.indexOf("by") + 2); + } + authorGuess = authorGuess.replaceAll(", ", ";"); + authorGuess = authorGuess.replaceAll("and ", ""); + while(authorGuess.charAt(0)==' ' || authorGuess.charAt(0)==';'){ + authorGuess = authorGuess.substring(1); + } } - - return true; - } - - /*- * Attempts to find data in the book to automatically populate the text fields
- */ - public void autoPopulate(String bookPath){ - File book = new File(bookPath); - try{ - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - - Document doc = docBuilder.parse(book); - - Node fmNode = doc.getElementsByTagName("frontmatter").item(0); - if(fmNode == null){- xmlmap.put("reproductionnotice", "Further reproduction or distribution in other than a specialized format is prohibited.");
- xmlmap.put("template", defaultTemplate); - return; + //Parse front matter - Currently broken+ Pattern isbn13pattern = Pattern.compile("(?<!\\S)[\\d]+-[\\d]+-[\\d]+-[\\d]+-[\\d]\\b"); + Pattern isbn10pattern = Pattern.compile("(?<!\\S)[\\d]+-[\\d]+-[\\d]+-[\\d]\\b"); + Pattern copyrightpattern1 = Pattern.compile("(Copyright [\\d][\\d][\\d][\\d])"); + Pattern copyrightpattern2 = Pattern.compile("© [\\d][\\d][\\d][\\d]"); // Only way I can get it to work
+ Pattern websitepattern = Pattern.compile("www[.][\\w]*[.]com");+ Pattern printpattern = Pattern.compile("[\\d]+ [\\d]+ [\\d]+ [\\d]+ [\\d]+ [\\d]+");
+ + Nodes fmChildren = document.query("//dtb:frontmatter/*", context); + List<Element> allChildren = new ArrayList<Element>(); + for(int i = 0; i < fmChildren.size(); i++){ + allChildren.add((Element)fmChildren.get(i));+ List<Element> moreChildren = getAllChildren((Element)fmChildren.get(i), nameSpace);
+ for(int q = 0; q < moreChildren.size(); q++){ + allChildren.add(moreChildren.get(q)); + } + } + //List<Node> allChildren = getAllChildren(fmChildren, context); + for(int i = 0; i < allChildren.size(); i++){ + String nodeVal = removeBrlNode(allChildren.get(i)); + ///////Copyright + Matcher copyMatcher1 = copyrightpattern1.matcher(nodeVal); + Matcher copyMatcher2 = copyrightpattern2.matcher(nodeVal); + if(copyMatcher1.find()){ + copyright = nodeVal; + } else if (copyMatcher2.find()){ + copyright = nodeVal; } - //////Begin iterating through Head tags - Node headNode = doc.getElementsByTagName("head").item(0); - if(headNode != null) - parseHeadTags(headNode); - - if(publisherGuess != null) - xmlmap.put("publisher", publisherGuess); - - ///////Title - String title;- if(titleGuess==null) //Couldn't find anything defined in Head tags. Search for <doctitle>
- title = findTitle(doc); - else - title = titleGuess; - String subtitle = ""; - if(!title.equals("")){ - if(title.contains(":")){ //There is probably a subtitle - subtitle = title.substring(title.indexOf(":") + 2);- while(subtitle.charAt(0)==' '){ // Remove spaces from beginning of subtitle
- subtitle = subtitle.substring(1); - } - title = title.substring(0, title.indexOf(":")); - } - while(title.charAt(0)==' '){ - title = title.substring(1); - } + //////ISBN + Matcher isbn13Matcher = isbn13pattern.matcher(nodeVal); + if(isbn13Matcher.find()){ + isbn13 = isbn13Matcher.group(); } - //////////Authors - String authors;- if(authorGuess == null) //Couldn't find anything defined in Head tags. Search for <docauthor>
- authors = findAuthors(doc); - else - authors = authorGuess; - if(!authors.equals("")){ - if(authors.contains("by")){ - authors = authors.substring(authors.indexOf("by") + 2); - } - authors = authors.replace(", ", ";"); - authors = authors.replace("and ", ""); - while(authors.charAt(0)==' ' || authors.charAt(0)==';'){ - authors = authors.substring(1); - } - } - xmlmap.put("booktitle", title); - xmlmap.put("subtitle", subtitle); - xmlmap.put("authors", authors); - ///////Begin iterating through front matter - parseFrontMatter(fmNode); - - xmlmap.put("isbn13", isbn13); - xmlmap.put("isbn10", isbn10); - - if(websiteGuess != null){ - xmlmap.put("publisherwebsite", websiteGuess); - } - if(printHistoryGuess != null){ - xmlmap.put("printhistory", printHistoryGuess); + Matcher isbn10Matcher = isbn10pattern.matcher(nodeVal); + if(isbn10Matcher.find()){ + isbn10 = isbn10Matcher.group(); } - if(copyright!=null){ - xmlmap.put("copyrighttext", copyright); + //////Website + Matcher websiteMatcher = websitepattern.matcher(nodeVal); + if(websiteMatcher.find()){ + websiteGuess = websiteMatcher.group(); }- xmlmap.put("reproductionnotice", "Further reproduction or distribution in other than a specialized format is prohibited.");
- xmlmap.put("template", defaultTemplate); - - } catch(ParserConfigurationException e){ - e.printStackTrace(); - return; - } catch(IOException e){ - e.printStackTrace(); - return; - }catch (SAXException e){ - e.printStackTrace(); - return; + ////Print History + Matcher printMatcher = printpattern.matcher(nodeVal); + if(printMatcher.find()){ + printHistoryGuess = nodeVal; + } + } + + if(titleGuess!=null) + xmlmap.put("booktitle", titleGuess); + if(authorGuess!=null) + xmlmap.put("authors", authorGuess); + if(publisherGuess!=null) + xmlmap.put("publisher", publisherGuess); + if(copyright!=null) + xmlmap.put("copyright", copyright); + if(isbn13!=null) + xmlmap.put("isbn13", isbn13); + if(isbn10!=null) + xmlmap.put("isbn10", isbn10); + if(websiteGuess!=null) + xmlmap.put("publisherwebsite", websiteGuess); + if(printHistoryGuess!=null){ + xmlmap.put("printhistory", printHistoryGuess); } } - - private void parseHeadTags(Node head) { - List<Node> children = getAllChildren(head); - NamedNodeMap attrMap; + + /* Recursive method that assists autoPopulate */+ private List<Element> getAllChildren(Element parent, String namespace){ // Not working as expected - will revisit
+ List<Element> returnedNodes = new ArrayList<Element>(); + Elements children = parent.getChildElements(); for(int i = 0; i < children.size(); i++){ - if(children.get(i).getNodeName().equals("meta")){ - attrMap = children.get(i).getAttributes(); - if(attrMap.getNamedItem("name")!=null){ - if(attrMap.getNamedItem("name").getNodeValue().equals("dc:Title")){ - titleGuess = attrMap.getNamedItem("content").getNodeValue(); + Element element = children.get(i); + returnedNodes.add(element); + if(element.getChildCount()>0){ + if(element.getChildElements("brl", namespace).size()>0){ + element = (Element)element.copy(); + Elements brlChildren = element.getChildElements("brl", namespace); + for(int q = 0; q < brlChildren.size(); q++){ + element.removeChild(brlChildren.get(q)); } - if(attrMap.getNamedItem("name").getNodeValue().equals("dc:Creator")){ - authorGuess += ";" + attrMap.getNamedItem("content").getNodeValue(); - }- if(attrMap.getNamedItem("name").getNodeValue().equals("dc:Publisher")){
- publisherGuess = attrMap.getNamedItem("content").getNodeValue(); + } + List<Element> moreChildren = getAllChildren(element, namespace); + for(int q = 0; q < moreChildren.size(); q++){ + if(!moreChildren.get(q).getLocalName().equalsIgnoreCase("brl")){ + returnedNodes.add(moreChildren.get(q)); } } } } + return returnedNodes; } -- private List<Node> getAllChildren(Node parent){ // Could likely be made more efficient
- List<Node> returnedNodes = new ArrayList<Node>(); - NodeList nodes = parent.getChildNodes(); - for(int i = 0; i < nodes.getLength(); i++){ - Node tempNode = nodes.item(i); - returnedNodes.add(tempNode); - if(tempNode.hasChildNodes()){ - List<Node> childNodes = new ArrayList<Node>(getAllChildren(tempNode)); - for(int q = 0; q < childNodes.size(); q++){ - returnedNodes.add(childNodes.get(q)); + + public HashMap<String, String> getXmlMap(){ + return xmlmap; + } + + /* Initialize xmlmap to get rid of those pesky nullpointerexceptions */ + public HashMap<String, String> getEmptyXmlMap(){ + HashMap<String, String> newMap = new HashMap<String,String>(); + for (int i = 0; i < xmlElements.length; i++){ + newMap.put(xmlElements[i], ""); + }+ newMap.put("reproductionnotice", "Further reproduction or distribution in other than a specialized format is prohibited.");
+ newMap.put("template", defaultTemplate); + newMap.put("specialsymbols", ""); + return newMap; + } + + public String[] getXmlElements(){ + return xmlElements; + } + + + /* User has previously made a tpage with the tpage dialog */ + public Element getTPageElement(Document docRoot){ + String nameSpace = docRoot.getRootElement().getNamespaceURI(); + XPathContext context = new XPathContext("dtb", nameSpace); + Nodes nodes = docRoot.query("//dtb:prodnote", context); + if(nodes.size() > 0){ + Element pnElement = (Element)nodes.get(0); + if(pnElement.getAttributeCount()>0){+ if(pnElement.getAttribute("id").getValue().equalsIgnoreCase("brl-tp-TitlePage")){
+ return pnElement; } } } - return returnedNodes; + return null; } - private String findTitle(Document doc){ - String title = ""; - Node doctitle = doc.getElementsByTagName("doctitle").item(0); - if(doctitle!=null){ - List<Node> nodeChildren = getAllChildren(doctitle); - for (int q = 0; q < nodeChildren.size(); q++){ - if(nodeChildren.get(q).getNodeName().equals("#text")) - title += " " + nodeChildren.get(q).getNodeValue();+ /* If user has previously created a tpage, fills the xmlmap with those values */
+ public HashMap<String, String> pullFromElement(Element rootElement){ + HashMap<String, String> returnMap = getEmptyXmlMap(); + String nameSpace = rootElement.getNamespaceURI(); + XPathContext context = new XPathContext("dtb", nameSpace); + Nodes divs = rootElement.query("//dtb:div", context); + for(int i = 0; i < divs.size(); i++){ + Element element = (Element)divs.get(i); + Attribute attr = element.getAttribute("class"); + if(attr!=null){ + if(attr.getValue().contains("brl-tp-")){+ Element finalElement = (Element)element.copy(); //Don't edit the xml file in memory + for(int q = finalElement.getChildCount()-1; q > 0; q--){ //Remove those brl nodes
+ finalElement.removeChild(q); + } + returnMap.put(attr.getValue().substring(7), finalElement.getValue()); + } } } - return title;+ Nodes ssPN = rootElement.query("//dtb:prodnote[@id='brl-tp-SpecialSymbolsPage']", context);
+ if(ssPN.size()>0){ + String xmlToString = ""; + Element ssElement = (Element)ssPN.get(0); + Nodes ssPtags = ssElement.query("dtb:p", context); + for(int i = 1; i < ssPtags.size(); i++){ + String nodeVal = removeBrlNode((Element)ssPtags.get(i)); + xmlToString += "||" + nodeVal.replace(": ", "|"); + } + returnMap.put("specialsymbols", xmlToString); + } else + returnMap.put("specialsymbols", ""); ++ Nodes tnPN = rootElement.query("//dtb:prodnote[@id='brl-tp-TranscriberNotesPage']", context);
+ if(tnPN.size() > 0){ + String xmlToString = ""; + Element tnElement = (Element)tnPN.get(0); + Nodes tnPtags = tnElement.query("dtb:p", context); + for(int i = 1; i < tnPtags.size(); i++){ + String nodeVal = removeBrlNode((Element)tnPtags.get(i)); + if(i==tnPtags.size()-1) + xmlToString += nodeVal; + else + xmlToString += nodeVal + "\r\n"; + } + returnMap.put("transcribernotes", xmlToString); + } else + returnMap.put("transcribernotes", ""); + return returnMap; } - private String findAuthors(Document doc){ - String authors = ""; - NodeList docAuthors = doc.getElementsByTagName("docauthor"); - if(docAuthors.getLength()>0){ - for(int i = 0; i < docAuthors.getLength(); i++){ - List<Node> daChildren = getAllChildren(docAuthors.item(i)); - for(int q = 0; q < daChildren.size(); q++){ - if(daChildren.get(q).getNodeName().equals("#text")) - authors += ";" + daChildren.get(q).getNodeValue(); - }+ /* Used by various methods to strip Brl nodes out of an element. Is not 100% accurate but not a priority to fix */
+ private String removeBrlNode(Element element){ + String nameSpace = element.getNamespaceURI(); + XPathContext context = new XPathContext("dtb", nameSpace); + + Element returnElement = (Element) element.copy(); + + if(returnElement.getChildCount() > 0){ + Nodes brlNodes = returnElement.query("dtb:brl", context); + System.out.println("Found " + brlNodes.size() + " brl nodes"); + for(int i = 0; i < brlNodes.size(); i++){ + Element curNode = (Element)brlNodes.get(i); + returnElement.removeChild(curNode); } } - return authors; + return returnElement.getValue(); } - private void parseFrontMatter(Node parent){ - NodeList nodes = parent.getChildNodes();- Pattern isbn13pattern = Pattern.compile("(?<!\\S)[\\d]+-[\\d]+-[\\d]+-[\\d]+-[\\d]\\b"); - Pattern isbn10pattern = Pattern.compile("(?<!\\S)[\\d]+-[\\d]+-[\\d]+-[\\d]\\b"); - Pattern copyrightpattern1 = Pattern.compile("(Copyright [\\d][\\d][\\d][\\d])"); - Pattern copyrightpattern2 = Pattern.compile("© [\\d][\\d][\\d][\\d]"); // Only way I can get it to work
- Pattern websitepattern = Pattern.compile("www[.][\\w]*[.]com");- Pattern printpattern = Pattern.compile("[\\d]+ [\\d]+ [\\d]+ [\\d]+ [\\d]+ [\\d]+");
- for(int i = 0; i < nodes.getLength(); i++){ - Node tempNode = nodes.item(i); - if(tempNode.getNodeName().equals("#text")){ - String nodeVal = tempNode.getNodeValue(); - //////Copyright - Matcher copyMatcher1 = copyrightpattern1.matcher(nodeVal); - Matcher copyMatcher2 = copyrightpattern2.matcher(nodeVal); - if(copyMatcher1.find()){ - copyright = nodeVal; - } else if (copyMatcher2.find()){ - copyright = nodeVal; - } - - //////ISBN - Matcher isbn13Matcher = isbn13pattern.matcher(nodeVal); - if(isbn13Matcher.find()){ - isbn13 = isbn13Matcher.group(); - } - - Matcher isbn10Matcher = isbn10pattern.matcher(nodeVal); - if(isbn10Matcher.find()){ - isbn10 = isbn10Matcher.group(); - } - - //////Website - Matcher websiteMatcher = websitepattern.matcher(nodeVal); - if(websiteMatcher.find()){ - websiteGuess = websiteMatcher.group(); - } - - ////Print History - Matcher printMatcher = printpattern.matcher(nodeVal); - if(printMatcher.find()){ - printHistoryGuess = nodeVal;+ /* If user has previously created a tpage, fills the Template text field with the tpage's current layout */
+ public String elementToTemplate(Element rootElement){ + String nameSpace = rootElement.getNamespaceURI(); + XPathContext context = new XPathContext("dtb", nameSpace); + Element newRoot = (Element)rootElement.copy(); + Nodes ptags = newRoot.query("//dtb:p", context); + + for(int i = 0; i < ptags.size(); i++){ + Element curElement = (Element)ptags.get(i); + removeAllAttributes(curElement); + if(curElement.getChildCount() > 0){ + Nodes divs = curElement.query("dtb:div|dtb:brl", context); + for(int q = 0; q < divs.size(); q++){ + Element curDiv = (Element)divs.get(q); + Attribute attr = curDiv.getAttribute("class"); + if(attr!=null){ + Element newElement = new Element(attr.getValue().substring(7)); + removeAllAttributes(newElement); + curElement.replaceChild(curDiv, newElement); + } else{ + curElement.removeChild(curDiv); + } } } - - ////// - if(tempNode.hasChildNodes()){ - parseFrontMatter(tempNode); - } } + String returnString = newRoot.toXML(); + returnString = returnString.replaceAll("<prodnote[^>]+>", "");+ returnString = returnString.replaceAll(" xmlns=\"[0-9a-zA-Z:/\\-\\.]*\" ", "");
+ returnString = returnString.replaceAll("/>", ">"); + returnString = returnString.replace("</prodnote>", ""); + returnString = returnString.replaceAll("</p>", "\r\n"); + returnString = returnString.replaceAll("<p>", ""); + return returnString; } - public HashMap<String, String> getXmlMap(){ - return xmlmap; + /* Strips all attributes out of a node for elementToTemplate */ + private void removeAllAttributes(Element element){ + for(int i = 0; i < element.getAttributeCount(); i++){ + element.removeAttribute(element.getAttribute(i)); + } } - public HashMap<String, String> getEmptyXmlMap(){ - HashMap<String, String> newMap = new HashMap<String,String>(); - for (int i = 0; i < xmlElements.length; i++){ - newMap.put(xmlElements[i], "");+ /* When inserting the tpage, creates the parent node that will passed to the BrailleDocument */
+ public Element getTPageParent(String template){ + Element rootTPage = new Element("level1"); + + /*Title Page*/ + Element titlePage = new Element("prodnote"); + Attribute titleAttr = new Attribute("id", "brl-tp-TitlePage"); + titlePage.addAttribute(titleAttr); + String[] tempLines = template.split("\r|\n"); + for(String line : tempLines){ + if(!line.equals("")){ + Element finalLine = extractXmlTags(line); + titlePage.appendChild(finalLine); + } }- newMap.put("reproductionnotice", "Further reproduction or distribution in other than a specialized format is prohibited.");
- newMap.put("template", defaultTemplate); - return newMap; + /* ********* */ + + /*Special Symbols*/ + Element ssPage = new Element("prodnote"); + Attribute ssAttr = new Attribute("id", "brl-tp-SpecialSymbolsPage"); + ssPage.addAttribute(ssAttr); + Element ssHeader = new Element("p"); + ssHeader.appendChild("Special Symbols"); + ssPage.appendChild(ssHeader); + + String ssText = xmlmap.get("specialsymbols"); + if(ssText!=null){ + String[] ssSplit = ssText.split("\\|\\|"); + for(String string : ssSplit){ + String[] parts = string.split("\\|"); + if(parts[0]!=null){ + Element ptag = new Element("p"); + if(parts[1]!=null) + ptag.appendChild(parts[0] + ": " + parts[1]); + else + ptag.appendChild(parts[0]); + ssPage.appendChild(ptag); + } + } + } + /* ********* */ + + /*Transcriber Notes*/ + Element tnPage = new Element("prodnote"); + Attribute tnAttr = new Attribute("id", "brl-tp-TranscriberNotesPage"); + tnPage.addAttribute(tnAttr); + Element tnHeader = new Element("p"); + tnHeader.appendChild("Transcriber Notes"); + tnPage.appendChild(tnHeader); + + String tnText = xmlmap.get("transcribernotes"); + String[] tnLines = tnText.split("\r|\n"); + for(String line : tnLines){ + Element ptag = new Element("p"); + ptag.appendChild(line); + tnPage.appendChild(ptag); + } + /* ******** */ + + rootTPage.appendChild(titlePage); + rootTPage.appendChild(ssPage); + rootTPage.appendChild(tnPage); + + return rootTPage; } - public String[] getXmlElements(){ - return xmlElements;+ /* Takes the template defined in the tpage dialog and converts it into xml elements */
+ private Element extractXmlTags(String tempLine){ + String line = tempLine.replaceAll("<p>", ""); + line = line.replaceAll("</p>", ""); + Element ptag = new Element("p"); + String temp = ""; + for(int i = 0; i < line.length(); i++){ + if(line.charAt(i)=='<'){ + ptag.appendChild(temp); + temp = ""; + String findElement = ""; + for(int q = i+1; q < line.length(); q++){ + if(line.charAt(q)=='>'){ + i = q; + Element newElement = new Element("div"); + Attribute newAttr = new Attribute("class", "brl-tp-" + findElement); + newElement.addAttribute(newAttr); + newElement.appendChild(xmlmap.get(findElement)); + ptag.appendChild(newElement); + break; + } else { + findElement += line.charAt(q); + } + } + } else{ + temp += line.charAt(i); + } + } + ptag.appendChild(temp); + return ptag; } }