KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > utility > DBTool


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 package com.jcorporate.expresso.core.utility;
65
66 import com.jcorporate.expresso.core.ExpressoSchema;
67 import com.jcorporate.expresso.core.controller.Controller;
68 import com.jcorporate.expresso.core.dataobjects.Securable;
69 import com.jcorporate.expresso.core.db.DBConnection;
70 import com.jcorporate.expresso.core.db.DBConnectionPool;
71 import com.jcorporate.expresso.core.db.DBException;
72 import com.jcorporate.expresso.core.db.TableCreator;
73 import com.jcorporate.expresso.core.db.TypeMapper;
74 import com.jcorporate.expresso.core.dbobj.DBObject;
75 import com.jcorporate.expresso.core.dbobj.Schema;
76 import com.jcorporate.expresso.core.dbobj.SchemaFactory;
77 import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
78 import com.jcorporate.expresso.core.i18n.Messages;
79 import com.jcorporate.expresso.core.job.Job;
80 import com.jcorporate.expresso.core.job.ServerException;
81 import com.jcorporate.expresso.core.misc.ConfigManager;
82 import com.jcorporate.expresso.core.misc.ConfigurationException;
83 import com.jcorporate.expresso.core.misc.DateTime;
84 import com.jcorporate.expresso.core.misc.StringUtil;
85 import com.jcorporate.expresso.core.registry.MutableRequestRegistry;
86 import com.jcorporate.expresso.core.security.SuperUser;
87 import com.jcorporate.expresso.core.security.User;
88 import com.jcorporate.expresso.core.servlet.StdServlet;
89 import com.jcorporate.expresso.kernel.InstallLog;
90 import com.jcorporate.expresso.kernel.LogManager;
91 import com.jcorporate.expresso.services.dbobj.ControllerSecurity;
92 import com.jcorporate.expresso.services.dbobj.DBObjLimit;
93 import com.jcorporate.expresso.services.dbobj.DBObjSecurity;
94 import com.jcorporate.expresso.services.dbobj.DefaultUserInfo;
95 import com.jcorporate.expresso.services.dbobj.Event;
96 import com.jcorporate.expresso.services.dbobj.GroupMembers;
97 import com.jcorporate.expresso.services.dbobj.JobSecurity;
98 import com.jcorporate.expresso.services.dbobj.RegistrationDomain;
99 import com.jcorporate.expresso.services.dbobj.RegistrationObjectMap;
100 import com.jcorporate.expresso.services.dbobj.SchemaList;
101 import com.jcorporate.expresso.services.dbobj.Setup;
102 import com.jcorporate.expresso.services.dbobj.UserGroup;
103 import com.jcorporate.expresso.services.html.HtmlException;
104 import com.jcorporate.expresso.services.html.Page;
105 import com.jcorporate.expresso.services.html.Paragraph;
106 import com.jcorporate.expresso.services.html.Text;
107 import org.apache.log4j.Logger;
108
109 import java.io.BufferedInputStream JavaDoc;
110 import java.io.BufferedOutputStream JavaDoc;
111 import java.io.BufferedReader JavaDoc;
112 import java.io.File JavaDoc;
113 import java.io.FileInputStream JavaDoc;
114 import java.io.FileOutputStream JavaDoc;
115 import java.io.IOException JavaDoc;
116 import java.io.InputStreamReader JavaDoc;
117 import java.io.PrintStream JavaDoc;
118 import java.sql.Connection JavaDoc;
119 import java.sql.DatabaseMetaData JavaDoc;
120 import java.sql.DriverManager JavaDoc;
121 import java.sql.ResultSet JavaDoc;
122 import java.sql.SQLException JavaDoc;
123 import java.util.ArrayList JavaDoc;
124 import java.util.Date JavaDoc;
125 import java.util.Enumeration JavaDoc;
126 import java.util.Hashtable JavaDoc;
127 import java.util.Iterator JavaDoc;
128 import java.util.List JavaDoc;
129 import java.util.StringTokenizer JavaDoc;
130 import java.util.Vector JavaDoc;
131
132
133 /**
134  * DBTool is a multi-purpose tool for working with database objects. It can:
135  * <ol>
136  * <li>Verify data in the database with respect to referential integrity</li>
137  * <li>Generate the code for a Database Object by reading the data in a
138  * database</li>
139  * <li>Export data in a database object to an external XML file</li>
140  * <li>Import data from an external XML file into a database object</li>
141  * </ol>
142  * <p/>
143  * <h4>Command Line Parameters</h4>
144  * <h5 align="left">Required Command Line Arguments </h5>
145  * <p align="left"><b>configDir</b> - &lt;Directory that contains your config files&gt;</p>
146  * <p align="left"><b>webbAppDir</b> -&lt;The Expresso webapp directory&gt;</p>
147  * <p align="left"><b>db=</b>&lt;The database to create&gt;</p>
148  * <h5 align="left">Optional Command Line Argumments</h5>
149  * <p align="left">These arguments define the role to use as well as some arguments
150  * are specific for a given task. </p>
151  * <ul>
152  * <li><b>setup</b> - Setup the database schema</li>
153  * <li><b>pooltest</b> - Stress Test the Connection Pool</li>
154  * <li><b>test</b> - @todo document</li>
155  * <li><b>generate</b> - Generate DBObjects given an active database with tables.</li>
156  * <li><b>gen_package</b> generate dbobject with this package name.</li>
157  * <li><b>import</b> - import DBObjects.</li>
158  * <li><b>export</b> - export DBObjects.
159  * <br />file - The file to import or export to
160  * <br />format - Either tab or comma, or XML file format.</li>
161  * <li><b>passwords</b> - @todo Document</li>
162  * <li><b>bench</b> - Run some basic benchmarks.</li>
163  * <li><b>config</b> - Run configuration utility.</li>
164  * <li><b>nameChange</b> - Update packages to latest package format.</li>
165  * <li><b>uidChange</b> -Convert your database to integer- keyed index for users .</li>
166  * </ul>
167  *
168  * @author Michael Nash
169  * <p/>
170  * Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
171  */

172 public class DBTool
173         extends Thread JavaDoc {
174     private static final String JavaDoc thisClass = DBTool.class.getName();
175     private static String JavaDoc dbName = null;
176     private static Logger log = Logger.getLogger(DBTool.class);
177
178     /**
179      * Constructor
180      */

181     public DBTool() {
182     } /* DBTool() */
183
184     /**
185      * Choose a schema to enter Setup values for
186      *
187      * @param dbName The data context to work with
188      */

189     private static void chooseConfig(String JavaDoc dbName)
190             throws DBException, IOException JavaDoc {
191         System.out.println("Choose Schema: (Database " + dbName + ")");
192
193         Hashtable JavaDoc choices = new Hashtable JavaDoc();
194         choices.put("1",
195                 "Expresso|com.jcorporate.expresso.core.ExpressoSchema");
196
197         int nextNum = 1;
198         SchemaList sl = new SchemaList();
199         sl.setDataContext(dbName);
200
201         String JavaDoc nextKey = null;
202
203         List list = sl.searchAndRetrieveList();
204         for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
205             SchemaList oneSchemaList = (SchemaList) iterator.next();
206             nextNum++;
207             nextKey = "" + nextNum;
208             choices.put(nextKey,
209                     oneSchemaList.getField("Descrip") + "|" +
210                     oneSchemaList.getField("SchemaClass"));
211         }
212
213         /* Now present the menu */
214         String JavaDoc oneNumber = null;
215         String JavaDoc oneDescrip = null;
216
217         for (Enumeration JavaDoc ex = choices.keys(); ex.hasMoreElements();) {
218             oneNumber = (String JavaDoc) ex.nextElement();
219
220             StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc((String JavaDoc) choices.get(oneNumber), "|");
221             oneDescrip = stk.nextToken();
222             System.out.println(oneNumber + ". " + oneDescrip);
223         }
224
225         System.out.println("");
226         System.out.print("Enter the number corresponding to the schema that " +
227                 "you wish to enter/edit Setup values for:");
228
229         BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
230         String JavaDoc command = StringUtil.notNull(br.readLine());
231
232         if (command.equals("")) {
233             return;
234         } else {
235             StringTokenizer JavaDoc stk2 = new StringTokenizer JavaDoc((String JavaDoc) choices.get(command), "|");
236             stk2.nextToken();
237             enterConfig(dbName, stk2.nextToken());
238         }
239     } /* chooseConfig(String) */
240
241
242     /**
243      * Benchmark the data connection
244      */

