KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > ext > xml > controller > XMLController


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 /**
66  * XMLController
67  *
68  * Copyright 2000, 2001 Jcorporate Ltd.
69  */

70 package com.jcorporate.expresso.ext.xml.controller;
71
72 import com.jcorporate.expresso.core.controller.ControllerException;
73 import com.jcorporate.expresso.core.controller.ControllerRequest;
74 import com.jcorporate.expresso.core.controller.ControllerResponse;
75 import com.jcorporate.expresso.core.controller.DBController;
76 import com.jcorporate.expresso.core.controller.Input;
77 import com.jcorporate.expresso.core.controller.NonHandleableException;
78 import com.jcorporate.expresso.core.controller.Output;
79 import com.jcorporate.expresso.core.controller.State;
80 import com.jcorporate.expresso.core.controller.Transition;
81 import com.jcorporate.expresso.core.db.DBException;
82 import com.jcorporate.expresso.core.dbobj.DBObject;
83 import com.jcorporate.expresso.core.dbobj.Schema;
84 import com.jcorporate.expresso.core.dbobj.SchemaFactory;
85 import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
86 import com.jcorporate.expresso.core.dbobj.ValidValue;
87 import com.jcorporate.expresso.ext.xml.dbobj.XMLDBObject;
88 import com.jcorporate.expresso.services.dbobj.SchemaList;
89 import org.apache.log4j.Logger;
90
91 import java.io.BufferedOutputStream JavaDoc;
92 import java.io.FileOutputStream JavaDoc;
93 import java.io.IOException JavaDoc;
94 import java.io.PrintStream JavaDoc;
95 import java.util.Enumeration JavaDoc;
96 import java.util.Iterator JavaDoc;
97 import java.util.Vector JavaDoc;
98
99
100 /**
101  * The XML transaction allows authorized users to easily
102  * import and export DBObject contents to XML formats
103  *
104  * @author Michael Nash
105  */

