KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > ext > xml > dbobj > XMLImportDocument


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.ext.xml.dbobj;
66
67 import com.jcorporate.expresso.core.dataobjects.DataObject;
68 import com.jcorporate.expresso.core.dataobjects.Defineable;
69 import com.jcorporate.expresso.core.db.DBException;
70 import com.jcorporate.expresso.core.dbobj.DBObject;
71 import com.jcorporate.expresso.core.misc.URLUTF8Encoder;
72 import com.jcorporate.expresso.kernel.util.FastStringBuffer;
73 import org.apache.log4j.Logger;
74 import org.xml.sax.Attributes JavaDoc;
75 import org.xml.sax.SAXException JavaDoc;
76 import org.xml.sax.helpers.DefaultHandler JavaDoc;
77
78 import java.util.Iterator JavaDoc;
79 import java.util.Vector JavaDoc;
80
81
82 /**
83  * Insert the type's description here.
84  * Creation date: (4/6/00 8:12:40 PM)
85  *
86  * @author Michael Nash
87  */

88 public class XMLImportDocument
89         extends DefaultHandler JavaDoc {
90     private DataObject myDBObject = null;
91     private String JavaDoc currentItem = ("None");
92     private FastStringBuffer theData = new FastStringBuffer();
93     private static final String JavaDoc thisClass = XMLImportDocument.class.getName() + ".";
94     private String JavaDoc currentFieldName = ("None");
95     private Vector JavaDoc errorList = new Vector JavaDoc(3);
96     int recordCount = 0;
97     private String JavaDoc dbName = "default";
98     private static Logger log = Logger.getLogger(XMLImportDocument.class);
99
100     /**
101      * XMLImportDocument constructor.
102      */

103     public XMLImportDocument() {
104         super();
105     } /* XMLImportDocument() */
106
107     /**
108      * XMLImportDocument constructor.
109      *
110      * @param newDBObject The DataObject being set.
111      */

112     public XMLImportDocument(DataObject newDBObject) {
113         super();
114         myDBObject = newDBObject;
115     } /* XMLImportDocument(DataObject) */
116
117     public void setDBName(String JavaDoc newName) {
118         dbName = newName;
119     }
120
121     public String JavaDoc getDBName() {
122         return dbName;
123     }
124
125     /**
126      * DefaultHandler implementation for SAX parsing.
127      *
128      * @param ch
129      * @param start
130      * @param length
131      */

132     public void characters(char[] ch, int start, int length)
133             throws SAXException JavaDoc {
134         for (int i = start; i < start + length; i++) {
135             theData.append(ch[i]);
136         }
137
138         if (log.isDebugEnabled()) {
139             log.debug("Data for " + currentItem + ":" +
140                     theData.toString());
141         }
142     } /* characters(char[], int, int) */
143
144
145     /**
146      * DefaultHandler implementation for SAX parsing.
147      * Creation date: (4/6/00 8:27:22 PM)
148      */

149     public void endDocument()
150             throws SAXException JavaDoc {
151         log.debug("End document");
152
153         if (myDBObject != null) {
154             saveDBObject();
155         } else {
156             throw new SAXException JavaDoc("Database object is null - Unable to save object");
157         }
158     } /* endDocument() */
159
160
161     /**
162      * DefaultHandler implementation for SAX parsing.
163      *
164      * @param uri
165      * @param localpart
166      * @param rawname
167      */

168     public void endElement(String JavaDoc uri, String JavaDoc localpart, String JavaDoc rawname)
169             throws SAXException JavaDoc {
170         String JavaDoc myName = (thisClass + "endElement(String, String, String)");
171         log.debug("End:" + rawname);
172
173         if (rawname.equals("ObjectName")) {
174             log.debug("Record count was " + recordCount);
175
176             /* New object */
177             recordCount = 0;
178
179             try {
180                 Class JavaDoc c = Class.forName(theData.toString());
181                 myDBObject = (DataObject) c.newInstance();
182                 myDBObject.setDataContext(getDBName());
183             } catch (ClassNotFoundException JavaDoc cn) {
184                 throw new SAXException JavaDoc(myName + ":Database object not found:" +
185                         cn.getMessage());
186             } catch (InstantiationException JavaDoc ie) {
187                 throw new SAXException JavaDoc(myName +
188                         ":Database object cannot be instantiated:" +
189                         ie.getMessage());
190             } catch (IllegalAccessException JavaDoc iae) {
191                 throw new SAXException JavaDoc(myName +
192                         ":Illegal access loading Database object:" +
193                         iae.getMessage());
194             } catch (Exception JavaDoc eeother) {
195                 throw new SAXException JavaDoc(eeother.getMessage());
196             }
197         } else if (rawname.equals("FieldName")) {
198             currentFieldName = theData.toString();
199         } else if (rawname.equals("FieldValue")) {
200             if (myDBObject != null) {
201                 try {
202                     if (myDBObject.getFieldMetaData(currentFieldName) == null) {
203                         throw new SAXException JavaDoc(myName + ":Error setting field " +
204                                 currentFieldName + ":" +
205                                 "Field does not exist");
206                     } else if (myDBObject.getFieldMetaData(currentFieldName).isVirtual()) {
207                         log.debug("Skipping virtual field " + currentFieldName);
208                     } else {
209                         myDBObject.set(currentFieldName,
210                                 URLUTF8Encoder.decode(theData.toString()));
211                     }
212                 } catch (DBException de) {
213                     throw new SAXException JavaDoc(myName + ":Error setting field " +
214                             currentFieldName + ":" +
215                             de.getMessage());
216                 }
217             }
218         }
219
220         if (rawname.equals("DataRecord")) {
221             log.debug("--> Saving datarecord");
222
223             if (myDBObject != null) {
224                 saveDBObject();
225             } else {
226                 throw new SAXException JavaDoc("DataObject was null - Error saving object");
227             }
228         }
229
230         theData.clear();
231     } /* endElement(String) */
232
233
234     /**
235      * The set of exceptions that have occurred during processing.
236      * Creation date: (4/6/00 8:27:22 PM)
237      *
238      * @return
239      */

240     public Vector JavaDoc getErrorList() {
241         return errorList;
242     } /* getErrorList() */
243
244     /**
245      * Insert the method's description here.
246      * Creation date: (4/6/00 8:27:22 PM)
247      */

248     public void saveDBObject() {
249         try {
250             log.debug("Saving database object");
251
252             if (myDBObject == null) {
253                 throw new DBException("DataObject is null, cannot save");
254             }
255
256             /* If an object with this key exists, delete the old one first */
257             DataObject checkObject = null;
258
259             if (myDBObject instanceof DBObject) {
260                 checkObject = ((DBObject) myDBObject).newInstance();
261             } else {
262                 try {
263                     checkObject = (DataObject) myDBObject.getClass().newInstance();
264                     if (checkObject instanceof Defineable) {
265                         ((Defineable) checkObject).setDefinitionName(((Defineable) myDBObject).getDefinitionName());
266                     }
267                     java.util.Map JavaDoc attrMap = myDBObject.getAllAttributes();
268                     java.util.Iterator JavaDoc keys = attrMap.keySet().iterator();
269                     while (keys.hasNext()) {
270                         String JavaDoc key = keys.next().toString();
271                         checkObject.setAttribute(key, attrMap.get(key));
272                     }
273                 } catch (Exception JavaDoc e) {
274                     throw new DBException("Error creating checkObject: " + e.getMessage(), e);
275                 }
276             }
277             checkObject.setDataContext(getDBName());
278
279             String JavaDoc oneKey = null;
280
281             for (Iterator JavaDoc e = myDBObject.getMetaData().getAllKeysMap().keySet().iterator();/*myDBObject.getKeyFieldListIterator();*/
282                  e.hasNext();) {
283                 oneKey = (String JavaDoc) e.next();
284                 checkObject.set(oneKey, myDBObject.getField(oneKey));
285             }
286             if (checkObject.find()) {
287                 log.debug("Record is there, updating");
288
289                 /* Don't throw an exception if the record doesn't need updating */
290                 myDBObject.getMetaData().setCheckZeroUpdate(false);
291                 myDBObject.setDataContext(getDBName());
292                 myDBObject.update();
293             } else {
294                 log.debug("Record is not there, adding");
295                 myDBObject.setDataContext(getDBName());
296                 myDBObject.add();
297                 log.debug("Added");
298             }
299
300             recordCount++;
301         } catch (DBException de) {
302             de.printStackTrace();
303             errorList.addElement(de);
304             log.error(de);
305         }
306     } /* saveDBObject() */
307
308     /**
309      * @param name
310      * @param attributes
311      */

312     /* public void startElement(String name, AttributeList attributes)
313
314 throws SAXException {
315
316
317
318 System.out.println("Start:" + name);
319
320 //for (int i = 0; i < attributes.getLength(); i++) {
321
322 // System.out.println("Attribute " + i + " Name: " + attributes.getName(i)
323
324 // + " Value:" + attributes.getValue(i));
325
326 //}
327
328 currentItem = name;
329
330 //getType(int);
331
332 //getValue(int);
333
334 //getValue(String);
335
336 } /* startElement(String, AttributeList) */

337     ///Idit
338
public void startElement(String JavaDoc uri, String JavaDoc localpart, String JavaDoc rawname,
339                              Attributes JavaDoc attributes)
340             throws SAXException JavaDoc {
341         log.debug("Start:" + rawname);
342         currentItem = rawname;
343     }
344     // Idit Mike
345
/**
346      * @return
347      */

348     public DataObject getDBObject()
349             throws DBException {
350         return myDBObject;
351     } /* getDBObject() */
352
353
354 } /* XMLImportDocument */
355
Popular Tags