245     private static void doBenchMarks()
246             throws DBException, SQLException JavaDoc,
247             ConfigurationException {
248         System.out.println("Benchmarks begin at " +
249                 DateTime.getDateTimeString());
250
251         int retryCount = 5000;
252         System.out.println("This benchmark tests the performance of the " +
253                 "connection pool in simple \n" +
254                 " allocations of connections - it makes & releases " +
255                 retryCount + " connections, 5 at a time.\n");
256         System.out.println("Begin connection pool tests:" +
257                 DateTime.getDateTimeString());
258
259         DBConnectionPool myPool = DBConnectionPool.getInstance("default");
260
261         for (int i = 0; i <= retryCount; i++) {
262             DBConnection conn1 = myPool.getConnection("Test " + (i + 1));
263             DBConnection conn2 = myPool.getConnection("Test " + (i + 2));
264             DBConnection conn3 = myPool.getConnection("Test " + (i + 4));
265             DBConnection conn4 = myPool.getConnection("Test " + (i + 5));
266             DBConnection conn5 = myPool.getConnection("Test " + (i + 6));
267             myPool.release(conn1);
268             myPool.release(conn2);
269             myPool.release(conn3);
270             myPool.release(conn4);
271             myPool.release(conn5);
272         }
273
274         System.out.println("End connection pool tests:" +
275                 DateTime.getDateTimeString());
276         System.out.println("Compare this to making & breaking the connection " +
277                 "to the DB the same number\n" + " of times.");
278
279         String JavaDoc dbURL = ConfigManager.getJdbcRequired("default").getUrl();
280         String JavaDoc dbLogin = ConfigManager.getJdbcRequired("default").getLogin();
281         String JavaDoc dbPassword = ConfigManager.getJdbcRequired("default").getPassword();
282         System.out.println("Begin direct connection tests:" +
283                 DateTime.getDateTimeString());
284
285         for (int i = 0; i <= retryCount; i++) {
286             Connection conn1 = DriverManager.getConnection(dbURL, dbLogin,
287                     dbPassword);
288             conn1.createStatement();
289             conn1.close();
290
291             Connection conn2 = DriverManager.getConnection(dbURL, dbLogin,
292                     dbPassword);
293             conn2.createStatement();
294             conn2.close();
295
296             Connection conn3 = DriverManager.getConnection(dbURL, dbLogin,
297                     dbPassword);
298             conn3.createStatement();
299             conn3.close();
300
301             Connection conn4 = DriverManager.getConnection(dbURL, dbLogin,
302                     dbPassword);
303             conn4.createStatement();
304             conn4.close();
305
306             Connection conn5 = DriverManager.getConnection(dbURL, dbLogin,
307                     dbPassword);
308             conn5.createStatement();
309             conn5.close();
310         }
311
312         System.out.println("End direct connection tests:" +
313                 DateTime.getDateTimeString());
314         System.out.println("Direct SQL tests - the above test is repeated, " +
315                 "but with a series of simple \n" +
316                 " SQL queries executed in each of the connections.");
317         System.out.println("Begin direct SQL tests:" +
318                 DateTime.getDateTimeString());
319
320         for (int i = 0; i <= retryCount; i++) {
321             DBConnection conn1 = myPool.getConnection("Test " + (i + 1));
322             conn1.execute("SELECT * FROM USERLOGIN WHERE UserName = 'Admin'");
323
324             DBConnection conn2 = myPool.getConnection("Test " + (i + 2));
325             conn2.execute("SELECT * FROM GROUPMEMBERS WHERE UserName = 'Admin'");
326
327             DBConnection conn3 = myPool.getConnection("Test " + (i + 4));
328             conn3.execute("SELECT * FROM SETUP WHERE SetupCode = 'ServletEvent'");
329
330             DBConnection conn4 = myPool.getConnection("Test " + (i + 5));
331             conn4.execute("SELECT * FROM DBOBJSECURITY WHERE GroupName = 'Admin'");
332
333             DBConnection conn5 = myPool.getConnection("Test " + (i + 6));
334             conn5.execute("SELECT * FROM EVENT WHERE Event = 'SYSERROR'");
335             myPool.release(conn1);
336             myPool.release(conn2);
337             myPool.release(conn3);
338             myPool.release(conn4);
339             myPool.release(conn5);
340         }
341
342         System.out.println("End direct SQL tests:" +
343                 DateTime.getDateTimeString());
344         System.out.println("DB Object tests - the above test is repeated, " +
345                 "but with db objects \n" +
346                 " doing the queries rather than direct sql");
347         System.out.println("Begin db object tests:" +
348                 DateTime.getDateTimeString());
349
350         GroupMembers gm = new GroupMembers();
351         DefaultUserInfo oneUser = new DefaultUserInfo();
352         Setup s1 = new Setup();
353         DBObjSecurity dbo = new DBObjSecurity();
354         Event e = new Event();
355
356         for (int i = 0; i <= retryCount; i++) {
357             DBConnection conn1 = myPool.getConnection("Test " + (i + 1));
358             oneUser.setConnection(conn1);
359             oneUser.setField("UserName", User.ADMIN_USER);
360             oneUser.find();
361
362             DBConnection conn2 = myPool.getConnection("Test " + (i + 2));
363             gm.setConnection(conn2);
364             gm.setField("UserName", User.ADMIN_USER);
365             gm.find();
366
367             DBConnection conn3 = myPool.getConnection("Test " + (i + 4));
368             s1.setConnection(conn3);
369             s1.setField("SetupCode", "ServletEvent");
370             s1.find();
371
372             DBConnection conn4 = myPool.getConnection("Test " + (i + 5));
373             dbo.setConnection(conn4);
374             dbo.setField("GroupName", User.ADMIN_USER);
375             dbo.find();
376
377             DBConnection conn5 = myPool.getConnection("Test " + (i + 6));
378             e.setConnection(conn5);
379             e.setField("Event", "SYSERROR");
380             e.find();
381             System.out.println("Benchmarks begin at " +
382                     DateTime.getDateTimeString());
383             myPool.release(conn1);
384             myPool.release(conn2);
385             myPool.release(conn3);
386             myPool.release(conn4);
387             myPool.release(conn5);
388         }
389
390         retryCount = 5000;
391         System.out.println("End dbobject tests:" +
392                 DateTime.getDateTimeString());
393         System.out.println("This benchmark tests the performance of the " +
394                 "connection pool in simple \n" +
395                 " allocations of connections - it makes & releases " +
396                 retryCount + " connections, 5 at a time.\n");
397         System.out.println("Begin connection pool tests:" +
398                 DateTime.getDateTimeString());
399         myPool = DBConnectionPool.getInstance("default");
400
401         for (int i = 0; i <= retryCount; i++) {
402             DBConnection conn1 = myPool.getConnection("Test " + (i + 1));
403             DBConnection conn2 = myPool.getConnection("Test " + (i + 2));
404             DBConnection conn3 = myPool.getConnection("Test " + (i + 4));
405             DBConnection conn4 = myPool.getConnection("Test " + (i + 5));
406             DBConnection conn5 = myPool.getConnection("Test " + (i + 6));
407             myPool.release(conn1);
408             myPool.release(conn2);
409             myPool.release(conn3);
410             myPool.release(conn4);
411             myPool.release(conn5);
412         }
413
414         System.out.println("End connection pool tests:" +
415                 DateTime.getDateTimeString());
416         System.out.println("Compare this to making & breaking the connection " +
417                 "to the DB the same number\n" + " of times.");
418         dbURL = ConfigManager.getJdbcRequired("default").getUrl();
419         dbLogin = ConfigManager.getJdbcRequired("default").getLogin();
420         dbPassword = ConfigManager.getJdbcRequired("default").getPassword();
421         System.out.println("Begin direct connection tests:" +
422                 DateTime.getDateTimeString());
423
424         for (int i = 0; i <= retryCount; i++) {
425             Connection conn1 = DriverManager.getConnection(dbURL, dbLogin,
426                     dbPassword);
427             conn1.createStatement();
428             conn1.close();
429
430             Connection conn2 = DriverManager.getConnection(dbURL, dbLogin,
431                     dbPassword);
432             conn2.createStatement();
433             conn2.close();
434
435             Connection conn3 = DriverManager.getConnection(dbURL, dbLogin,
436                     dbPassword);
437             conn3.createStatement();
438             conn3.close();
439
440             Connection conn4 = DriverManager.getConnection(dbURL, dbLogin,
441                     dbPassword);
442             conn4.createStatement();
443             conn4.close();
444
445             Connection conn5 = DriverManager.getConnection(dbURL, dbLogin,
446                     dbPassword);
447             conn5.createStatement();
448             conn5.close();
449         }
450
451         System.out.println("End direct connection tests:" +
452                 DateTime.getDateTimeString());
453         System.out.println("Direct SQL tests - the above test is repeated, " +
454                 "but with a series of simple \n" +
455                 " SQL queries executed in each of the connections.");
456         System.out.println("Begin direct SQL tests:" +
457                 DateTime.getDateTimeString());
458
459         for (int i = 0; i <= retryCount; i++) {
460             DBConnection conn1 = myPool.getConnection("Test " + (i + 1));
461             conn1.execute("SELECT * FROM USERLOGIN WHERE UserName = 'Admin'");
462
463             DBConnection conn2 = myPool.getConnection("Test " + (i + 2));
464             conn2.execute("SELECT * FROM GROUPMEMBERS WHERE UserName = 'Admin'");
465
466             DBConnection conn3 = myPool.getConnection("Test " + (i + 4));
467             conn3.execute("SELECT * FROM SETUP WHERE SetupCode = 'ServletEvent'");
468
469             DBConnection conn4 = myPool.getConnection("Test " + (i + 5));
470             conn4.execute("SELECT * FROM DBOBJSECURITY WHERE GroupName = 'Admin'");
471
472             DBConnection conn5 = myPool.getConnection("Test " + (i + 6));
473             conn5.execute("SELECT * FROM EVENT WHERE Event = 'SYSERROR'");
474             myPool.release(conn1);
475             myPool.release(conn2);
476             myPool.release(conn3);
477             myPool.release(conn4);
478             myPool.release(conn5);
479         }
480
481         System.out.println("End direct SQL tests:" +
482                 DateTime.getDateTimeString());
483         System.out.println("DB Object tests - the above test is repeated, " +
484                 "but with db objects \n" +
485                 " doing the queries rather than direct sql");
486         System.out.println("Begin db object tests:" +
487                 DateTime.getDateTimeString());
488         gm = new GroupMembers();
489         oneUser = new DefaultUserInfo();
490         s1 = new Setup();
491         dbo = new DBObjSecurity();
492         e = new Event();
493
494         for (int i = 0; i <= retryCount; i++) {
495             DBConnection conn1 = myPool.getConnection("Test " + (i + 1));
496
497             // Modified 05/20/01 by Shash Chatterjee
498
// Used to use UserDBObj directly....but Uid as key complicates things....
499
// oneUser.setConnection(conn1);
500
oneUser.setField("UserName", User.ADMIN_USER);
501             oneUser.find();
502
503             DBConnection conn2 = myPool.getConnection("Test " + (i + 2));
504             gm.setConnection(conn2);
505             gm.setField("UserName", User.ADMIN_USER);
506             gm.find();
507
508             DBConnection conn3 = myPool.getConnection("Test " + (i + 4));
509             s1.setConnection(conn3);
510             s1.setField("SetupCode", "ServletEvent");
511             s1.find();
512
513             DBConnection conn4 = myPool.getConnection("Test " + (i + 5));
514             dbo.setConnection(conn4);
515             dbo.setField("GroupName", User.ADMIN_USER);
516             dbo.find();
517
518             DBConnection conn5 = myPool.getConnection("Test " + (i + 6));
519             e.setConnection(conn5);
520             e.setField("Event", "SYSERROR");
521             e.find();
522             myPool.release(conn1);
523             myPool.release(conn2);
524             myPool.release(conn3);
525             myPool.release(conn4);
526             myPool.release(conn5);
527         }
528
529         System.out.println("End dbobject tests:" +
530                 DateTime.getDateTimeString());
531         System.out.println("Benchmarks end at " +
532                 DateTime.getDateTimeString());
533     } /* doBenchMarks() */
534
535
536     /**
537      * Delete Table - Deletes a table from the specified db
538      *
539      * @param dbName - the name of the db that contains this table
540      * @param tableName - The name of the table to delete.
541      */

542     public static void deleteTable(String JavaDoc dbName, String JavaDoc tableName)
543             throws DBException {
544         DBConnectionPool pool = DBConnectionPool.getInstance(dbName);
545         String JavaDoc stmnt = "DROP TABLE " + tableName;
546         pool.executeExclusiveUpdate(stmnt);
547     }
548
549     /**
550      * Method wipes out more than one installed schema.
551      *
552      * @param myPage an HTML page to render output to (optional)
553      * @param dbName The database context to create the database in.
554      * @param schemas List of the schema objects to delete
555      * @throws HtmlException if an error occurs constructing the HTML code
556      */

557     public static synchronized void deleteSchema(Page myPage, String JavaDoc dbName,
558                                                  Vector JavaDoc schemas)
559             throws DBException, HtmlException,
560             IllegalArgumentException JavaDoc {
561         log.info("Removing " + Integer.toString(schemas.size()) + " schemas");
562
563         for (Enumeration JavaDoc e = schemas.elements(); e.hasMoreElements();) {
564             String JavaDoc oneName = (e.nextElement()).getClass().getName();
565             deleteSchema(myPage, dbName, oneName);
566         }
567
568         log.info("Schema Deletion Complete");
569     }
570
571     /**
572      * Method to remove an installed schema. Deletes all the tables associated
573      * with the schema
574      *
575      * @param myPage - The page to output the 'log' to.
576      * @param dbName - the name of the database to perform this operation
577      * @param schemaName - the full classname of the schema to delete.
578      * @throws IllegalArgumentException if the schema doesn't exist.
579      * @throws DBException If there is a database problem creating
580      * the new default values
581      * @throws HtmlException If there is a problem building the
582      * confirmation page
583      * <p/>
584      * Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
585      * @since $DatabaseSchema $Date: 2004/11/20 20:11:53 $
586      */

587     public static synchronized void deleteSchema(Page myPage, String JavaDoc dbName,
588                                                  String JavaDoc schemaName)
589             throws DBException, HtmlException,
590             IllegalArgumentException JavaDoc {
591         final String JavaDoc myName = (thisClass +
592                 "deleteSchema(Page,String,String)");
593         boolean expressoDelete = false;
594         log.info(myName + ": removing schema: " + schemaName + " from db " +
595                 dbName);
596
597         if (schemaName.equals("com.jcorporate.expresso.core.ExpressoSchema")) {
598             expressoDelete = true;
599         }
600
601         Schema oneSchema = null;
602
603         try {
604             oneSchema = (Schema) Class.forName(schemaName).newInstance();
605         } catch (Throwable JavaDoc e) {
606             throw new IllegalArgumentException JavaDoc("Unable to load class " +
607                     schemaName + " " +
608                     e.getMessage());
609         }
610
611         DBObject oneObject;
612
613         try {
614
615             //Make sure all connections are dropped first - otherwise tables
616
//will be locked
617
DBConnectionPool.reInitialize();
618         } catch (DBException e) {
619         }
620         for (Enumeration JavaDoc e = oneSchema.getMembers(); e.hasMoreElements();) {
621             oneObject = (DBObject) e.nextElement();
622
623             if (myPage != null) {
624                 myPage.add(new Paragraph(new Text("Removing Table" + " " +
625                         oneObject.getJDBCMetaData().getTargetSQLTable(oneObject.getDataContext()))));
626             }
627             try {
628                 deleteTable(dbName, oneObject.getJDBCMetaData().getTargetSQLTable(oneObject.getDataContext()));
629             } catch (DBException dbe) {
630                 log.warn("Unable To Delete Table: " +
631                         oneObject.getJDBCMetaData().getTargetSQLTable(oneObject.getDataContext()) + " DB Message: " +
632                         dbe.getDBMessage());
633             }
634         }
635         //If schema is not expresso, we also have to clear the
636
//setup table
637
if (expressoDelete == false) {
638             try {
639
640                 //First remove the schema entries
641
SchemaList schemaEntry = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
642                 schemaEntry.setDataContext(dbName);
643                 schemaEntry.setField("SchemaClass", schemaName);
644                 schemaEntry.delete();
645             } catch (DBException e) {
646                 log.info("Unable to delete schema entry.", e);
647             }
648
649             //Now remove the setup values
650
Setup setupList = new Setup(SecuredDBObject.SYSTEM_ACCOUNT);
651             setupList.setDataContext(dbName);
652             setupList.setField("SchemaClass", schemaName);
653
654             List list = setupList.searchAndRetrieveList();
655             for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
656                 Setup s = (Setup) iterator.next();
657                 try {
658                     s.setDataContext(dbName);
659                     s.delete();
660                 } catch (DBException e) {
661                     if (s != null) {
662                         log.info("Unable to delete setup value: " +
663                                 s.getField("SetupCode"), e);
664                     } else {
665                         log.info("Unable to delete setup value: (s=null)", e);
666                     }
667                 }
668             }
669         }
670         if (myPage != null) {
671             myPage.add(new Paragraph(new Text("All Tables Removed")));
672         }
673     } /* otherSetups(PrintWriter, Vector, String) */
674
675
676     /**
677      * @param dbName The datacontext to use
678      * @param schemaClass The classname of the Schema Object to use
679      */