106 public class XMLController
107         extends DBController {
108
109     private static Logger log = Logger.getLogger(XMLController.class);
110
111     /**
112      * Our constructor declares the states this transaction supports
113      */

114     public XMLController() {
115         State promptForSchema = new State("promptForSchema",
116                 "Prompt for Schema");
117         addState(promptForSchema);
118         setInitialState("promptForSchema");
119
120         State promptImport = new State("promptImport",
121                 "Prompt for Parameters for Import");
122         addState(promptImport);
123
124         State promptFileImport = new State("promptFileImport",
125                 "Prompt for Parameters for File Import");
126         addState(promptFileImport);
127
128         State promptFileExport = new State("promptFileExport",
129                 "Prompt for Parameters for File Export");
130         addState(promptFileExport);
131
132         /* Given a schema, prompt the user to select a database object
133
134 * and then select import or export
135
136 */

137         State selDBObj = new State("selDBObj", "Select Database Object");
138         selDBObj.addRequiredParameter("SchemaClass");
139         addState(selDBObj);
140
141         State doFileExport = new State("doFileExport", "Export Data to a File");
142         doFileExport.addRequiredParameter("FileName");
143         doFileExport.addRequiredParameter("DBObjectClass");
144         addState(doFileExport);
145
146         State doFileImport = new State("doFileImport",
147                 "Import Data from a File");
148         doFileImport.addRequiredParameter("FileName");
149         addState(doFileImport);
150
151         State doImport = new State("doImport",
152                 "Import Data from remote Server");
153         doImport.addRequiredParameter("DBObjectName");
154         doImport.addRequiredParameter("Server");
155         doImport.addRequiredParameter("Login");
156         doImport.addRequiredParameter("Password");
157         addState(doImport);
158     } /* XMLController() */
159
160     /**
161      * @param req The <code>ControllerRequest</code> object given
162      * to us by the framework.
163      * @param res The <code>ControllerResponse</code> object to populate
164      * with Inputs/Outputs and Blocks.
165      */

166     private void doFileExportState(ControllerRequest req,
167                                    ControllerResponse res)
168             throws ControllerException {
169         String JavaDoc fileName = req.getParameter("FileName") + ".xml";
170         int objectCount = 0;
171
172         try {
173             FileOutputStream JavaDoc fout = new FileOutputStream JavaDoc(fileName, false);
174             BufferedOutputStream JavaDoc bout = new BufferedOutputStream JavaDoc(fout);
175             PrintStream JavaDoc XMLFileStream = new PrintStream JavaDoc(bout);
176             XMLFileStream.println("<?xml version=\"1.0\" standalone=\"no\"?>");
177             XMLFileStream.println("<!DOCTYPE ExpressoData [");
178             XMLFileStream.println("<!ELEMENT DBObjects (DBObject+)>");
179             XMLFileStream.println("<!ELEMENT DBObject (ObjectName, TableName, Data)>");
180             XMLFileStream.println("<!ELEMENT ObjectName (#PCDATA)>");
181             XMLFileStream.println("<!ELEMENT TableName (#PCDATA)>");
182             XMLFileStream.println("<!ELEMENT Data (DataRecord+)>");
183             XMLFileStream.println("<!ELEMENT DataRecord (Field)>");
184             XMLFileStream.println("<!ELEMENT Field (FieldName, FieldValue)>");
185             XMLFileStream.println("<!ELEMENT FieldName (#PCDATA)>");
186             XMLFileStream.println("<!ELEMENT FieldValue (#PCDATA)>");
187             XMLFileStream.println("]>");
188             XMLFileStream.println("<DBObjects>");
189             XMLFileStream.flush();
190             XMLFileStream.close();
191
192             DBObject oneDBObject = null;
193             String JavaDoc dbObjClassName = req.getParameter("DBObjectClass");
194
195             if (dbObjClassName.equals("All")) {
196                 Schema mySchema = getSchema(req.getParameter("SchemaClass"));
197
198                 for (Enumeration JavaDoc e = mySchema.getMembers();
199                      e.hasMoreElements();) {
200                     oneDBObject = (DBObject) e.nextElement();
201                     oneDBObject.setDataContext(req.getDataContext());
202
203                     XMLDBObject myXMLObj = new XMLDBObject(oneDBObject);
204                     myXMLObj.exportToFile(req.getParameter("FileName"));
205                     objectCount++;
206                 }
207             } else {
208                 oneDBObject = getDBObject(dbObjClassName);
209                 oneDBObject.setDataContext(req.getDataContext());
210
211                 XMLDBObject myXMLObj = new XMLDBObject(oneDBObject);
212                 myXMLObj.exportToFile(req.getParameter("FileName"));
213                 objectCount++;
214             }
215
216             FileOutputStream JavaDoc fout2 = new FileOutputStream JavaDoc(fileName, true);
217             BufferedOutputStream JavaDoc bout2 = new BufferedOutputStream JavaDoc(fout2);
218             PrintStream JavaDoc XMLFileStream2 = new PrintStream JavaDoc(bout2);
219             XMLFileStream2.println("</DBObjects>");
220             XMLFileStream2.flush();
221             XMLFileStream2.close();
222         } catch (Exception JavaDoc de) {
223             throw new ControllerException(de.getMessage());
224         }
225
226         res.addOutput(new Output("Exported " + objectCount + " objects."));
227     } /* doFileExportState() */
228
229
230     /**
231      * @param req The <code>ControllerRequest</code> object given
232      * to us by the framework.
233      * @param res The <code>ControllerResponse</code> object to populate
234      * with Inputs/Outputs and Blocks.
235      */

236     private void doFileImportState(ControllerRequest req,
237                                    ControllerResponse res)
238             throws ControllerException {
239         int errorCount = 0;
240
241         try {
242             XMLDBObject myXMLObj = new XMLDBObject();
243             myXMLObj.setDBName(req.getDataContext());
244             myXMLObj.importFromFile(req.getParameter("FileName"));
245
246             Exception JavaDoc ex = null;
247
248             for (Enumeration JavaDoc e = myXMLObj.getErrorList().elements();
249                  e.hasMoreElements();) {
250                 errorCount++;
251                 ex = (Exception JavaDoc) e.nextElement();
252                 res.addOutput(new Output(ex.getMessage()));
253             }
254         } catch (DBException de) {
255             throw new ControllerException(de.getMessage());
256         }
257
258         res.addOutput(new Output("Import Complete - " + errorCount +
259                 " errors."));
260     } /* doFileImportState() */
261
262
263     /**
264      * @param req The <code>ControllerRequest</code> object given
265      * to us by the framework.
266      */

267     private void doImportState(ControllerRequest req)
268             throws ControllerException {
269         String JavaDoc importURL = ("http://" + req.getParameter("Server") +
270                 "/servlet/Export?dbobj=" +
271                 req.getParameter("DBObjectName") +
272                 "&UserName=" +
273                 req.getParameter("Login") +
274                 "&Password=" +
275                 req.getParameter("Password"));
276
277         try {
278             XMLDBObject myXMLObj = new XMLDBObject();
279             myXMLObj.importFromURL(importURL);
280         } catch (DBException de) {
281             throw new ControllerException(de.getMessage());
282         }
283     } /* doImportState() */
284
285
286     /**
287      * @param dbObjName The Object to load.
288      * @return A Schema object instantiated from the class named by the
289      * 'SchemaClass' parameter
290      */

291     private DBObject getDBObject(String JavaDoc dbObjName)
292             throws ControllerException {
293         try {
294             return (DBObject) Class.forName(dbObjName).newInstance();
295         } catch (IllegalAccessException JavaDoc ie) {
296             throw new ControllerException("Illegal Access " +
297                     "Exception loading DBObject class " +
298                     dbObjName, ie);
299         } catch (InstantiationException JavaDoc ie) {
300             throw new ControllerException("Can't instantiate " +
301                     "DBObject class " + dbObjName, ie);
302         } catch (ClassNotFoundException JavaDoc se) {
303             throw new ControllerException("Can't find a DBObject " +
304                     "class called " + dbObjName, se);
305         } catch (Exception JavaDoc eo) {
306             throw new ControllerException("Exception loading " + "DBObject " +
307                     dbObjName, eo);
308         }
309     } /* getDBObject() */
310
311
312     /**
313      * Instantiate & return the schema class given in the current parameter
314      *
315      * @param schemaName the class-name of the schema to load.
316      * @return A Schema object instantiated from the class named by the
317      * 'SchemaClass' parameter
318      */

319     private Schema getSchema(String JavaDoc schemaName)
320             throws ControllerException {
321         Schema mySchema = SchemaFactory.getInstance().getSchema(schemaName);
322         if (mySchema == null) {
323             throw new ControllerException("Can't instantiate Schema class " +
324                     schemaName + ". See log for details");
325
326         }
327
328         return mySchema;
329     } /* getSchema(String) */
330
331
332     /**
333      * Return the title of this Transaction
334      *
335      * @return java.lang.String The Title of the controller
336      */

337     public String JavaDoc getTitle() {
338         return "Database Object XML Import/Export";
339     } /* getTitle() */
340
341     /**
342      * Old-Style State switching method.
343      *
344      * @param req The <code>ControllerRequest</code> object given
345      * to us by the framework.
346      * @param newState the new state to transition into.
347      * @return ControllerResponse.
348      * @throws ControllerException upon error.
349      * @throws NonHandleableException upon fatal error.
350      */

351     public ControllerResponse newState(String JavaDoc newState, ControllerRequest req)
352             throws ControllerException,
353             NonHandleableException {
354         ControllerResponse res = super.newState(newState, req);
355
356         if (newState.equals("promptImport")) {
357             promptImportState(res);
358         } else if (newState.equals("doImport")) {
359             doImportState(req);
360         } else if (newState.equals("promptFileExport")) {
361             promptFileExportState(req, res);
362         } else if (newState.equals("doFileExport")) {
363             doFileExportState(req, res);
364         } else if (newState.equals("doFileImport")) {
365             doFileImportState(req, res);
366         } else if (newState.equals("promptForSchema")) {
367             promptForSchema(req, res);
368         } else if (newState.equals("selDBObj")) {
369             selDBObj(req, res);
370         } else if (newState.equals("promptFileImport")) {
371             promptFileImportState(res);
372         }
373
374         log.debug("State currently '" + newState + "'");
375
376         if ((!newState.equals("promptForSchema")) && (!newState.equals(""))) {
377             Transition again = new Transition("Start Again",
378                     getClass().getName());
379             again.setName("again");
380             again.addParam(STATE_PARAM_KEY, "promptForSchema");
381             res.addTransition(again);
382         }
383
384         return res;
385     } /* newState(String) */
386
387
388     /**
389      * @param req The <code>ControllerRequest</code> object given
390      * to us by the framework.
391      * @param res The <code>ControllerResponse</code> object to populate
392      * with Inputs/Outputs and Blocks.
393      */

394     private void promptFileExportState(ControllerRequest req,
395                                        ControllerResponse res)
396             throws ControllerException {
397         try {
398             Schema mySchema = getSchema(req.getParameter("Schema"));
399
400             for (Enumeration JavaDoc e = mySchema.getMembers(); e.hasMoreElements();) {
401                 XMLDBObject myXMLObj = new XMLDBObject((DBObject) e.nextElement());
402                 myXMLObj.exportToFile(req.getParameter("FileName"));
403             }
404         } catch (DBException de) {
405             throw new ControllerException(de);
406         } catch (IOException JavaDoc ie) {
407             throw new ControllerException(ie);
408         }
409
410         Input fileName = new Input("FileName");
411         fileName.setLabel("XML File Name (no extension)");
412         res.addInput(fileName);
413
414         Input schemaName = new Input("Schema");
415         schemaName.setLabel("Schema Object Name");
416         res.addInput(schemaName);
417     } /* promptFileExportState() */
418
419
420     /**
421      * @param res The <code>ControllerResponse</code> object to populate
422      * with Inputs/Outputs and Blocks.
423      */

424     private void promptFileImportState(ControllerResponse res)
425             throws ControllerException {
426         Input fileName = new Input("FileName");
427         fileName.setLabel("XML File Name (no extension)");
428         res.addInput(fileName);
429
430         /* now the actions */
431         Transition doImport = new Transition("Begin Import",
432                 getClass().getName());
433         doImport.setName("doFileImport");
434         doImport.addParam(STATE_PARAM_KEY, "doFileImport");
435         res.addTransition(doImport);
436     } /* promptFileImportState() */
437
438
439     /**
440      * @param res The <code>ControllerResponse</code> object to populate
441      * with Inputs/Outputs and Blocks.
442      */

443     private void promptImportState(ControllerResponse res)
444             throws ControllerException {
445         Input server = new Input("Server");
446         server.setLabel("Server Name");
447         res.addInput(server);
448
449         Input dbobjName = new Input("DBObjectName");
450         dbobjName.setLabel("Database Object:");
451         res.addInput(dbobjName);
452
453         dbobjName.setLabel("Login:");
454         res.addInput(dbobjName);
455
456         Input password = new Input("Password");
457         password.setLabel("Password:");
458         res.addInput(password);
459     } /* promptImportState() */
460
461
462     /**
463      * @param req The <code>ControllerRequest</code> object given
464      * to us by the framework.
465      * @param res The <code>ControllerResponse</code> object to populate
466      * with Inputs/Outputs and Blocks.
467      */

468     private void promptForSchema(ControllerRequest req, ControllerResponse res)
469             throws ControllerException {
470         log.debug("Begin state promptForSchema");
471
472         Input chooseSchema = new Input();
473         chooseSchema.setLabel("Choose Schema");
474         chooseSchema.setName("SchemaClass");
475
476         Vector JavaDoc v2 = new Vector JavaDoc(2);
477         v2.addElement(new ValidValue("com.jcorporate.expresso." + "core.ExpressoSchema",
478                 "General"));
479
480         try {
481             SchemaList sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
482             sl.setDataContext(req.getDataContext());
483
484             SchemaList oneSchema = null;
485
486             for (Iterator JavaDoc i = sl.searchAndRetrieveList("Descrip").iterator();
487                  i.hasNext();) {
488                 oneSchema = (SchemaList) i.next();
489                 v2.addElement(new ValidValue(oneSchema.getField("SchemaClass"),
490                         oneSchema.getField("Descrip")));
491             }
492         } catch (DBException de) {
493             throw new ControllerException(de);
494         }
495
496         chooseSchema.setValidValues(v2);
497         res.addInput(chooseSchema);
498
499         /* now the actions */
500         Transition promptImport = new Transition("Import from File",
501                 getClass().getName());
502         promptImport.setName("promptFileImport");
503         promptImport.addParam(STATE_PARAM_KEY, "promptFileImport");
504         res.addTransition(promptImport);
505
506         /* now the actions */
507         Transition promptImport2 = new Transition("Import from Server",
508                 getClass().getName());
509         promptImport2.setName("promptImport");
510         promptImport2.addParam(STATE_PARAM_KEY, "promptImport");
511         res.addTransition(promptImport2);
512
513         /* now the actions */
514         Transition selDBObj = new Transition("Select Database Object",
515                 getClass().getName());
516         selDBObj.setName("selDBObj");
517         selDBObj.addParam(STATE_PARAM_KEY, "selDBObj");
518         res.addTransition(selDBObj);
519     }
520
521     /* Prompt for a database object to import/export from the specified schema */
522     private void selDBObj(ControllerRequest req, ControllerResponse res)
523             throws ControllerException {
524         Input chooseDBobj = new Input();
525         chooseDBobj.setLabel("Choose Database Object");
526         chooseDBobj.setName("DBObjectClass");
527
528         Vector JavaDoc v2 = new Vector JavaDoc(2);
529         v2.addElement(new ValidValue("All", "All Objects in this Schema"));
530
531         DBObject oneDBObject = null;
532         Schema mySchema = getSchema(req.getParameter("SchemaClass"));
533
534         for (Enumeration JavaDoc e = mySchema.getMembers(); e.hasMoreElements();) {
535             oneDBObject = (DBObject) e.nextElement();
536             v2.addElement(new ValidValue(oneDBObject.getClass().getName(),
537                     oneDBObject.getMetaData().getDescription(req.getLocale())));
538         }
539
540         chooseDBobj.setValidValues(v2);
541         res.addInput(chooseDBobj);
542         log.debug("Just added chooseDBObj");
543
544         Input fileName = new Input("FileName");
545         fileName.setLabel("XML File Name (no extension)");
546         res.addInput(fileName);
547
548         Transition doExport = new Transition("Export", getClass().getName());
549         doExport.setName("doFileExport");
550         doExport.addParam(STATE_PARAM_KEY, "doFileExport");
551         doExport.addParam("SchemaClass", req.getParameter("SchemaClass"));
552         res.addTransition(doExport);
553     } /* selDBObj(ControllerRequest, ControllerResponse) */
554
555 } /* XMLController */
556
Popular Tags