/src/mpv5/utils/xml/XMLWriter.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/ · Java · 376 lines · 199 code · 70 blank · 107 comment · 29 complexity · 48369df1450ca722cdb2bc69d5520697 MD5 · raw file

  1. /*
  2. * This file is part of YaBS.
  3. *
  4. * YaBS is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * YaBS is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with YaBS. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. package mpv5.utils.xml;
  18. //~--- non-JDK imports --------------------------------------------------------
  19. import mpv5.data.PropertyStore;
  20. import mpv5.db.common.Context;
  21. import mpv5.db.common.DatabaseObject;
  22. import mpv5.db.common.NodataFoundException;
  23. import mpv5.globals.Constants;
  24. import mpv5.globals.Messages;
  25. import mpv5.logging.Log;
  26. import mpv5.usermanagement.MPSecurityManager;
  27. import mpv5.utils.files.FileDirectoryHandler;
  28. import org.jdom.DocType;
  29. import org.jdom.Document;
  30. import org.jdom.Element;
  31. import org.jdom.output.Format;
  32. import org.jdom.output.XMLOutputter;
  33. //~--- JDK imports ------------------------------------------------------------
  34. import java.io.File;
  35. import java.io.FileWriter;
  36. import java.util.ArrayList;
  37. import java.util.Iterator;
  38. import java.util.List;
  39. /**
  40. *
  41. *
  42. */
  43. public class XMLWriter {
  44. public static final String rootElementName = Constants.XML_ROOT;
  45. public static DocType DEFAULT_DOCTYPE = new DocType(rootElementName, Constants.XML_DOCTYPE_ID,
  46. Constants.XML_DOCTYPE_URL);
  47. private Element rootElement = new Element(rootElementName);
  48. private Document myDocument = new Document();
  49. private Element defaultSubRoot;
  50. /**
  51. * Exports all data in the given context to XML and shows a file save dialog for the created file.
  52. * @param c
  53. */
  54. public static void export(Context c) {
  55. if (mpv5.usermanagement.MPSecurityManager.check(c, MPSecurityManager.EXPORT)) {
  56. try {
  57. XMLWriter xmlw = new XMLWriter();
  58. xmlw.newDoc(true);
  59. String name = c.getDbIdentity();
  60. ArrayList<DatabaseObject> dbobjarr = DatabaseObject.getObjects(c);
  61. xmlw.add(dbobjarr);
  62. mpv5.YabsViewProxy.instance().showFilesaveDialogFor(xmlw.createFile(name));
  63. } catch (NodataFoundException ex) {
  64. Log.Debug(XMLWriter.class, ex);
  65. }
  66. }
  67. }
  68. /**
  69. * Adds all objects
  70. * @param dbobjarr
  71. */
  72. public void add(ArrayList<DatabaseObject> dbobjarr) {
  73. if ((dbobjarr != null) && (dbobjarr.size() > 0)) {
  74. DatabaseObject d = dbobjarr.get(0);
  75. String sident = d.getDbIdentity();
  76. Element parent = addNode(new Element(sident));
  77. Log.Debug(this, "Adding root node " + sident);
  78. for (int i = 0; i < dbobjarr.size(); i++) {
  79. try {
  80. DatabaseObject databaseObject = dbobjarr.get(i);
  81. Element ident = new Element(databaseObject.getType());
  82. List<String[]> data = databaseObject.getValues();
  83. this.addNode(parent, ident, databaseObject.__getIDS().toString());
  84. for (int h = 0; h < data.size(); h++) {
  85. if (!data.get(h)[0].equals("IDS")) {
  86. this.addElement(parent, ident, databaseObject.__getIDS().toString(),
  87. data.get(h)[0].toLowerCase(), data.get(h)[1]);
  88. }
  89. }
  90. } catch (Exception ex) {
  91. Log.Debug(this, ex.getMessage());
  92. }
  93. }
  94. }
  95. }
  96. /**
  97. * Adds a node to root with the given name
  98. * @param e
  99. * @return
  100. */
  101. public Element addNode(Element e) {
  102. rootElement.addContent(e);
  103. return e;
  104. }
  105. /**
  106. * Adds a node to parent with the given name
  107. * @param parent
  108. * @param name The node name
  109. * @return
  110. */
  111. public Element addNode(Element parent, String name) {
  112. Element elem = new Element(name);
  113. parent.addContent(elem);
  114. return elem;
  115. }
  116. /**
  117. * Adds a node to parent with the given name, and an additional attribute "ID" with the attribute value
  118. * @param parent
  119. * @param name
  120. * @param attribute
  121. * @return the generated element
  122. */
  123. public Element addNode(Element parent, Element name, String attribute) {
  124. Element elem = name;
  125. elem.setAttribute("id", attribute);
  126. @SuppressWarnings("unchecked")
  127. List<Element> list = (List<Element>) parent.getContent();
  128. for (int i = 0; i < list.size(); i++) {
  129. if (list.get(i) instanceof Element) {
  130. if (list.get(i).getName().equals(elem.getName()) && (list.get(i).getAttribute("id") != null)
  131. && list.get(i).getAttribute("id").getValue().equals(attribute)) {
  132. Log.Debug(this, "Node exists: " + elem.getName() + ": " + attribute);
  133. return null;
  134. }
  135. }
  136. }
  137. parent.addContent(elem);
  138. return elem;
  139. }
  140. // /**
  141. // * Adds a node with the given name to root
  142. // * @param name
  143. // * @return
  144. // */
  145. // public Element addNode(String name) {
  146. // Element e = new Element(name);
  147. // rootElement.addContent(e);
  148. // return e;
  149. // }
  150. /**
  151. * Appends the PropertyStore's data to an existing XML file,
  152. * or creates one if not existant
  153. *
  154. * @param file
  155. * @param nodename
  156. * @param nodeid
  157. * @param cookie
  158. */
  159. public void append(File file, String nodename, String nodeid, PropertyStore cookie) {
  160. XMLReader reader = new XMLReader();
  161. try {
  162. Log.Debug(this, "Reading in " + file);
  163. myDocument = reader.newDoc(file);
  164. rootElement = myDocument.getRootElement();
  165. } catch (Exception ex) {
  166. newDoc(true);
  167. }
  168. parse(nodename, nodeid, cookie);
  169. }
  170. public void createOrReplace(File file) throws Exception {
  171. FileWriter fw = null;
  172. if (file.exists()) {
  173. Log.Debug(this, "Updating " + file);
  174. fw = new FileWriter(file);
  175. } else {
  176. file.getParentFile().mkdirs();
  177. file.createNewFile();
  178. fw = new FileWriter(file);
  179. }
  180. Log.Debug(this, "Writing Document: " + file + " using encoding: " + fw.getEncoding());
  181. XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
  182. outputter.output(myDocument, fw);
  183. mpv5.YabsViewProxy.instance().addMessage(Messages.FILE_SAVED + file.getPath());
  184. Log.Debug(this, Messages.FILE_SAVED + file.getPath());
  185. }
  186. /**
  187. * Creates a new XML document with the root element
  188. * @param withDocTypeDeclaration
  189. */
  190. public void newDoc(boolean withDocTypeDeclaration) {
  191. if (withDocTypeDeclaration) {
  192. myDocument = new Document(rootElement, (DocType) DEFAULT_DOCTYPE.clone());
  193. Log.Debug(this, "Using doctype: " + DEFAULT_DOCTYPE);
  194. } else {
  195. myDocument = new Document(rootElement);
  196. }
  197. }
  198. /**
  199. * Creates a ned XML document with the sub root element and DocType
  200. * @param defaultSubRootElementName
  201. */
  202. public void newDoc(String defaultSubRootElementName) {
  203. newDoc(true);
  204. defaultSubRoot = new Element(defaultSubRootElementName);
  205. rootElement.addContent(defaultSubRoot);
  206. }
  207. public void newDoc(String defaultSubRootElementName, boolean withDocTypeDeclaration) {
  208. newDoc(withDocTypeDeclaration);
  209. defaultSubRoot = new Element(defaultSubRootElementName);
  210. rootElement.addContent(defaultSubRoot);
  211. }
  212. public void newDoc() {
  213. newDoc(true);
  214. }
  215. /**
  216. * Creates a new XML file with the given name
  217. *
  218. * @param filename
  219. * @return
  220. */
  221. public File createFile(String filename) {
  222. try {
  223. File f = FileDirectoryHandler.getTempFile(filename, "xml");
  224. FileWriter fw = new FileWriter(f);
  225. Format format = Format.getPrettyFormat();
  226. format.setEncoding(fw.getEncoding());
  227. XMLOutputter outputter = new XMLOutputter(format);
  228. Log.Debug(this, "Writing Document: " + f + " using encoding: " + fw.getEncoding());
  229. outputter.output(myDocument, new FileWriter(f));
  230. return f;
  231. } catch (java.io.IOException e) {
  232. Log.Debug(this,
  233. e);
  234. }
  235. return null;
  236. }
  237. /**
  238. * Adds an element or replaces it if already existing
  239. * @param parent
  240. * @param nodename
  241. * @param attributevalue The ID of the node where this element shall be added
  242. * @param name The name of the new element
  243. * @param value The value of the element
  244. * @return
  245. */
  246. public boolean addElement(Element parent, Element nodename, String attributevalue, String name, String value) {
  247. // add some child elements
  248. Element elem = new Element(name);
  249. elem.addContent(value);
  250. @SuppressWarnings("unchecked")
  251. List<Element> list = (List<Element>) parent.getContent();
  252. for (int i = 0; i < list.size(); i++) {
  253. if (list.get(i) instanceof Element) {
  254. if (list.get(i).getName().equals(nodename.getName()) && (list.get(i).getAttribute("id") != null)
  255. && list.get(i).getAttribute("id").getValue().equals(attributevalue)) {
  256. list.get(i).addContent(elem);
  257. return true; // only add once
  258. }
  259. }
  260. }
  261. return false; // no matching parent node found
  262. }
  263. /**
  264. * Parses a PropertyStore object. "nodeid" properties are ignored.
  265. * Make sure to call newDoc() first!
  266. * @param nodename
  267. * @param nodeid
  268. * @param cookie
  269. */
  270. public void parse(String nodename, String nodeid, PropertyStore cookie) {
  271. Element e = new Element(nodename);
  272. addNode(defaultSubRoot, e, nodeid);
  273. Iterator list = cookie.getList().iterator();
  274. while (list.hasNext()) {
  275. Object o = list.next();
  276. // Log.Debug(this,((String[]) o)[0]);
  277. addElement(defaultSubRoot, e, nodeid, ((String[]) o)[0], ((String[]) o)[1]);
  278. }
  279. }
  280. /**
  281. * Parses a PropertyStore list. "nodeid" property is mandatory!
  282. * Make sure to call newDoc() first.
  283. * @param nodename
  284. * @param cookie
  285. */
  286. public void parse(String nodename, List<PropertyStore> cookie) {
  287. for (int i = 0; i < cookie.size(); i++) {
  288. PropertyStore propertyStore = cookie.get(i);
  289. Element e = new Element(nodename);
  290. Element n = addNode(defaultSubRoot, e, propertyStore.getProperty("nodeid"));
  291. if (n != null) {
  292. Iterator list = propertyStore.getList().iterator();
  293. while (list.hasNext()) {
  294. Object o = list.next();
  295. if (!((String[]) o)[0].equals("nodeid")) {
  296. // addElement(defaultSubRoot, e, propertyStore.getProperty("nodeid"), ((String[]) o)[0], ((String[]) o)[1]);
  297. Element en = new Element(((String[]) o)[0]);
  298. en.addContent(((String[]) o)[1]);
  299. n.addContent(en);
  300. }
  301. }
  302. }
  303. }
  304. }
  305. }
  306. //~ Formatted by Jindent --- http://www.jindent.com