680     private static void enterConfig(String JavaDoc dbName, String JavaDoc schemaClass)
681             throws DBException, IOException JavaDoc {
682         System.out.println("Setup/Configuration values: (Database " + dbName +
683                 ", Schema " + schemaClass + ")");
684
685         Setup setupList = new Setup();
686         setupList.setDataContext(dbName);
687
688         String JavaDoc command = ("");
689         setupList.setField("SchemaClass", schemaClass);
690
691         List list = setupList.searchAndRetrieveList();
692         if (list.size() == 0) {
693             System.out.println("There were no default setup values in database/context '" +
694                     dbName +
695                     "'. You must run initial setup to create the defaults " +
696                     "first.");
697         }
698
699         for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
700             Setup oneSetup = (Setup) iterator.next();
701             System.out.println("---------------------------------");
702             System.out.println("Setup Code :" +
703                     oneSetup.getField("SetupCode"));
704             System.out.println("Description :" +
705                     oneSetup.getField("Descrip"));
706             System.out.println("Current Value:" +
707                     oneSetup.getField("SetupValue"));
708             System.out.println("");
709             System.out.print("Press enter to leave current value, or enter new value:");
710
711             BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
712             command = StringUtil.notNull(br.readLine());
713
714             if (!command.equals("")) {
715                 System.out.println("Value for code '" +
716                         oneSetup.getField("SetupCode") + "' " +
717                         " now '" + command + "'");
718                 oneSetup.setField("SetupValue", command);
719                 oneSetup.update();
720                 System.out.println("Database updated");
721             } else {
722                 System.out.println("Current value retained.");
723             }
724         } /* while more values */
725
726
727         System.out.println("All setup values have been edited & stored.");
728     } /* enterConfig(String, String) */
729
730
731     /**
732      * Export data from the named dbobject to the specified filename
733      *
734      * @param exportCmd The DBobject class name to export
735      * @param fileName The filename to export to
736      * @param format The format to export to, either 'xml', or 'tab'
737      */

738     private static void exportFile(String JavaDoc exportCmd, String JavaDoc fileName,
739                                    String JavaDoc format)
740             throws DBException, IOException JavaDoc,
741             IllegalAccessException JavaDoc,
742             InstantiationException JavaDoc,
743             ClassNotFoundException JavaDoc {
744         DBObject myObj = (DBObject) Class.forName(exportCmd).newInstance();
745
746         //myObj.setConnection(myConnection);
747
if (format == null) {
748             format = ("tab");
749         }
750         if (format.equals("tab")) {
751             exportTabFile(myObj, fileName);
752         } else if (format.equals("xml")) {
753             throw new IOException JavaDoc("not implemented yet");
754         }
755     } /* exportFile(String, String, String, DBConnection) */
756
757
758     /**
759      * Export the named database object into the given file, where the file
760      * is tab delimited, and the fields are in the order of the database
761      * object's fields
762      *
763      * @param myObj The DBOBject to export
764      * @param fileName The filename to export to
765      */

766     private static void exportTabFile(DBObject myObj, String JavaDoc fileName)
767             throws IOException JavaDoc, DBException {
768         FileOutputStream JavaDoc fout = new FileOutputStream JavaDoc(fileName, false);
769         BufferedOutputStream JavaDoc bout = new BufferedOutputStream JavaDoc(fout);
770         PrintStream JavaDoc out = new PrintStream JavaDoc(bout);
771         int lineCount = 0;
772         DBObject oneObj = null;
773         String JavaDoc fieldName = null;
774
775         for (Iterator JavaDoc rc = myObj.searchAndRetrieveList().iterator();
776              rc.hasNext();) {
777             oneObj = (DBObject) rc.next();
778
779             for (Iterator JavaDoc e = myObj.getJDBCMetaData().getFieldListArray().iterator(); e.hasNext();) {
780                 fieldName = (String JavaDoc) e.next();
781                 out.print(oneObj.getField(fieldName) + "\t");
782             } /* for each field */
783
784
785             out.println("");
786             lineCount++;
787         } /* for each record */
788
789
790         out.flush();
791         out.close();
792         System.out.println("Wrote " + lineCount + " records from " +
793                 myObj.getJDBCMetaData().getDescription() + " to " + fileName);
794     } /* exportTabFile(DBObject, String) */
795
796
797     /**
798      * Recursively generate a Java DBObject file for every table
799      * in the specified database.
800      * <p/>
801      * The schemaPattern and tableNamePattern attributes take a String
802      * that can match the JDBC pattern-matching format.
803      * A percent ("%") character will match 0
804      * or more characters in a String, while an underscore ("_") character
805      * will match any single character.
806      * So, if you wanted to retrieve information on all tables in schemas
807      * containing the string "Employee", you could use "%Employee%"
808      * for the schemaPattern parameter.
809      * <p/>
810      * Both schemaPattern and tableNamePattern may be null, in which case
811      * all tables will be returned.
812      *
813      * @param myConnection The dbconnection to use.
814      * @param schemaPattern - Only used by databases that support schemas.
815      * @param tableNamePattern - Name of the table to export or ALL
816      * @param packageName The base name of the package to generate all the DBObjects
817      * into
818      * @param dbKey The data context to generate from
819      */

820     private static void genAllDBObject(DBConnection myConnection,
821                                        String JavaDoc schemaPattern,
822                                        String JavaDoc tableNamePattern,
823                                        String JavaDoc dbKey,
824                                        String JavaDoc packageName)
825             throws IOException JavaDoc, DBException, SQLException JavaDoc {
826         System.out.println("Fetching all table names to generate JAVA source files.");
827
828         String JavaDoc tableName = null;
829         String JavaDoc schemaName = null;
830         DatabaseMetaData JavaDoc dm = myConnection.getDBMetaData();
831         ResultSet JavaDoc rs = dm.getTables(null, schemaPattern, tableNamePattern,
832                 new String JavaDoc[]{"TABLE"});
833         System.out.println("Table names obtained. Beginning JAVA source file generation.");
834         System.out.println("Using schemaPattern = " + schemaPattern +
835                 " and tableNamePattern = " + tableNamePattern +
836                 ".");
837
838         while (rs.next()) {
839             tableName = rs.getString("TABLE_NAME");
840             schemaName = rs.getString("TABLE_SCHEM");
841
842
843             if (tableName != null && tableName.length() > 0) {
844                 String JavaDoc genStr = "\tTable = " +
845                         tableName;
846                 if (StringUtil.notNull(schemaName).length() > 0) {
847                     genStr += " and schema = " + schemaName;
848                 }
849                 System.out.println(genStr);
850
851                 genDBObject(myConnection, tableName, dbKey, packageName);
852             } else {
853                 System.out.println("ignoring null table = " +
854                         tableName + " and schema = " + StringUtil.notNull(schemaName));
855
856             }
857         }
858
859         System.out.println("JAVA source file generation completed.");
860     } /* genAllDBObjects(DBConnection, String) */
861
862
863     /**
864      * Generate a Java file as a database object for the given table
865      *
866      * @param myConnection The DBConnection to use
867      * @param generate The table name to generate
868      * @param dbKey The data context to generate from
869      * @param packageName the base java package name to generate the dbobjects
870      * into
871      */

872     private static void genDBObject(DBConnection myConnection,
873                                     String JavaDoc generate,
874                                     String JavaDoc dbKey,
875                                     String JavaDoc packageName)
876             throws IOException JavaDoc, DBException, SQLException JavaDoc {
877         DatabaseMetaData JavaDoc dm = myConnection.getDBMetaData();
878 // String thisCatalog = myConnection.getCatalog();
879
//System.out.println("Catalog: " + thisCatalog);
880

881         String JavaDoc tableName = generate;
882         String JavaDoc javaClassName = getJavaClassName(tableName);
883         File JavaDoc file = new File JavaDoc(javaClassName + ".java");
884         FileOutputStream JavaDoc fout = new FileOutputStream JavaDoc(file.getName(),
885                 false);
886         System.out.println("File: " + file.getAbsoluteFile());
887         BufferedOutputStream JavaDoc bout = new BufferedOutputStream JavaDoc(fout);
888         PrintStream JavaDoc f = new PrintStream JavaDoc(bout);
889         f.println("/*");
890         f.println("* " + javaClassName + ".java");
891         f.println("*");
892         f.println("* Automatically Generated by Expresso's DBTool on " + (new Date JavaDoc()).toString());
893         f.println("*/");
894         f.println("");
895
896         if (packageName != null) {
897             f.println("package " + packageName + ";");
898         }
899         f.println("");
900         f.println("import com.jcorporate.expresso.core.dbobj.*;");
901         f.println("import com.jcorporate.expresso.core.db.*;");
902 // f.println("import java.util.Hashtable;");
903
// f.println("import java.util.Enumeration;");
904
f.println("");
905         f.println("public class " + javaClassName +
906                 " extends SecuredDBObject {");
907         f.println("");
908         f.println("\t/**");
909         f.println("\t * Constructor");
910         f.println("\t * Create a new object of this type with no connection");
911         f.println("\t * yet allocated.");
912         f.println("\t */");
913         f.println("\tpublic " + javaClassName + "() throws DBException {");
914         f.println("\t} ");
915         f.println("");
916         f.println("");
917         f.println("\t/**");
918         f.println("\t * Constructor");
919         f.println("\t *");
920         f.println("\t * @param theConnection Database connection to ");
921         f.println("\t * communicate with the database");
922         f.println("\t * @throws DBException If the new object cannot be ");
923         f.println("\t * created");
924         f.println("\t */");
925         f.println("\tpublic " + javaClassName +
926                 "(DBConnection theConnection) " + "throws DBException {");
927         f.println("\t\tsuper(theConnection);");
928         f.println("\t} ");
929         f.println("");
930         f.println("");
931         f.println("\t/**");
932         f.println("\t * Constructor");
933         f.println("\t *");
934         f.println("\t * @param theConnection DBConnection to be used to ");
935         f.println("\t * communicate with the database");
936         f.println("\t * @param theUser User name attempting to access the ");
937         f.println("\t * object");
938         f.println("\t * @throws DBException If the user cannot access this ");
939         f.println("\t * object or the object cannot be initialized");
940         f.println("\t */");
941         f.println("\tpublic " + javaClassName +
942                 "(DBConnection theConnection, " +
943                 "String theUser) throws DBException {");
944         f.println("\t\tsuper(theConnection, theUser);");
945         f.println("\t} ");
946         f.println("");
947         f.println("");
948         f.println("\t/**");
949         f.println("\t * Define the fields for this object");
950         f.println("\t *");
951         f.println("\t * @throws DBException");
952         f.println("\t */");
953         f.println("\tprotected synchronized void setupFields() throws " +
954                 "DBException {");
955         f.println("\t\tsetTargetTable(\"" + tableName + "\");");
956         f.println("");
957         f.println("\t\tsetDescription(\"Object Description Goes Here\");");
958         f.println("");
959         //Postgresql JDBC 7.2 driver bug. Tablename must be lower case
960
//which doesn't apply to other databases such as Oracle
961
try {
962             if (ConfigManager.getJdbcRequired(dbName).getDriver()
963                     .equals("org.postgresql.Driver")) {
964
965                 tableName = tableName.toLowerCase();
966             }
967         } catch (ConfigurationException ce) {
968             log.error("Error getting config for " + dbName + " ", ce);
969             throw new DBException(ce);
970         }
971
972         ArrayList JavaDoc listOfColumnNames = new ArrayList JavaDoc();
973         ResultSet JavaDoc rs = dm.getColumns(null, "%", tableName, "%");
974         String JavaDoc fieldName = null;
975         String JavaDoc fieldType;
976         String JavaDoc expressoType = null;
977         int sqlType = 0;
978         int fieldSize;
979         int nullField = 0;
980         boolean nullable;
981         String JavaDoc fieldDescrip = null;
982         TypeMapper tm = TypeMapper.getInstance(dbKey);
983         while (rs.next()) {
984
985             sqlType = rs.getInt(5);
986             expressoType = tm.getTypeForExpresso(sqlType);
987
988             if (expressoType == null || expressoType.length() == 0) {
989
990                 expressoType = "UNMAPPED_TYPE";
991
992             }
993
994             fieldName = rs.getString(4);
995             listOfColumnNames.add("\tpublic static final String "
996                     + fieldName + " = \"" + fieldName + "\";");
997
998             fieldSize = rs.getInt(7);
999
1000            fieldDescrip = rs.getString(12);
1001
1002            fieldType = rs.getString(6);
1003
1004            nullField = rs.getInt(11);
1005
1006            if (nullField == DatabaseMetaData.columnNoNulls) {
1007
1008                nullable = false;
1009
1010            } else {
1011
1012                nullable = true;
1013
1014            }
1015
1016            f.print("\t\taddField(" + fieldName + ", \"" + expressoType);
1017
1018            f.print("\", " + fieldSize + ", ");
1019
1020            if (nullable) {
1021
1022                f.print("true");
1023
1024            } else {
1025
1026                f.print("false");
1027
1028            }
1029
1030            f.print(", \"" + StringUtil.notNull(fieldDescrip) + "\");");
1031
1032            f.println(
1033                    "\t // " + fieldName + " had DB type: " + fieldType + " in the database that was reverse-engineered.");
1034
1035        } /* for each field */
1036
1037
1038        f.println("");
1039        ResultSet JavaDoc rspk = dm.getPrimaryKeys(null, "%", tableName);
1040
1041        while (rspk.next()) {
1042            f.println("\t\taddKey(" + rspk.getString("COLUMN_NAME") + ");");
1043        }
1044
1045        f.println("\t} /* setupFields() */");
1046        f.println("");
1047
1048        // it would have been nice to do this at top of class, but it is easier to
1049
// declare these statics here
1050
for (Iterator JavaDoc iter = listOfColumnNames.iterator(); iter.hasNext();) {
1051            String JavaDoc fieldDecl = (String JavaDoc) iter.next();
1052            f.println(fieldDecl);
1053        }
1054        f.println("");
1055        f.println("\t/**");
1056        f.println("\t * Standard method to create a new copy of this ");
1057        f.println("\t * particular database object");
1058        f.println("\t * ");
1059        f.println("\t * @return DBObject A newly created instance of this " +
1060                "object");
1061        f.println("\t * @throws DBException If the new object cannot be " +
1062                "created");
1063        f.println("\t */");
1064        f.println("\tpublic DBObject getThisDBObj() throws DBException {");
1065        f.println(" return new " + javaClassName + "();");
1066        f.println("\t} ");
1067        f.println("} /* " + javaClassName + " */");
1068        f.println("");
1069        f.close();
1070    } /* genDBObject(DBConnection, String) */
1071
1072
1073    /**
1074     * Reverse engineer the table for each db object for every known schema, then
1075     * compare the fields in the database to the fields in the db object and report
1076     * on the differences to the the log and to System.err
1077     * <p/>
1078     * todo why isn't this log passed in used?
1079     *
1080     * @param theLog the Install log to output to
1081     * @param allSchemas a vector of all the schemas to compare
1082     * @param dbName the data context to use
1083     * @return list of string error messages
1084     */

