PageRenderTime 28ms CodeModel.GetById 12ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 1ms

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