1085    public static List compareTables(InstallLog theLog, Vector JavaDoc allSchemas,
1086                                     String JavaDoc dbName)
1087            throws DBException,
1088            ConfigurationException {
1089        String JavaDoc defaultDbName = dbName;
1090        ArrayList JavaDoc messages = new ArrayList JavaDoc();
1091        messages.add("Comparing tables for database '" + dbName + "'");
1092
1093        boolean compareLengths = true;
1094
1095        /* Some drivers can't provide length information, notably Hsql */
1096        if (StringUtil.notNull(ConfigManager.getJdbcRequired(dbName).getDriver()).equals("org.hsqldb.jdbcDriver")) {
1097            compareLengths = false;
1098        }
1099
1100        DBConnectionPool myPool = null;
1101        DBConnection myConnection = null;
1102
1103        try {
1104
1105            /* For each schema */
1106            for (Enumeration JavaDoc e = allSchemas.elements(); e.hasMoreElements();) {
1107                Schema oneSchema = (Schema) e.nextElement();
1108                messages.add("Schema:" + oneSchema.getClass().getName());
1109
1110                if (log.isDebugEnabled()) {
1111                    log.debug("Schema:" + oneSchema.getClass().getName());
1112                }
1113
1114                /* for each database object in the schema */
1115                DBObject oneDBObject = null;
1116
1117                for (Enumeration JavaDoc dbo = oneSchema.getMembers();
1118                     dbo.hasMoreElements();) {
1119                    oneDBObject = (DBObject) dbo.nextElement();
1120
1121                    if (log.isDebugEnabled()) {
1122                        log.debug("DBObject:" +
1123                                oneDBObject.getClass().getName());
1124                    }
1125
1126                    oneDBObject.setDataContext(defaultDbName);
1127
1128                    //STOP HERE
1129
//This dbobject may be in an "otherdb" location, so we get it
1130
//back to see...
1131
dbName = oneDBObject.getMappedDataContext();
1132                    myPool = DBConnectionPool.getInstance(dbName);
1133                    myConnection = myPool.getConnection();
1134
1135                    DatabaseMetaData JavaDoc dm = myConnection.getDBMetaData();
1136                    ArrayList JavaDoc allFieldsFromObj = oneDBObject.getMetaData().getFieldListArray();
1137                    ArrayList JavaDoc allFields = new ArrayList JavaDoc();
1138                    String JavaDoc oneFieldName = null;
1139
1140                    for (Iterator JavaDoc of = allFieldsFromObj.iterator();
1141                         of.hasNext();) {
1142                        oneFieldName = (String JavaDoc) of.next();
1143                        allFields.add(oneFieldName);
1144                    }
1145
1146                    String JavaDoc tableName = oneDBObject.getJDBCMetaData().getTargetSQLTable(oneDBObject.getDataContext());
1147                    //Postgresql JDBC 7.2 driver bug. Tablename must be lower case
1148
//which doesn't apply to other databases such as Oracle
1149
if (ConfigManager.getJdbcRequired(dbName).getDriver()
1150                            .equals("org.postgresql.Driver")) {
1151
1152                        tableName = tableName.toLowerCase();
1153                    }
1154                    ResultSet JavaDoc rs = dm.getColumns(null, "%", tableName, "%");
1155                    String JavaDoc fieldName = null;
1156// String fieldType;
1157
int fieldSize;
1158                    int nullField = 0;
1159                    boolean nullable;
1160                    String JavaDoc nullableByDBObj = null;
1161
1162                    while (rs.next()) {
1163                        fieldName = rs.getString(4);
1164                        fieldSize = rs.getInt(7);
1165                        //fieldDescrip = rs.getString(12);
1166
//fieldType = rs.getString(6);
1167
nullField = rs.getInt(11);
1168
1169                        if (nullField == DatabaseMetaData.columnNoNulls) {
1170                            nullable = false;
1171                        } else {
1172                            nullable = true;
1173                        }
1174                        if (log.isDebugEnabled()) {
1175                            log.debug("Field:" + fieldName);
1176                        }
1177                        /* Now compare */
1178                        String JavaDoc internalFieldName = oneDBObject.getJDBCMetaData().isFieldIgnoreCase(fieldName);
1179                        if (internalFieldName != null) {
1180                            nullableByDBObj = "N";
1181
1182                            if (oneDBObject.getFieldMetaData(internalFieldName).allowsNull()) {
1183                                nullableByDBObj = "Y";
1184                            }
1185                            /* Drop it from the list of field names, so we know we've */
1186                            /* done it */
1187                            if (compareLengths) {
1188                                int dbObjLength = oneDBObject.getLengthInt(internalFieldName);
1189
1190                                if ((dbObjLength != fieldSize) &&
1191                                        (dbObjLength != 0)) {
1192                                    messages.add("Length does not match: Field '" +
1193                                            fieldName + "' in table '" +
1194                                            tableName +
1195                                            "' is defined as length " +
1196                                            fieldSize + ", " +
1197                                            " but in DBObject '" +
1198                                            oneDBObject.getClass().getName() +
1199                                            "' is defined as type " +
1200                                            oneDBObject.getFieldMetaData(internalFieldName).getTypeString() +
1201                                            " size " + dbObjLength +
1202                                            " and null allowed = " +
1203                                            nullableByDBObj +
1204                                            ". The table should be " +
1205                                            " altered to match.");
1206                                }
1207                            }
1208                            if (nullableByDBObj.equals("N") && nullable) {
1209                                messages.add("Field '" + fieldName +
1210                                        "' in table '" + tableName +
1211                                        "' allows nulls in the database, but the " +
1212                                        oneDBObject.getClass().getName() +
1213                                        " DBObject does not allow nulls for this " +
1214                                        " field. It should be set to not allow " +
1215                                        " nulls in the database as well." +
1216                                        " It is defined as type " +
1217                                        oneDBObject.getFieldMetaData(internalFieldName).getTypeString() +
1218                                        ", length " +
1219                                        oneDBObject.getFieldMetaData(internalFieldName).getLengthInt() +
1220                                        ".");
1221                            }
1222                            if (nullableByDBObj.equals("Y") && (!nullable)) {
1223                                messages.add("Field '" + fieldName +
1224                                        "' in table '" + tableName +
1225                                        "' does not allow nulls in the database, " +
1226                                        "but the " +
1227                                        oneDBObject.getClass().getName() +
1228                                        " DBObject *does* allow nulls for this " +
1229                                        " field. It should be set to allow " +
1230                                        " nulls in the database as well." +
1231                                        " It is defined as type " +
1232                                        oneDBObject.getFieldMetaData(internalFieldName).getTypeString() +
1233                                        ", length " +
1234                                        oneDBObject.getFieldMetaData(internalFieldName).getLengthInt() +
1235                                        ".");
1236                            }
1237
1238                            allFields.remove(internalFieldName);
1239                        } else {
1240                            messages.add("Field '" + fieldName +
1241                                    "' is in the table '" + tableName +
1242                                    "', but is not " +
1243                                    "a field in DBObject '" +
1244                                    oneDBObject.getClass().getName() +
1245                                    "'. It should be " +
1246                                    "dropped from the table.");
1247                        }
1248                    } /* for each field */
1249
1250
1251                    String JavaDoc oneLeftOverFieldName = null;
1252
1253                    for (Iterator JavaDoc leftOvers = allFields.iterator();
1254                         leftOvers.hasNext();) {
1255                        oneLeftOverFieldName = (String JavaDoc) leftOvers.next();
1256
1257                        if (!oneDBObject.getMetaData().isVirtual(oneLeftOverFieldName)) {
1258                            messages.add("Field '" + oneLeftOverFieldName +
1259                                    "' is defined in " + "db object '" +
1260                                    oneDBObject.getClass().getName() +
1261                                    "', but " +
1262                                    "is not defined as part of the table '" +
1263                                    oneDBObject.getJDBCMetaData().getTargetSQLTable(oneDBObject.getDataContext()) +
1264                                    "' in the database. You " +
1265                                    "must alter this table to add this field." +
1266                                    " It is defined as type " +
1267                                    oneDBObject.getFieldMetaData(oneLeftOverFieldName).getTypeString() +
1268                                    ", length " +
1269                                    oneDBObject.getFieldMetaData(oneLeftOverFieldName).getLengthInt() +
1270                                    " and allows null = " +
1271                                    nullableByDBObj + ".");
1272                        }
1273                    }
1274                    if (myPool != null) {
1275                        myPool.release(myConnection);
1276                    }
1277
1278                    myPool = null;
1279                } /* for each DB Object in this schema */
1280
1281            } /* for each schema */
1282
1283        } catch (SQLException JavaDoc se) {
1284            throw new DBException(se);
1285        } finally {
1286            if (myPool != null) {
1287                myPool.release(myConnection);
1288            }
1289        }
1290
1291        String JavaDoc oneMessage = null;
1292        for (Iterator JavaDoc i = messages.iterator(); i.hasNext();) {
1293            oneMessage = (String JavaDoc) i.next();
1294            log.info(oneMessage);
1295            System.out.println(oneMessage);
1296        } /* for each message */
1297
1298        return messages;
1299    } /* compareTables(DBConnection, String) */
1300
1301
1302    /**
1303     * Instantiate & load all Schema objects that we know about,
1304     * get a list of their DBObjects, and call the import or export
1305     * for each DBObject as appropriate
1306     *
1307     * @param myConnection The DBConnection to use
1308     * @param choice either 'import' or 'export'
1309     * @param format The import format, either 'tab' or 'xml'
1310     * @throws ServerException Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
1311     * @since $DatabaseSchema $Date: 2004/11/20 20:11:53 $
1312     */

1313    private static void importExportAll(DBConnection myConnection,
1314                                        String JavaDoc choice, String JavaDoc format)
1315            throws DBException, IllegalAccessException JavaDoc,
1316            InstantiationException JavaDoc,
1317            ClassNotFoundException JavaDoc, IOException JavaDoc,
1318            ServerException {
1319        String JavaDoc extension;
1320
1321        if (format == null) {
1322            format = ("tab");
1323        }
1324        if (format.equals("xml")) {
1325            extension = ("xml");
1326        } else {
1327            extension = ("dat");
1328        }
1329
1330        Vector JavaDoc allSchemas = new Vector JavaDoc(5);
1331        {
1332            ExpressoSchema jcs = new ExpressoSchema();
1333            allSchemas.addElement(jcs);
1334
1335            SchemaList sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
1336            List list = sl.searchAndRetrieveList();
1337            for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
1338                SchemaList oneSchema = (SchemaList) iterator.next();
1339
1340                Schema mySchema2 = SchemaFactory.getInstance().getSchema(oneSchema.getField("SchemaClass"));
1341
1342                if (mySchema2 != null) {
1343                    allSchemas.addElement(mySchema2);
1344                }
1345            }
1346        }
1347
1348        System.out.println("Loaded " + allSchemas.size() + " schema objects.");
1349
1350        Schema thisSchema = null;
1351
1352        for (Enumeration JavaDoc als = allSchemas.elements(); als.hasMoreElements();) {
1353            thisSchema = (Schema) als.nextElement();
1354            System.out.println(choice + "ing objects in Schema " +
1355                    thisSchema.getClass().getName());
1356
1357            DBObject oneObject = null;
1358
1359            for (Enumeration JavaDoc dbo = thisSchema.getMembers();
1360                 dbo.hasMoreElements();) {
1361                oneObject = (DBObject) dbo.nextElement();
1362                System.out.println(choice + "ing database object " +
1363                        oneObject.getJDBCMetaData().getName() + " (" +
1364                        oneObject.getJDBCMetaData().getDescription() + ")");
1365
1366                //oneObject.setConnection(myConnection);
1367
if (choice.equals("import")) {
1368                    importFile(oneObject.getClass().getName(),
1369                            oneObject.getJDBCMetaData().getTargetSQLTable(oneObject.getDataContext()) + "." + extension,
1370                            format, myConnection);
1371                } else {
1372                    exportFile(oneObject.getClass().getName(),
1373                            oneObject.getJDBCMetaData().getTargetSQLTable(oneObject.getDataContext()) + "." + extension,
1374                            format);
1375                }
1376            } /* for each database object */
1377
1378        } /* for each schema in the list */
1379
1380    } /* importExportAll(DBConnection, String, String) */
1381
1382
1383    /**
1384     * Import data into the named dbobject from the specified filename
1385     *
1386     * @param importCmd The DBObject class name to import
1387     * @param fileName The filename to use
1388     * @param format either 'tab' or 'xml'
1389     * @param myConnection The DBConnection to use for import
1390     * @throws ServerException Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
1391     * @since $DatabaseSchema $Date: 2004/11/20 20:11:53 $
1392     */

1393    private static void importFile(String JavaDoc importCmd, String JavaDoc fileName,
1394                                   String JavaDoc format, DBConnection myConnection)
1395            throws DBException, IOException JavaDoc,
1396            IllegalAccessException JavaDoc,
1397            InstantiationException JavaDoc,
1398            ClassNotFoundException JavaDoc, ServerException {
1399        DBObject myObj = (DBObject) Class.forName(importCmd).newInstance();
1400
1401        //myObj.setConnection(myConnection);
1402

1403        /* Clear existing data */
1404        System.out.println("Clearing existing data from " +
1405                myObj.getJDBCMetaData().getTargetSQLTable(myObj.getDataContext()));
1406        myConnection.executeUpdate("DELETE FROM " + myObj.getJDBCMetaData().getTargetSQLTable(myObj.getDataContext()));
1407
1408        if (format == null) {
1409            format = ("tab");
1410        }
1411        if (format.equals("tab")) {
1412            importTabFile(myObj, fileName);
1413        } else if (format.equals("xml")) {
1414            throw new ServerException(":XML import not yet implemented.");
1415        }
1416    } /* importFile(String, String, String, DBConnection) */
1417
1418
1419    /**
1420     * Import the named file into the given database object, where the file
1421     * is tab delimited, and the fields are in the order of the database
1422     * object's fields
1423     *
1424     * @param myObj The DBObject to import to
1425     * @param fileName The filename of the tab delimited file.
1426     */

1427    private static void importTabFile(DBObject myObj, String JavaDoc fileName)
1428            throws IOException JavaDoc, DBException,
1429            ServerException {
1430        FileInputStream JavaDoc fin = new FileInputStream JavaDoc(fileName);
1431        BufferedInputStream JavaDoc bin = new BufferedInputStream JavaDoc(fin);
1432        BufferedReader JavaDoc ds = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(bin));
1433        int lineCount = 0;
1434        String JavaDoc oneLine = ds.readLine();
1435
1436        while (oneLine != null) {
1437            importTabLine(oneLine, myObj, lineCount);
1438            lineCount++;
1439            oneLine = ds.readLine();
1440        }
1441
1442        System.out.println("Loaded " + lineCount + " records into " +
1443                myObj.getJDBCMetaData().getDescription());
1444    } /* importTabFile(DBObject, String) */
1445
1446
1447    /**
1448     * Process a single line of tab-delimited data into a record for the
1449     * given database object, and add the object to the database
1450     *
1451     * @param oneLine One tab delimited line.
1452     * @param myObj The target DBObject
1453     * @param lineNumber Line Number in the tab file, used for error tracking
1454     */

1455    private static void importTabLine(String JavaDoc oneLine, DBObject myObj,
1456                                      int lineNumber)
1457            throws DBException, ServerException {
1458        String JavaDoc fieldName = null;
1459        myObj.clear();
1460
1461        StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(oneLine, "\t");
1462
1463        for (Iterator JavaDoc e = myObj.getJDBCMetaData().getFieldListArray().iterator(); e.hasNext();) {
1464            fieldName = (String JavaDoc) e.next();
1465
1466            if (!stk.hasMoreTokens()) {
1467                throw new ServerException("Error on line " + lineNumber +
1468                        " of import file. No value for field '" +
1469                        fieldName + "'");
1470            }
1471
1472            myObj.setField(fieldName, stk.nextToken());
1473        } /* for each field */
1474
1475
1476        myObj.add();
1477    } /* importTabLine(String, DBObject, int) */
1478
1479
1480    /**
1481     * Main method so that DBTool can be launched from a command line
1482     *
1483     * @param args Command line arguments to supply the information to
1484     * connect to the database
1485     */

1486    public static void main(String JavaDoc[] args) {
1487        String JavaDoc myName = (thisClass + "main(String[])");
1488        Hashtable JavaDoc commandArgs = new Hashtable JavaDoc(10);
1489        String JavaDoc paramCode = null;
1490        String JavaDoc paramValue = null;
1491
1492        for (int i = 0; i < args.length; i++) {
1493            StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(args[i], "=");
1494
1495            if (!stk.hasMoreTokens()) {
1496                usage();
1497            }
1498
1499            paramCode = stk.nextToken();
1500
1501            if (!stk.hasMoreTokens()) {
1502                usage();
1503            }
1504
1505            paramValue = stk.nextToken();
1506            commandArgs.put(paramCode, paramValue);
1507        } /* for each command-line argument */
1508
1509        try {
1510            if (commandArgs.get("configDir") == null) {
1511                usage();
1512                System.exit(0);
1513            }
1514
1515            String JavaDoc logDir = (String JavaDoc) commandArgs.get("logDir");
1516            String JavaDoc logConfig = (String JavaDoc) commandArgs.get("logConfig");
1517            if (logConfig == null) {
1518                logConfig = (String JavaDoc) commandArgs.get("configDir") + "/expressoLogging.xml";
1519            }
1520
1521            new LogManager(logConfig, logDir); // todo necessary?
1522

1523            // set up ConfigManager first
1524
ConfigManager.setWebAppDir((String JavaDoc) commandArgs.get("webAppDir"));
1525            ConfigManager.load((String JavaDoc) commandArgs.get("configDir"));
1526            //initialize the db pool
1527
ConfigManager.dbInitialize();
1528
1529            //Load DBOtherMaps
1530
ConfigManager.mapOtherDBs();
1531
1532            //call the LoadLists method and load up the lists used by this application
1533
dbName = StringUtil.notNull((String JavaDoc) commandArgs.get("db"));
1534
1535            if (dbName.equals("")) {
1536                dbName = "default";
1537            }
1538
1539            //Set the permission of the request context.
1540
new MutableRequestRegistry(dbName,
1541                    SuperUser.SUPER_USER);
1542
1543            String JavaDoc setup = (String JavaDoc) commandArgs.get("setup");
1544            String JavaDoc poolTest = (String JavaDoc) commandArgs.get("pooltest");
1545            String JavaDoc testMode = (String JavaDoc) commandArgs.get("test");
1546            String JavaDoc generate = (String JavaDoc) commandArgs.get("generate");
1547            String JavaDoc fileName = (String JavaDoc) commandArgs.get("file");
1548            String JavaDoc importCmd = (String JavaDoc) commandArgs.get("import");
1549            String JavaDoc exportCmd = (String JavaDoc) commandArgs.get("export");
1550            String JavaDoc format = (String JavaDoc) commandArgs.get("format");
1551// String updPassword = (String) commandArgs.get("passwords");
1552
String JavaDoc benchMark = (String JavaDoc) commandArgs.get("bench");
1553            String JavaDoc config = (String JavaDoc) commandArgs.get("config");
1554            String JavaDoc nameChange = (String JavaDoc) commandArgs.get("nameChange");
1555// String uidChange = (String) commandArgs.get("uidChange");
1556
String JavaDoc schemaPattern = (String JavaDoc) commandArgs.get("schemaPattern");
1557            String JavaDoc tableNamePattern = (String JavaDoc) commandArgs.get("tableNamePattern");
1558            String JavaDoc packageName = (String JavaDoc) commandArgs.get("gen_package");
1559
1560            if (setup != null) {
1561                setup(dbName);
1562
1563                System.out.println("Exiting....");
1564                ConfigManager.destroy();
1565                return;
1566            }
1567            if (config != null) {
1568                chooseConfig(dbName);
1569
1570                System.out.println("Exiting....");
1571                ConfigManager.destroy();
1572                return;
1573            }
1574            if (nameChange != null) {
1575                nameChange(dbName);
1576
1577                System.out.println("Exiting....");
1578                ConfigManager.destroy();
1579                return;
1580            }
1581            if (benchMark != null) {
1582                doBenchMarks();
1583
1584                System.out.println("Exiting....");
1585                ConfigManager.destroy();
1586                return;
1587            }
1588// if (uidChange != null) {
1589
// doUidChange();
1590
//
1591
// return;
1592
// }
1593

1594            DBConnectionPool myPool = DBConnectionPool.getInstance(dbName);
1595
1596            if (poolTest != null) {
1597                System.out.println("Database Connection Pool Test Mode");
1598                poolTest();
1599                System.out.println("Connection pool tests completed.");
1600                System.exit(1);
1601            }
1602
1603            DBConnection myConnection = myPool.getConnection("DBTool");
1604
1605            if (testMode != null) {
1606                System.out.println("Database/Database Object Test Mode");
1607                testAllSchemas();
1608                System.out.println("All tests completed.");
1609            }
1610            if (generate != null) {
1611                System.out.println("Generate DBObject Mode");
1612
1613                if ("ALL".equalsIgnoreCase(generate)) {
1614
1615                    //We are generating source files for all database tables.
1616
//Now we call genAllDBOBjects with the schemaPattern and
1617
//tableNamePattern values. If these arguments where not
1618
//given, then they will be passed as nulls with no harm done
1619
//(they will be ignored).
1620
genAllDBObject(myConnection, schemaPattern,
1621                            tableNamePattern, dbName, packageName);
1622                } else {
1623                    genDBObject(myConnection, generate, dbName, packageName);
1624                }
1625            }
1626            if (importCmd != null) {
1627                System.out.println("Import Data Mode");
1628
1629                if (importCmd.equalsIgnoreCase("ALL")) {
1630                    importExportAll(myConnection, "import", format);
1631                }
1632                if (fileName == null) {
1633                    throw new ServerException(myName + ":You must supply a " +
1634                            "file=xxx argument for import.");
1635                }
1636
1637                importFile(importCmd, fileName, format, myConnection);
1638            }
1639            if (exportCmd != null) {
1640                System.out.println("Export Data Mode");
1641
1642                if (exportCmd.equalsIgnoreCase("ALL")) {
1643                    importExportAll(myConnection, "export", format);
1644                } else {
1645                    if (fileName == null) {
1646                        throw new ServerException(myName +
1647                                ":You must supply a " +
1648                                "file=xxx argument for export.");
1649                    }
1650
1651                    exportFile(exportCmd, fileName, format);
1652                }
1653            } /* if export */
1654
1655
1656            myPool.release(myConnection);
1657        } catch (Exception JavaDoc de) {
1658            System.out.println("DBTool Error:" + de.getMessage());
1659            de.printStackTrace();
1660            System.exit(1);
1661        }
1662        System.out.println("Exiting....");
1663        ConfigManager.destroy();
1664    } /* main(String) */
1665
1666    /**
1667     * This method returns true if the string contains both upper and lowercase
1668     * letters, false otherwise.
1669     *
1670     * @param stringToCheck The string to check against.
1671     * @return true if the string has mixed case letters in it.
1672     */

1673    private static boolean isMixedCase(String JavaDoc stringToCheck) {
1674        if (stringToCheck == null) {
1675            return false;
1676        }
1677
1678        char[] cArray = stringToCheck.toCharArray();
1679        boolean hasLowerCase = false;
1680        boolean hasUpperCase = false;
1681
1682        for (int i = 0; i < cArray.length; i++) {
1683            if (hasLowerCase && hasUpperCase) {
1684                return true;
1685            }
1686            if (Character.isUpperCase(cArray[i])) {
1687                hasUpperCase = true;
1688            }
1689            if (Character.isLowerCase(cArray[i])) {
1690                hasLowerCase = true;
1691            }
1692        }
1693
1694        return false;
1695    } /* isMixedCase(String) */
1696
1697    /**
1698     * Creates a Java Class name from a database table name.
1699     * Removes underscore characters and spaces, capitalizes the first
1700     * letter of each word.
1701     *
1702     * @param tableName The tablename to check
1703     * @return java.lang.String The classname to be used.
1704     */

1705    private static String JavaDoc getJavaClassName(String JavaDoc tableName) {
1706        if (tableName == null) {
1707            return "";
1708        }
1709        //if the name is mixed case, we do not transform it.
1710
if (isMixedCase(tableName)) {
1711            return tableName;
1712        }
1713
1714        StringBuffer JavaDoc nameBuf = new StringBuffer JavaDoc();
1715        StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(tableName, "_ ");
1716
1717        while (st.hasMoreTokens()) {
1718            nameBuf.append(prepareWord(st.nextToken()));
1719        }
1720
1721        return nameBuf.toString();
1722    } /* getJavaClassName(String tableName) */
1723
1724    /**
1725     * prepareWord prepares a single word for use in a Java class name
1726     * by capitalizing the first letter and lowecasing the rest.
1727     *
1728     * @param wordToPrepare the String to processs
1729     * @return the appropriate mixed case word
1730     */

1731    private static String JavaDoc prepareWord(String JavaDoc wordToPrepare) {
1732        String JavaDoc preparedWord = null;
1733
1734        if (wordToPrepare == null) {
1735            return "";
1736        }
1737        if (wordToPrepare.length() <= 1) {
1738            return wordToPrepare;
1739        }
1740
1741        //lowercase the word
1742
wordToPrepare = wordToPrepare.toLowerCase();
1743
1744        //now uppercase the first letter
1745
String JavaDoc firstLetter = wordToPrepare.substring(0, 1);
1746        firstLetter = firstLetter.toUpperCase();
1747        preparedWord = firstLetter + wordToPrepare.substring(1);
1748
1749        return preparedWord;
1750    } /* prepareWord(String) */
1751
1752
1753    /**
1754     * Performs the Expresso 3 to Expresso 4 name changes
1755     *
1756     * @param dbName The data context to correct
1757     */

1758    private static void nameChange(String JavaDoc dbName)
1759            throws DBException {
1760        System.out.println("Beginning name change update...");
1761
1762        ControllerSecurity secList = new ControllerSecurity();
1763        secList.setDataContext(dbName);
1764
1765        String JavaDoc currClass = null;
1766        int updateCount = 0;
1767        ControllerSecurity newSec = null;
1768        String JavaDoc newClass = null;
1769
1770        List list = secList.searchAndRetrieveList();
1771        for (Iterator JavaDoc iter = list.iterator(); iter.hasNext();) {
1772            ControllerSecurity oneSec = (ControllerSecurity) iter.next();
1773            currClass = oneSec.getField("ControllerClass");
1774
1775            if (currClass.indexOf(".trx.") > 0) {
1776                newSec = new ControllerSecurity();
1777                newSec.setDataContext(dbName);
1778                newClass = StringUtil.replace(currClass, ".trx.",
1779                        ".controller.");
1780                newSec.setField("GroupName", oneSec.getField("GroupName"));
1781
1782                if (!newSec.find()) {
1783                    newSec.setField("States", oneSec.getField("States"));
1784                    newSec.setField("GroupName", oneSec.getField("GroupName"));
1785                    newSec.setField("ControllerClass", newClass);
1786                    newSec.add();
1787                }
1788
1789                oneSec.delete();
1790                updateCount++;
1791            }
1792        }
1793
1794        System.out.println("\n" + updateCount + " entries changed");
1795    } /* nameChange(String) */
1796
1797    private static void poolTest() {
1798        throw new java.lang.UnsupportedOperationException JavaDoc("pool test has been " +
1799                "moved to it's own junit test suite in " +
1800                "com.jcorporate.expresso.core.db.tests");
1801    } /* poolTest() */
1802
1803
1804    /**
1805     * Command line setup
1806     *
1807     * @param dbName The data context to use
1808     * @throws ConfigurationException if we're working with a data context
1809     * that does not exist in the config files.
1810     */

1811    private static void setup(String JavaDoc dbName)
1812            throws DBException, ConfigurationException {
1813        System.out.println("Beginning system setup...");
1814
1815        if (StringUtil.notNull(dbName).equals("")) {
1816            dbName = "default";
1817        }
1818
1819        Vector JavaDoc allSchemas = new Vector JavaDoc(5);
1820        ExpressoSchema jcs = new ExpressoSchema();
1821        allSchemas.addElement(jcs);
1822
1823        SchemaList sl = null;
1824        SchemaList oneSchema = null;
1825        boolean noOtherSchemas = true;
1826
1827        try {
1828            sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
1829            sl.setDataContext(dbName);
1830
1831            if (sl.count() > 0) {
1832                noOtherSchemas = false;
1833            }
1834        } catch (DBException de) {
1835            noOtherSchemas = true;
1836        }
1837        if (!noOtherSchemas) {
1838
1839            List list = sl.searchAndRetrieveList();
1840            for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
1841                oneSchema = (SchemaList) iterator.next();
1842
1843                boolean schemaWarning = false;
1844
1845                Schema mySchema2 = SchemaFactory.getInstance().getSchema(oneSchema.getField("SchemaClass"));
1846                if (mySchema2 != null) {
1847                    allSchemas.addElement(mySchema2);
1848                    System.out.println("Adding Schema " +
1849                            oneSchema.getField("SchemaClass"));
1850                } else {
1851                    schemaWarning = true;
1852                }
1853                if (schemaWarning) {
1854                    System.err.println("Warning: Unable to process schema " +
1855                            oneSchema.getField("SchemaClass") +
1856                            " - see log for details");
1857                }
1858            }
1859
1860        } /* if we read other schemas */
1861
1862        com.jcorporate.expresso.kernel.InstallLog installLog =
1863                new com.jcorporate.expresso.kernel.ConsoleInstallLog();
1864
1865        System.out.println("Creating tables...");
1866        createTables(installLog, allSchemas, dbName);
1867        System.out.println("Comaring tables...");
1868        compareTables(installLog, allSchemas, dbName);
1869        System.out.println("Setting up security...");
1870        setupSecurity(installLog, allSchemas, dbName);
1871        System.out.println("Populating default values...");
1872        populateTables(installLog, allSchemas, dbName);
1873        System.out.println("Other setup functions...");
1874        otherSetups(installLog, allSchemas, dbName);
1875        Setup.setTableExists(dbName);
1876        ConfigManager.initializeAllDBObjects();
1877        System.out.println("\nAll setups complete");
1878    } /* setup(String) */
1879
1880
1881    /**
1882     * Instantiate & load all Schema objects that we know about,
1883     * get a list of their DBObjects, and call the verify() method
1884     * of each DBObject
1885     */

1886    private static void testAllSchemas()
1887            throws DBException {
1888        System.out.println("Begin schema tests:" +
1889                DateTime.getDateTimeString());
1890
1891        Vector JavaDoc allSchemas = new Vector JavaDoc(5);
1892        {
1893            ExpressoSchema jcs = new ExpressoSchema();
1894            allSchemas.addElement(jcs);
1895
1896            SchemaList sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
1897
1898
1899            List list = sl.searchAndRetrieveList();
1900            for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
1901                SchemaList oneSchema = (SchemaList) iterator.next();
1902
1903                Schema mySchema2 = SchemaFactory.getInstance().getSchema(oneSchema.getField("SchemaClass"));
1904                if (mySchema2 != null) {
1905                    allSchemas.addElement(mySchema2);
1906                }
1907            }
1908        }
1909
1910        System.out.println("Loaded " + allSchemas.size() + " schema objects.");
1911
1912        Schema thisSchema = null;
1913
1914        for (Enumeration JavaDoc als = allSchemas.elements(); als.hasMoreElements();) {
1915            thisSchema = (Schema) als.nextElement();
1916            System.out.println("Verifying Schema " +
1917                    thisSchema.getClass().getName());
1918
1919            DBObject oneObject = null;
1920
1921            for (Enumeration JavaDoc dbo = thisSchema.getMembers();
1922                 dbo.hasMoreElements();) {
1923                oneObject = (DBObject) dbo.nextElement();
1924                System.out.println("Verifying database object " +
1925                        oneObject.getJDBCMetaData().getName() + " (" +
1926                        oneObject.getJDBCMetaData().getDescription() + ")");
1927
1928                //oneObject.setConnection(myConnection);
1929
try {
1930                    oneObject.verify();
1931                } catch (DBException de) {
1932                    System.out.println("Error in object " +
1933                            oneObject.getJDBCMetaData().getName() + ":" +
1934                            de.getMessage());
1935                    de.printStackTrace();
1936                }
1937            } /* for each database object */
1938
1939        } /* for each schema in the list */
1940
1941
1942        System.out.println("End schema tests:" + DateTime.getDateTimeString());
1943    } /* testAllSchemas(DBConnection) */
1944
1945
1946    /**
1947     * Show the user a usage message
1948     */

1949    private static void usage() {
1950        System.out.println("Usage: DBTool configDir=directory " +
1951                "webAppDir=webdir [logDir=directory] [logConfig=file] [db=dbname] [arg=value] ... ");
1952        System.out.println("Where 'directory' is the directory containing " +
1953                "the expresso configuration files (if any)");
1954        System.out.println("\tand webdir is the directory in which this web " +
1955                "application is installed, if used as a web-application");
1956        System.out.println("\tand dbname is the name of the db/context to use " +
1957                "- 'default' is used if no dbname argument is specified");
1958        System.out.println(" ");
1959        System.out.println("Optional arguments:");
1960        System.out.println("\tsetup=yes: Initial system setup");
1961        System.out.println("\tconfig=yes: Enter/edit Setup/configuration " +
1962                "values");
1963        System.out.println("\ttest=yes: Invoke test mode");
1964        System.out.println("\tgenerate=dbobjname: Generate database object " +
1965                "source code from named table in the database. Use 'all' to " +
1966                "generate source code for every table in the database.");
1967        System.out.println("\tschemaPattern=schema pattern string: Add a " +
1968                "schema pattern using JDBC wildcards to match SQL schemas. Only " +
1969                "applicable when used with generate=all. Omit if you want all tables in all schemas.");
1970        System.out.println("\ttableNamePattern=table name pattern String: Add a " +
1971                "pattern using JDBC wildcards to match table names. Only applicable " +
1972                "when used with generate=all. Omit if you want all tables in all tables.");
1973        System.out.println("\timport=dbobjname: Import data into named database" +
1974                " object, use 'all' to import into all known database objects " +
1975                "for which files exist.");
1976        System.out.println("\tfile=filename: File name to import from/export " +
1977                "to. Not required if 'all' is used for the import parameter.");
1978        System.out.println("\tformat=formatCode: Format for import/export. " +
1979                "Options are xml, tab");
1980        System.out.println("\tgen_package=com.whatever: package name for generated" +
1981                " java files. Only applicable when generating.");
1982
1983        System.out.println("\tbench=yes: Run benchmarks");
1984        System.exit(1);
1985    } /* usage() */
1986
1987    /**
1988     * Create the tables required by the database objects in the list
1989     * of schemas.
1990     * Each database object knows how to create the database table it
1991     * requires - this
1992     * method goes through the list
1993     * of registered schemas and calls the create method for all of the
1994     * database objects in the schema. If the table is already there,
1995     * nothing is done.
1996     *
1997     * @param theLog The installLog object. Use ConsoleInstallLog if you
1998     * don't know what this does.
1999     * @param allSchemas List of the schema objects
2000     * @param dataContext The database context to create the database in.
2001     * @throws DBException If there is a problem creating the tables
2002     */

2003    public static synchronized void createTables(InstallLog theLog,
2004                                                 Vector JavaDoc allSchemas,
2005                                                 String JavaDoc dataContext)
2006            throws DBException {
2007
2008        theLog.info(Messages.getString("Creating_Tables_for_databa") + " '" + dataContext + "'");
2009        TableCreator tc = TableCreator.getInstance();
2010        for (Enumeration JavaDoc e = allSchemas.elements(); e.hasMoreElements();) {
2011            Schema oneSchema = (Schema) e.nextElement();
2012            Vector JavaDoc v = tc.createAsNeeded(oneSchema, dataContext);
2013
2014            if (v.size() > 0) {
2015                String JavaDoc oneTableName = null;
2016
2017                for (Enumeration JavaDoc et = v.elements(); et.hasMoreElements();) {
2018                    oneTableName = (String JavaDoc) et.nextElement();
2019
2020                    theLog.info(Messages.getString("Created_table_") + " " +
2021                            oneTableName);
2022                }
2023
2024                theLog.info("Schema " + oneSchema.getClass().getName() +
2025                        " " +
2026                        Messages.getString("__Created_") +
2027                        " " + v.size() + " " +
2028                        Messages.getString("_tables_in_database"));
2029            } else {
2030                theLog.info(Messages.getString("Schema_") + " " +
2031                        oneSchema.getClass().getName() +
2032                        " " +
2033                        Messages.getString("_Tables_are_all_already_in"));
2034            }
2035
2036            DBConnectionPool.reInitialize();
2037        } /* for each schema */
2038
2039    } /* createTables(PrintWriter, Vector, String) */
2040
2041
2042    /**
2043     * Method to perform any other additonal setup required by each
2044     * schema
2045     *
2046     * @param theLog InstallLog object to save the data to
2047     * @param allSchemas List of the schema objects
2048     * @param dbName The database context to create the database in.
2049     * @throws DBException If there is a database problem creating
2050     * the new default values
2051     */

2052    public static synchronized void otherSetups(InstallLog theLog, Vector JavaDoc allSchemas,
2053                                                String JavaDoc dbName)
2054            throws DBException {
2055        Schema oneSchema = null;
2056
2057        for (Enumeration JavaDoc e = allSchemas.elements(); e.hasMoreElements();) {
2058            oneSchema = (Schema) e.nextElement();
2059
2060            theLog.info(Messages.getString("Additional_setup_on_") + " " +
2061                    oneSchema.getClass().getName());
2062
2063            oneSchema.otherSetup(theLog, dbName);
2064
2065            /*
2066             call to Schema.otherSetup(String) until that method is removed after deprecation.
2067             This otherSetup(String)
2068            was previously called indirectly by a deprecated method, now removed.
2069            The problem is that Schema.otherSetup(String) was not itself
2070            deprecated previously (it now is), so end users did not have a
2071            notification to move away in previous releases.
2072            */

2073            oneSchema.otherSetup(dbName);
2074        }
2075
2076
2077        theLog.info(Messages.getString("All_Additional_Setup_funct"));
2078        System.gc();
2079    } /* otherSetups(PrintWriter, Vector, String) */
2080
2081
2082    /**
2083     * This method goes through the schemas and populates tables with default values
2084     * if they do not exist. Works closely with
2085     *
2086     * @param installLog The InstallLog to save the output traces to
2087     * @param allSchemas List of the schema objects
2088     * @param dbName The database context to create the database in.
2089     * @throws DBException If a problem occurrs putting the default records
2090     * in the database
2091     */

2092    public static synchronized void populateTables(InstallLog installLog,
2093                                                   Vector JavaDoc allSchemas,
2094                                                   String JavaDoc dbName)
2095            throws DBException {
2096        Schema oneSchema = null;
2097        Vector JavaDoc errors = new Vector JavaDoc();
2098
2099        for (Enumeration JavaDoc e = allSchemas.elements(); e.hasMoreElements();) {
2100            oneSchema = (Schema) e.nextElement();
2101
2102            installLog.info("Populate Tables on " + oneSchema.getClass().getName());
2103            try {
2104                oneSchema.setupDefaultValuesWithException(dbName);
2105            } catch (DBException de) {
2106                log.error(de);
2107                de.printStackTrace(System.err);
2108                errors.addElement(de);
2109            }
2110
2111            installLog.info("Adding Default Cache Settings on " +
2112                    oneSchema.getClass().getName());
2113            //
2114
//Setup cache settings for all the dbobjects.
2115
//
2116
DBObjLimit cacheSettings = new DBObjLimit(Securable.SYSTEM_ACCOUNT);
2117            cacheSettings.setDataContext(dbName);
2118            for (Enumeration JavaDoc dbobjects = oneSchema.getMembers(); dbobjects.hasMoreElements();) {
2119                DBObject oneObj = (DBObject) dbobjects.nextElement();
2120                cacheSettings.setField("DBObjectName", oneObj.getClass().getName());
2121                cacheSettings.setField("PageLimit", 50);
2122                cacheSettings.setField("CacheSize", 50);
2123                cacheSettings.setField("TTL", 10);
2124                cacheSettings.addIfNeeded();
2125            }
2126        }
2127
2128
2129        if (errors.size() > 0) {
2130            installLog.warn("" + errors.size() +
2131                    " error(s) were encountered when populating defaults:");
2132
2133            Throwable JavaDoc oneException = null;
2134
2135            for (Enumeration JavaDoc ee = errors.elements(); ee.hasMoreElements();) {
2136                oneException = (Throwable JavaDoc) ee.nextElement();
2137                installLog.error("Populate Default Error", oneException);
2138            }
2139        }
2140        installLog.info("All Additional Table Populations have been performed.");
2141
2142        setupConfig(installLog, allSchemas, dbName);
2143    } /* populateTables(PrintWriter, Vector, String) */
2144
2145
2146    /**
2147     * Method to set up the default Setup values for each schema.
2148     * Every schema object has a list of the Setup values and default
2149     * values for them that are required by the application that the
2150     * schema applies to. The default schema is done first, then
2151     * any other registered schema objects
2152     *
2153     * @param installLog - The installation log to log output to
2154     * @param allSchemas A list of all of the schema objects
2155     * @param dbName The database context to setup the config in.
2156     * @throws DBException If there is a database problem creating
2157     * the new default values
2158     */

2159    public static synchronized void setupConfig(InstallLog installLog, Vector JavaDoc allSchemas,
2160                                                String JavaDoc dbName)
2161            throws DBException {
2162        Schema oneSchema = null;
2163        Setup oneSetup = null;
2164        Setup findSetup = null;
2165
2166        for (Enumeration JavaDoc e = allSchemas.elements(); e.hasMoreElements();) {
2167            oneSchema = (Schema) e.nextElement();
2168
2169            for (Enumeration JavaDoc rl = oneSchema.getConfig().elements();
2170                 rl.hasMoreElements();) {
2171                oneSetup = (Setup) rl.nextElement();
2172                oneSetup.setDataContext(dbName);
2173                findSetup = new Setup();
2174                findSetup.setDataContext(dbName);
2175                findSetup.clear();
2176                findSetup.setField("SetupCode", oneSetup.getField("SetupCode"));
2177                findSetup.setField("SchemaClass",
2178                        oneSetup.getField("SchemaClass"));
2179
2180                if (!findSetup.find()) {
2181                    oneSetup.setDataContext(dbName);
2182                    oneSetup.add();
2183
2184                    installLog.info(Messages.getString("Added_default_config_") + " " +
2185                            Messages.getString("value_for_") +
2186                            " " +
2187                            oneSetup.getField("SetupCode"));
2188                }
2189            }
2190        }
2191        installLog.info(Messages.getString("All_Setup/Configuration_Va") + " " + Messages.getString("are_set_up."));
2192
2193        Setup.setTableExists(dbName);
2194        System.gc();
2195    } /* setupConfig(PrintWriter, Vector, String) */
2196
2197
2198    /**
2199     * This method creates default security entries for all of the
2200     * database objects and controller objects for the known schemas.
2201     * This includes full access for a group and user called User.ADMIN_USER
2202     *
2203     * @param theLog Installation Log
2204     * @param allSchemas List of the schema objects
2205     * @param dbName The database context to create the database in.
2206     * @throws DBException If a problem occurrs putting the security info
2207     * in the database
2208     */

2209    public static synchronized void setupSecurity(InstallLog theLog,
2210                                                  Vector JavaDoc allSchemas,
2211                                                  String JavaDoc dbName)
2212            throws DBException {
2213        /* Group 'Everybody' */
2214        UserGroup oneGroup = new UserGroup();
2215        oneGroup.setDataContext(dbName);
2216        oneGroup.setGroupName(UserGroup.ALL_USERS_GROUP);
2217
2218        if (!oneGroup.find()) {
2219            oneGroup.setField(UserGroup.GROUP_DESCRIPTION, Messages.getString("All_Users"));
2220            oneGroup.add();
2221        }
2222
2223        /* Group 'Nobody' */
2224        oneGroup.clear();
2225        oneGroup.setGroupName(UserGroup.UNKNOWN_USERS_GROUP);
2226        if (!oneGroup.find()) {
2227            oneGroup.setField(UserGroup.GROUP_DESCRIPTION, Messages.getString("Unknown_Users"));
2228            oneGroup.add();
2229        }
2230
2231        /* Group 'NotReg' */
2232        oneGroup.clear();
2233        oneGroup.setGroupName(UserGroup.NOT_REG_USERS_GROUP);
2234
2235        if (!oneGroup.find()) {
2236            oneGroup.setField(UserGroup.GROUP_DESCRIPTION, Messages.getString("NotReg_Users"));
2237            oneGroup.add();
2238        }
2239
2240        /* Group 'Admin' */
2241        oneGroup.clear();
2242        oneGroup.setGroupName(UserGroup.ADMIN_GROUP);
2243        if (!oneGroup.find()) {
2244            oneGroup.setField(UserGroup.GROUP_DESCRIPTION,
2245                    Messages.getString("Administrative_Users"));
2246            oneGroup.add();
2247
2248            theLog.info(Messages.getString("Added_'Admin'_user_group") + " ");
2249        }
2250
2251        //
2252
//Now create the registration domains.
2253
//
2254
RegistrationDomain rd = new RegistrationDomain();
2255        rd.setDataContext(dbName);
2256        rd.setField("Name", "default");
2257
2258        if (!rd.find()) {
2259            rd.setField("Description", "Default Registration Domain");
2260            rd.setField("RegRequired", "Y");
2261            rd.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2262            rd.setField("ControllerClass",
2263                    com.jcorporate.expresso.services.controller.SimpleRegistration.class.getName());
2264            rd.setField("RegRequired", "N");
2265            rd.setField("Approve", "N");
2266            rd.setField("UserPasswd", "Y");
2267            rd.setField("EmailValidate", "N");
2268            rd.setField("EmailAsLogin", "N");
2269            rd.add();
2270        }
2271
2272        RegistrationObjectMap rdm = new RegistrationObjectMap();
2273        rdm.setDataContext(dbName);
2274        rdm.setField("RegDomId", rd.getField("RegDomId"));
2275        rdm.setField("RegObj",
2276                com.jcorporate.expresso.ext.dbobj.RegisteredUser.class.getName());
2277
2278        if (!rdm.find()) {
2279            rdm.setField("UidField", "ExpUid");
2280            rdm.setField("RecMin", "1");
2281            rdm.setField("RecMax", "1");
2282            rdm.setField("AllowEdit", "Y");
2283            rdm.setField("AllowDel", "N");
2284            rdm.setField("RegFields",
2285                    "!IsActive" + ",!UserName" + ",!InternalComment" +
2286                    ",!AddedOn" + ",!UpdatedOn" + ",!URL" +
2287                    ",!EmailPrivate" + ",!Occupation" + ",!Location" +
2288                    ",!Expertise" + ",!OtherProjects" +
2289                    ",!Contributions" + ",!Phone" + ",!Testimonial" +
2290                    ",!IPAddress");
2291            rdm.add();
2292        }
2293
2294        rd.clear();
2295        rd.setField("Name", "extended");
2296
2297        if (!rd.find()) {
2298            rd.setField("Description", "Extended Registration Domain");
2299            rd.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2300            rd.setField("ControllerClass",
2301                    com.jcorporate.expresso.services.controller.Registration.class.getName());
2302            rd.setField("RegRequired", "Y");
2303            rd.setField("Approve", "N");
2304            rd.setField("UserPasswd", "Y");
2305            rd.setField("EmailValidate", "Y");
2306            rd.setField("EmailAsLogin", "N");
2307            rd.add();
2308        }
2309
2310        rdm.clear();
2311        rdm.setField("RegDomId", rd.getField("RegDomId"));
2312        rdm.setField("RegObj",
2313                com.jcorporate.expresso.ext.dbobj.regobj.Person.class.getName());
2314
2315        if (!rdm.find()) {
2316            rdm.setField("UidField", "ExpUid");
2317            rdm.setField("RecMin", "1");
2318            rdm.setField("RecMax", "1");
2319            rdm.setField("AllowEdit", "Y");
2320            rdm.setField("AllowDel", "N");
2321            rdm.setField("RegFields", "!ExpUid,!AddedOn,!UpdatedOn");
2322            rdm.add();
2323        }
2324
2325        rdm.clear();
2326        rdm.setField("RegDomId", rd.getField("RegDomId"));
2327        rdm.setField("RegObj",
2328                com.jcorporate.expresso.ext.dbobj.regobj.Phone.class.getName());
2329
2330        if (!rdm.find()) {
2331            rdm.setField("UidField", "ExpUid");
2332            rdm.setField("RecMin", "1");
2333            rdm.setField("RecMax", "0");
2334            rdm.setField("AllowEdit", "Y");
2335            rdm.setField("AllowDel", "N");
2336            rdm.setField("RegFields",
2337                    "!PhoneId,!ExpUid,!AddedOn,!UpdatedOn,+Type");
2338            rdm.add();
2339        }
2340
2341        rdm.clear();
2342        rdm.setField("RegDomId", rd.getField("RegDomId"));
2343        rdm.setField("RegObj",
2344                com.jcorporate.expresso.ext.dbobj.regobj.Address.class.getName());
2345
2346        if (!rdm.find()) {
2347            rdm.setField("UidField", "ExpUid");
2348            rdm.setField("RecMin", "1");
2349            rdm.setField("RecMax", "1");
2350            rdm.setField("AllowEdit", "Y");
2351            rdm.setField("AllowDel", "N");
2352            rdm.setField("RegFields", "!AddressId,!ExpUid,!AddedOn,!UpdatedOn");
2353            rdm.add();
2354        }
2355
2356        rdm.clear();
2357        rdm.setField("RegDomId", rd.getField("RegDomId"));
2358        rdm.setField("RegObj",
2359                com.jcorporate.expresso.ext.dbobj.regobj.Contact.class.getName());
2360
2361        if (!rdm.find()) {
2362            rdm.setField("UidField", "ExpUid");
2363            rdm.setField("RecMin", "0");
2364            rdm.setField("RecMax", "0");
2365            rdm.setField("AllowEdit", "Y");
2366            rdm.setField("AllowDel", "N");
2367            rdm.setField("RegFields",
2368                    "!ContactId,!ExpUid,!AddedOn,!UpdatedOn,+Type");
2369            rdm.add();
2370        }
2371
2372        //
2373
//Add the default users to the system
2374
//
2375
User oneUser = new User();
2376        oneUser.setDataContext(dbName);
2377        oneUser.setLoginName("Anonymous"); //$NON-NLS-2$//$NON-NLS-1$
2378

2379        if (!oneUser.find()) {
2380            oneUser.setDisplayName(Messages.getString("Anonymous_User"));
2381            oneUser.setEmail("none"); //$NON-NLS-2$//$NON-NLS-1$
2382
oneUser.setAccountStatus("D");
2383            oneUser.add();
2384
2385
2386            theLog.info(Messages.getString("Added_'Anonymous'_user") +
2387                    " ");
2388
2389            GroupMembers oneMember = new GroupMembers();
2390            oneMember.setDataContext(dbName);
2391            oneMember.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2392            oneMember.setField("ExpUid", oneUser.getUid());
2393
2394            if (!oneMember.find()) {
2395                oneMember.add();
2396
2397                theLog.info(Messages.getString("Added_'Anonymous'_user_") +
2398                        " " +
2399                        Messages.getString("to_the_group_'Everybody'"));
2400            }
2401        } /* if we didn't find the Anonymous user */
2402
2403
2404        oneUser.clear();
2405        oneUser.setLoginName(User.UNKNOWN_USER);
2406
2407        if (!oneUser.find()) {
2408            oneUser.setDisplayName(Messages.getString("Default_user_before_login"));
2409            oneUser.setEmail("none");
2410            oneUser.setAccountStatus("D");
2411            oneUser.add();
2412
2413            theLog.info(Messages.getString("Added_'NONE'_user_") +
2414                    " ");
2415        }
2416
2417        GroupMembers oneMember = new GroupMembers();
2418        oneMember.setDataContext(dbName);
2419        oneMember.setField("GroupName", UserGroup.UNKNOWN_USERS_GROUP);
2420        oneMember.setField("ExpUid", oneUser.getUid());
2421
2422        if (!oneMember.find()) {
2423            oneMember.add();
2424
2425            theLog.info(Messages.getString("Added_NONE'_user_to_the_'N") + " ");
2426        }
2427
2428        oneUser.clear();
2429        oneUser.setLoginName(User.ADMIN_USER);
2430
2431        if (!oneUser.find()) {
2432            oneUser.setDisplayName(Messages.getString("Administrative_User"));
2433            oneUser.setEmail("none");
2434            oneUser.setAccountStatus("A");
2435            oneUser.add();
2436
2437            theLog.info(Messages.getString("Added_'Admin'_user_-_SET_A") + " ");
2438        }
2439
2440        oneMember.clear();
2441        oneMember.setField("GroupName", User.ADMIN_USER);
2442        oneMember.setField("ExpUid", oneUser.getUid());
2443
2444        if (!oneMember.find()) {
2445            oneMember.add();
2446
2447            theLog.info(Messages.getString("Added_'Admin'_user_to_the_") + " ");
2448        }
2449
2450
2451        //
2452
//Set up default DBObject Security
2453
//
2454
DBObjSecurity oneSecurity = new DBObjSecurity();
2455        oneSecurity.setDataContext(dbName);
2456
2457        DBObject oneObj = null;
2458        Schema oneSchema = null;
2459
2460        for (Enumeration JavaDoc sl = allSchemas.elements(); sl.hasMoreElements();) {
2461            oneSchema = (Schema) sl.nextElement();
2462
2463            for (Enumeration JavaDoc ee = oneSchema.getMembers();
2464                 ee.hasMoreElements();) {
2465
2466                oneObj = (DBObject) ee.nextElement();
2467                oneSecurity.setField("GroupName", User.ADMIN_USER);
2468
2469                //$NON-NLS-2$//$NON-NLS-1$
2470
oneSecurity.setField("DBObjectName",
2471                        oneObj.getClass().getName());
2472
2473                //$NON-NLS-1$
2474
oneSecurity.setField("MethodCode", "A");
2475
2476                //$NON-NLS-2$//$NON-NLS-1$
2477
if (!oneSecurity.find()) {
2478                    oneSecurity.add();
2479
2480                    theLog.info(Messages.getString("Added_permission_for_") + " " +
2481                            Messages.getString("'Admin'_group_to_add_new_e") +
2482                            " " +
2483                            oneObj.getClass().getName());
2484                }
2485
2486                oneSecurity.setField("MethodCode", "U"); //$NON-NLS-2$//$NON-NLS-1$
2487

2488                if (!oneSecurity.find()) {
2489                    oneSecurity.add();
2490
2491                    theLog.info(Messages.getString("Added_permission_for_") + " " +
2492                            Messages.getString("'Admin'_group_to_update_en") +
2493                            " " +
2494                            oneObj.getClass().getName());
2495                }
2496
2497                oneSecurity.setField("MethodCode", "S"); //$NON-NLS-2$//$NON-NLS-1$
2498

2499                if (!oneSecurity.find()) {
2500                    oneSecurity.add();
2501
2502                    theLog.info(Messages.getString("Added_permission_for_") + " " +
2503                            Messages.getString("'Admin'_group_to_search_on") +
2504                            " " +
2505                            oneObj.getClass().getName());
2506                }
2507
2508                oneSecurity.setField("MethodCode", "D"); //$NON-NLS-2$//$NON-NLS-1$
2509

2510                if (!oneSecurity.find()) {
2511                    oneSecurity.add();
2512
2513                    theLog.info(Messages.getString("Added_permission_for_") + " " +
2514                            Messages.getString("'Admin'_group_to_delete_fr") +
2515                            " '" +
2516                            oneObj.getClass().getName() +
2517                            "'");
2518                }
2519            } /* for every object in the schema */
2520
2521
2522            Controller con;
2523            ControllerSecurity oneControllerSecurity = new ControllerSecurity(SecuredDBObject.SYSTEM_ACCOUNT);
2524            oneControllerSecurity.setDataContext(dbName);
2525
2526
2527            //
2528
//Setup default controller access.
2529
//
2530
for (Iterator JavaDoc et = oneSchema.getControllerList().iterator();
2531                 et.hasNext();) {
2532                con = (Controller) et.next();
2533                oneControllerSecurity.clear();
2534                oneControllerSecurity.setField("ControllerClass",
2535                        con.getClass().getName());
2536                oneControllerSecurity.setField("GroupName", User.ADMIN_USER);
2537                oneControllerSecurity.setField("States", "*");
2538
2539                if (!oneControllerSecurity.find()) {
2540                    theLog.info(Messages.getString("Adding_access_to_") + " " +
2541                            Messages.getString("all_states_of_Controller_") +
2542                            " '" +
2543                            con.getTitle() +
2544                            "'");
2545                    oneControllerSecurity.add();
2546                }
2547
2548                //
2549
//Special cases in login controller some states should be
2550
//enabled by default.
2551
//
2552
if (con instanceof com.jcorporate.expresso
2553
                        .services.controller.LoginController) {
2554                    oneControllerSecurity.clear();
2555                    oneControllerSecurity.setField("ControllerClass",
2556                            con.getClass().getName());
2557                    oneControllerSecurity.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2558                    oneControllerSecurity.setField("States", "*");
2559
2560                    if (!oneControllerSecurity.find()) {
2561                        theLog.info("Adding general access to Login controller");
2562                        oneControllerSecurity.add();
2563                    }
2564
2565                    oneControllerSecurity.clear();
2566                    oneControllerSecurity.setField("ControllerClass",
2567                            con.getClass().getName());
2568                    oneControllerSecurity.setField("GroupName", UserGroup.UNKNOWN_USERS_GROUP);
2569                    oneControllerSecurity.setField("States", "promptLogin,processLogin," +
2570                            "emailValidate,promptSendPassword,processSendPassword,processRevalidate");
2571
2572                    if (!oneControllerSecurity.find()) {
2573                        theLog.info("Adding default anonymous " +
2574                                "access to Login controller");
2575                        oneControllerSecurity.add();
2576                    }
2577
2578                } /* special case for login controller */
2579
2580                //
2581
//Special case for registration controller
2582
//
2583
if (con instanceof com.jcorporate.expresso
2584
                        .services.controller.Registration) {
2585                    oneControllerSecurity.clear();
2586                    oneControllerSecurity.setField("ControllerClass",
2587                            con.getClass().getName());
2588                    oneControllerSecurity.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2589                    oneControllerSecurity.setField("States", "showDBMenu,emailValidate," +
2590                            "promptSelfRegister,processSelfRegister,promptAddRecord," +
2591                            "processAddRecord,promptUpdateRecord," +
2592                            "processUpdateRecord,promptDeleteRecord," +
2593                            "processDeleteRecord,processListRecords,processRevalidate");
2594
2595                    if (!oneControllerSecurity.find()) {
2596                        theLog.info("Adding general " +
2597                                "access to Registration controller");
2598
2599                        oneControllerSecurity.add();
2600                    }
2601
2602                    oneControllerSecurity.clear();
2603                    oneControllerSecurity.setField("ControllerClass",
2604                            con.getClass().getName());
2605                    oneControllerSecurity.setField("GroupName", UserGroup.UNKNOWN_USERS_GROUP);
2606                    oneControllerSecurity.setField("States", "showDBMenu,emailValidate," +
2607                            "promptSelfRegister,processSelfRegister,processRevalidate");
2608
2609                    if (!oneControllerSecurity.find()) {
2610                        theLog.info("Adding default anonymous " +
2611                                "access to Registration controller");
2612
2613                        oneControllerSecurity.add();
2614                    }
2615
2616                }
2617
2618            } /* for each controller */
2619
2620
2621            StdServlet oneServlet;
2622
2623            //
2624
//Set up the servlet Security
2625
//
2626
for (Enumeration JavaDoc es = oneSchema.getServlets();
2627                 es.hasMoreElements();) {
2628                oneServlet = (StdServlet) es.nextElement();
2629                oneControllerSecurity.clear();
2630                oneControllerSecurity.setField("ControllerClass",
2631                        oneServlet.getClass().getName());
2632                oneControllerSecurity.setField("GroupName", User.ADMIN_USER);
2633
2634                //$NON-NLS-2$//$NON-NLS-1$
2635
oneControllerSecurity.setField("States", "*");
2636
2637                //$NON-NLS-2$//$NON-NLS-1$
2638
if (!oneControllerSecurity.find()) {
2639                    theLog.info(Messages.getString("Adding_access_to_") + Messages.getString("Servlet_'") +
2640                            " '" +
2641                            oneServlet.getTitle() +
2642                            "'");
2643
2644                    oneControllerSecurity.add();
2645                }
2646            } /* for each servlet */
2647
2648
2649            //
2650
//Set up the default Job security
2651
//
2652
Job j;
2653            JobSecurity oneJobSecurity = new JobSecurity(SecuredDBObject.SYSTEM_ACCOUNT); //$NON-NLS-1$
2654
oneJobSecurity.setDataContext(dbName);
2655
2656            for (Enumeration JavaDoc ej = oneSchema.getJobs(); ej.hasMoreElements();) {
2657                j = (Job) ej.nextElement();
2658                oneJobSecurity.clear();
2659                oneJobSecurity.setField("JobClass", j.getClass().getName());
2660
2661                //$NON-NLS-1$
2662
oneJobSecurity.setField("GroupName", User.ADMIN_USER);
2663
2664                //$NON-NLS-2$//$NON-NLS-1$
2665
oneJobSecurity.setField("Functions", "*");
2666
2667                //$NON-NLS-2$//$NON-NLS-1$
2668
if (!oneJobSecurity.find()) {
2669                    theLog.info(Messages.getString("Adding_access_to_") + " " +
2670                            Messages.getString("all_functions_of_Job_'") +
2671                            " '" + j.getTitle() + "'");
2672                    oneJobSecurity.add();
2673                } /* if job security not found */
2674
2675            } /* for each job*/
2676
2677        } /* for each schema */
2678
2679        theLog.info(Messages.getString("Security_Checks_Complete"));
2680    } /* setupSecurity(PrintWriter, Vector, String) */
2681
2682
2683} /* DBTool */
2684
Popular Tags