0001: /* ====================================================================
0002: * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
0003: *
0004: * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
0005: *
0006: * Redistribution and use in source and binary forms, with or without
0007: * modification, are permitted provided that the following conditions
0008: * are met:
0009: *
0010: * 1. Redistributions of source code must retain the above copyright
0011: * notice, this list of conditions and the following disclaimer.
0012: *
0013: * 2. Redistributions in binary form must reproduce the above copyright
0014: * notice, this list of conditions and the following disclaimer in
0015: * the documentation and/or other materials provided with the
0016: * distribution.
0017: *
0018: * 3. The end-user documentation included with the redistribution,
0019: * if any, must include the following acknowledgment:
0020: * "This product includes software developed by Jcorporate Ltd.
0021: * (http://www.jcorporate.com/)."
0022: * Alternately, this acknowledgment may appear in the software itself,
0023: * if and wherever such third-party acknowledgments normally appear.
0024: *
0025: * 4. "Jcorporate" and product names such as "Expresso" must
0026: * not be used to endorse or promote products derived from this
0027: * software without prior written permission. For written permission,
0028: * please contact info@jcorporate.com.
0029: *
0030: * 5. Products derived from this software may not be called "Expresso",
0031: * or other Jcorporate product names; nor may "Expresso" or other
0032: * Jcorporate product names appear in their name, without prior
0033: * written permission of Jcorporate Ltd.
0034: *
0035: * 6. No product derived from this software may compete in the same
0036: * market space, i.e. framework, without prior written permission
0037: * of Jcorporate Ltd. For written permission, please contact
0038: * partners@jcorporate.com.
0039: *
0040: * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
0041: * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
0042: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
0043: * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
0044: * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
0045: * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
0046: * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
0047: * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
0048: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
0049: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
0050: * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
0051: * SUCH DAMAGE.
0052: * ====================================================================
0053: *
0054: * This software consists of voluntary contributions made by many
0055: * individuals on behalf of the Jcorporate Ltd. Contributions back
0056: * to the project(s) are encouraged when you make modifications.
0057: * Please send them to support@jcorporate.com. For more information
0058: * on Jcorporate Ltd. and its products, please see
0059: * <http://www.jcorporate.com/>.
0060: *
0061: * Portions of this software are based upon other open source
0062: * products and are subject to their respective licenses.
0063: */
0064: package com.jcorporate.expresso.core.utility;
0065:
0066: import com.jcorporate.expresso.core.ExpressoSchema;
0067: import com.jcorporate.expresso.core.controller.Controller;
0068: import com.jcorporate.expresso.core.dataobjects.Securable;
0069: import com.jcorporate.expresso.core.db.DBConnection;
0070: import com.jcorporate.expresso.core.db.DBConnectionPool;
0071: import com.jcorporate.expresso.core.db.DBException;
0072: import com.jcorporate.expresso.core.db.TableCreator;
0073: import com.jcorporate.expresso.core.db.TypeMapper;
0074: import com.jcorporate.expresso.core.dbobj.DBObject;
0075: import com.jcorporate.expresso.core.dbobj.Schema;
0076: import com.jcorporate.expresso.core.dbobj.SchemaFactory;
0077: import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
0078: import com.jcorporate.expresso.core.i18n.Messages;
0079: import com.jcorporate.expresso.core.job.Job;
0080: import com.jcorporate.expresso.core.job.ServerException;
0081: import com.jcorporate.expresso.core.misc.ConfigManager;
0082: import com.jcorporate.expresso.core.misc.ConfigurationException;
0083: import com.jcorporate.expresso.core.misc.DateTime;
0084: import com.jcorporate.expresso.core.misc.StringUtil;
0085: import com.jcorporate.expresso.core.registry.MutableRequestRegistry;
0086: import com.jcorporate.expresso.core.security.SuperUser;
0087: import com.jcorporate.expresso.core.security.User;
0088: import com.jcorporate.expresso.core.servlet.StdServlet;
0089: import com.jcorporate.expresso.kernel.InstallLog;
0090: import com.jcorporate.expresso.kernel.LogManager;
0091: import com.jcorporate.expresso.services.dbobj.ControllerSecurity;
0092: import com.jcorporate.expresso.services.dbobj.DBObjLimit;
0093: import com.jcorporate.expresso.services.dbobj.DBObjSecurity;
0094: import com.jcorporate.expresso.services.dbobj.DefaultUserInfo;
0095: import com.jcorporate.expresso.services.dbobj.Event;
0096: import com.jcorporate.expresso.services.dbobj.GroupMembers;
0097: import com.jcorporate.expresso.services.dbobj.JobSecurity;
0098: import com.jcorporate.expresso.services.dbobj.RegistrationDomain;
0099: import com.jcorporate.expresso.services.dbobj.RegistrationObjectMap;
0100: import com.jcorporate.expresso.services.dbobj.SchemaList;
0101: import com.jcorporate.expresso.services.dbobj.Setup;
0102: import com.jcorporate.expresso.services.dbobj.UserGroup;
0103: import com.jcorporate.expresso.services.html.HtmlException;
0104: import com.jcorporate.expresso.services.html.Page;
0105: import com.jcorporate.expresso.services.html.Paragraph;
0106: import com.jcorporate.expresso.services.html.Text;
0107: import org.apache.log4j.Logger;
0108:
0109: import java.io.BufferedInputStream;
0110: import java.io.BufferedOutputStream;
0111: import java.io.BufferedReader;
0112: import java.io.File;
0113: import java.io.FileInputStream;
0114: import java.io.FileOutputStream;
0115: import java.io.IOException;
0116: import java.io.InputStreamReader;
0117: import java.io.PrintStream;
0118: import java.sql.Connection;
0119: import java.sql.DatabaseMetaData;
0120: import java.sql.DriverManager;
0121: import java.sql.ResultSet;
0122: import java.sql.SQLException;
0123: import java.util.ArrayList;
0124: import java.util.Date;
0125: import java.util.Enumeration;
0126: import java.util.Hashtable;
0127: import java.util.Iterator;
0128: import java.util.List;
0129: import java.util.StringTokenizer;
0130: import java.util.Vector;
0131:
0132: /**
0133: * DBTool is a multi-purpose tool for working with database objects. It can:
0134: * <ol>
0135: * <li>Verify data in the database with respect to referential integrity</li>
0136: * <li>Generate the code for a Database Object by reading the data in a
0137: * database</li>
0138: * <li>Export data in a database object to an external XML file</li>
0139: * <li>Import data from an external XML file into a database object</li>
0140: * </ol>
0141: * <p/>
0142: * <h4>Command Line Parameters</h4>
0143: * <h5 align="left">Required Command Line Arguments </h5>
0144: * <p align="left"><b>configDir</b> - <Directory that contains your config files></p>
0145: * <p align="left"><b>webbAppDir</b> -<The Expresso webapp directory></p>
0146: * <p align="left"><b>db=</b><The database to create></p>
0147: * <h5 align="left">Optional Command Line Argumments</h5>
0148: * <p align="left">These arguments define the role to use as well as some arguments
0149: * are specific for a given task. </p>
0150: * <ul>
0151: * <li><b>setup</b> - Setup the database schema</li>
0152: * <li><b>pooltest</b> - Stress Test the Connection Pool</li>
0153: * <li><b>test</b> - @todo document</li>
0154: * <li><b>generate</b> - Generate DBObjects given an active database with tables.</li>
0155: * <li><b>gen_package</b> generate dbobject with this package name.</li>
0156: * <li><b>import</b> - import DBObjects.</li>
0157: * <li><b>export</b> - export DBObjects.
0158: * <br />file - The file to import or export to
0159: * <br />format - Either tab or comma, or XML file format.</li>
0160: * <li><b>passwords</b> - @todo Document</li>
0161: * <li><b>bench</b> - Run some basic benchmarks.</li>
0162: * <li><b>config</b> - Run configuration utility.</li>
0163: * <li><b>nameChange</b> - Update packages to latest package format.</li>
0164: * <li><b>uidChange</b> -Convert your database to integer- keyed index for users .</li>
0165: * </ul>
0166: *
0167: * @author Michael Nash
0168: * <p/>
0169: * Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
0170: */
0171: public class DBTool extends Thread {
0172: private static final String this Class = DBTool.class.getName();
0173: private static String dbName = null;
0174: private static Logger log = Logger.getLogger(DBTool.class);
0175:
0176: /**
0177: * Constructor
0178: */
0179: public DBTool() {
0180: } /* DBTool() */
0181:
0182: /**
0183: * Choose a schema to enter Setup values for
0184: *
0185: * @param dbName The data context to work with
0186: */
0187: private static void chooseConfig(String dbName) throws DBException,
0188: IOException {
0189: System.out.println("Choose Schema: (Database " + dbName + ")");
0190:
0191: Hashtable choices = new Hashtable();
0192: choices.put("1",
0193: "Expresso|com.jcorporate.expresso.core.ExpressoSchema");
0194:
0195: int nextNum = 1;
0196: SchemaList sl = new SchemaList();
0197: sl.setDataContext(dbName);
0198:
0199: String nextKey = null;
0200:
0201: List list = sl.searchAndRetrieveList();
0202: for (Iterator iterator = list.iterator(); iterator.hasNext();) {
0203: SchemaList oneSchemaList = (SchemaList) iterator.next();
0204: nextNum++;
0205: nextKey = "" + nextNum;
0206: choices.put(nextKey, oneSchemaList.getField("Descrip")
0207: + "|" + oneSchemaList.getField("SchemaClass"));
0208: }
0209:
0210: /* Now present the menu */
0211: String oneNumber = null;
0212: String oneDescrip = null;
0213:
0214: for (Enumeration ex = choices.keys(); ex.hasMoreElements();) {
0215: oneNumber = (String) ex.nextElement();
0216:
0217: StringTokenizer stk = new StringTokenizer((String) choices
0218: .get(oneNumber), "|");
0219: oneDescrip = stk.nextToken();
0220: System.out.println(oneNumber + ". " + oneDescrip);
0221: }
0222:
0223: System.out.println("");
0224: System.out
0225: .print("Enter the number corresponding to the schema that "
0226: + "you wish to enter/edit Setup values for:");
0227:
0228: BufferedReader br = new BufferedReader(new InputStreamReader(
0229: System.in));
0230: String command = StringUtil.notNull(br.readLine());
0231:
0232: if (command.equals("")) {
0233: return;
0234: } else {
0235: StringTokenizer stk2 = new StringTokenizer((String) choices
0236: .get(command), "|");
0237: stk2.nextToken();
0238: enterConfig(dbName, stk2.nextToken());
0239: }
0240: } /* chooseConfig(String) */
0241:
0242: /**
0243: * Benchmark the data connection
0244: */
0245: private static void doBenchMarks() throws DBException,
0246: SQLException, ConfigurationException {
0247: System.out.println("Benchmarks begin at "
0248: + DateTime.getDateTimeString());
0249:
0250: int retryCount = 5000;
0251: System.out
0252: .println("This benchmark tests the performance of the "
0253: + "connection pool in simple \n"
0254: + " allocations of connections - it makes & releases "
0255: + retryCount + " connections, 5 at a time.\n");
0256: System.out.println("Begin connection pool tests:"
0257: + DateTime.getDateTimeString());
0258:
0259: DBConnectionPool myPool = DBConnectionPool
0260: .getInstance("default");
0261:
0262: for (int i = 0; i <= retryCount; i++) {
0263: DBConnection conn1 = myPool
0264: .getConnection("Test " + (i + 1));
0265: DBConnection conn2 = myPool
0266: .getConnection("Test " + (i + 2));
0267: DBConnection conn3 = myPool
0268: .getConnection("Test " + (i + 4));
0269: DBConnection conn4 = myPool
0270: .getConnection("Test " + (i + 5));
0271: DBConnection conn5 = myPool
0272: .getConnection("Test " + (i + 6));
0273: myPool.release(conn1);
0274: myPool.release(conn2);
0275: myPool.release(conn3);
0276: myPool.release(conn4);
0277: myPool.release(conn5);
0278: }
0279:
0280: System.out.println("End connection pool tests:"
0281: + DateTime.getDateTimeString());
0282: System.out
0283: .println("Compare this to making & breaking the connection "
0284: + "to the DB the same number\n" + " of times.");
0285:
0286: String dbURL = ConfigManager.getJdbcRequired("default")
0287: .getUrl();
0288: String dbLogin = ConfigManager.getJdbcRequired("default")
0289: .getLogin();
0290: String dbPassword = ConfigManager.getJdbcRequired("default")
0291: .getPassword();
0292: System.out.println("Begin direct connection tests:"
0293: + DateTime.getDateTimeString());
0294:
0295: for (int i = 0; i <= retryCount; i++) {
0296: Connection conn1 = DriverManager.getConnection(dbURL,
0297: dbLogin, dbPassword);
0298: conn1.createStatement();
0299: conn1.close();
0300:
0301: Connection conn2 = DriverManager.getConnection(dbURL,
0302: dbLogin, dbPassword);
0303: conn2.createStatement();
0304: conn2.close();
0305:
0306: Connection conn3 = DriverManager.getConnection(dbURL,
0307: dbLogin, dbPassword);
0308: conn3.createStatement();
0309: conn3.close();
0310:
0311: Connection conn4 = DriverManager.getConnection(dbURL,
0312: dbLogin, dbPassword);
0313: conn4.createStatement();
0314: conn4.close();
0315:
0316: Connection conn5 = DriverManager.getConnection(dbURL,
0317: dbLogin, dbPassword);
0318: conn5.createStatement();
0319: conn5.close();
0320: }
0321:
0322: System.out.println("End direct connection tests:"
0323: + DateTime.getDateTimeString());
0324: System.out
0325: .println("Direct SQL tests - the above test is repeated, "
0326: + "but with a series of simple \n"
0327: + " SQL queries executed in each of the connections.");
0328: System.out.println("Begin direct SQL tests:"
0329: + DateTime.getDateTimeString());
0330:
0331: for (int i = 0; i <= retryCount; i++) {
0332: DBConnection conn1 = myPool
0333: .getConnection("Test " + (i + 1));
0334: conn1
0335: .execute("SELECT * FROM USERLOGIN WHERE UserName = 'Admin'");
0336:
0337: DBConnection conn2 = myPool
0338: .getConnection("Test " + (i + 2));
0339: conn2
0340: .execute("SELECT * FROM GROUPMEMBERS WHERE UserName = 'Admin'");
0341:
0342: DBConnection conn3 = myPool
0343: .getConnection("Test " + (i + 4));
0344: conn3
0345: .execute("SELECT * FROM SETUP WHERE SetupCode = 'ServletEvent'");
0346:
0347: DBConnection conn4 = myPool
0348: .getConnection("Test " + (i + 5));
0349: conn4
0350: .execute("SELECT * FROM DBOBJSECURITY WHERE GroupName = 'Admin'");
0351:
0352: DBConnection conn5 = myPool
0353: .getConnection("Test " + (i + 6));
0354: conn5
0355: .execute("SELECT * FROM EVENT WHERE Event = 'SYSERROR'");
0356: myPool.release(conn1);
0357: myPool.release(conn2);
0358: myPool.release(conn3);
0359: myPool.release(conn4);
0360: myPool.release(conn5);
0361: }
0362:
0363: System.out.println("End direct SQL tests:"
0364: + DateTime.getDateTimeString());
0365: System.out
0366: .println("DB Object tests - the above test is repeated, "
0367: + "but with db objects \n"
0368: + " doing the queries rather than direct sql");
0369: System.out.println("Begin db object tests:"
0370: + DateTime.getDateTimeString());
0371:
0372: GroupMembers gm = new GroupMembers();
0373: DefaultUserInfo oneUser = new DefaultUserInfo();
0374: Setup s1 = new Setup();
0375: DBObjSecurity dbo = new DBObjSecurity();
0376: Event e = new Event();
0377:
0378: for (int i = 0; i <= retryCount; i++) {
0379: DBConnection conn1 = myPool
0380: .getConnection("Test " + (i + 1));
0381: oneUser.setConnection(conn1);
0382: oneUser.setField("UserName", User.ADMIN_USER);
0383: oneUser.find();
0384:
0385: DBConnection conn2 = myPool
0386: .getConnection("Test " + (i + 2));
0387: gm.setConnection(conn2);
0388: gm.setField("UserName", User.ADMIN_USER);
0389: gm.find();
0390:
0391: DBConnection conn3 = myPool
0392: .getConnection("Test " + (i + 4));
0393: s1.setConnection(conn3);
0394: s1.setField("SetupCode", "ServletEvent");
0395: s1.find();
0396:
0397: DBConnection conn4 = myPool
0398: .getConnection("Test " + (i + 5));
0399: dbo.setConnection(conn4);
0400: dbo.setField("GroupName", User.ADMIN_USER);
0401: dbo.find();
0402:
0403: DBConnection conn5 = myPool
0404: .getConnection("Test " + (i + 6));
0405: e.setConnection(conn5);
0406: e.setField("Event", "SYSERROR");
0407: e.find();
0408: System.out.println("Benchmarks begin at "
0409: + DateTime.getDateTimeString());
0410: myPool.release(conn1);
0411: myPool.release(conn2);
0412: myPool.release(conn3);
0413: myPool.release(conn4);
0414: myPool.release(conn5);
0415: }
0416:
0417: retryCount = 5000;
0418: System.out.println("End dbobject tests:"
0419: + DateTime.getDateTimeString());
0420: System.out
0421: .println("This benchmark tests the performance of the "
0422: + "connection pool in simple \n"
0423: + " allocations of connections - it makes & releases "
0424: + retryCount + " connections, 5 at a time.\n");
0425: System.out.println("Begin connection pool tests:"
0426: + DateTime.getDateTimeString());
0427: myPool = DBConnectionPool.getInstance("default");
0428:
0429: for (int i = 0; i <= retryCount; i++) {
0430: DBConnection conn1 = myPool
0431: .getConnection("Test " + (i + 1));
0432: DBConnection conn2 = myPool
0433: .getConnection("Test " + (i + 2));
0434: DBConnection conn3 = myPool
0435: .getConnection("Test " + (i + 4));
0436: DBConnection conn4 = myPool
0437: .getConnection("Test " + (i + 5));
0438: DBConnection conn5 = myPool
0439: .getConnection("Test " + (i + 6));
0440: myPool.release(conn1);
0441: myPool.release(conn2);
0442: myPool.release(conn3);
0443: myPool.release(conn4);
0444: myPool.release(conn5);
0445: }
0446:
0447: System.out.println("End connection pool tests:"
0448: + DateTime.getDateTimeString());
0449: System.out
0450: .println("Compare this to making & breaking the connection "
0451: + "to the DB the same number\n" + " of times.");
0452: dbURL = ConfigManager.getJdbcRequired("default").getUrl();
0453: dbLogin = ConfigManager.getJdbcRequired("default").getLogin();
0454: dbPassword = ConfigManager.getJdbcRequired("default")
0455: .getPassword();
0456: System.out.println("Begin direct connection tests:"
0457: + DateTime.getDateTimeString());
0458:
0459: for (int i = 0; i <= retryCount; i++) {
0460: Connection conn1 = DriverManager.getConnection(dbURL,
0461: dbLogin, dbPassword);
0462: conn1.createStatement();
0463: conn1.close();
0464:
0465: Connection conn2 = DriverManager.getConnection(dbURL,
0466: dbLogin, dbPassword);
0467: conn2.createStatement();
0468: conn2.close();
0469:
0470: Connection conn3 = DriverManager.getConnection(dbURL,
0471: dbLogin, dbPassword);
0472: conn3.createStatement();
0473: conn3.close();
0474:
0475: Connection conn4 = DriverManager.getConnection(dbURL,
0476: dbLogin, dbPassword);
0477: conn4.createStatement();
0478: conn4.close();
0479:
0480: Connection conn5 = DriverManager.getConnection(dbURL,
0481: dbLogin, dbPassword);
0482: conn5.createStatement();
0483: conn5.close();
0484: }
0485:
0486: System.out.println("End direct connection tests:"
0487: + DateTime.getDateTimeString());
0488: System.out
0489: .println("Direct SQL tests - the above test is repeated, "
0490: + "but with a series of simple \n"
0491: + " SQL queries executed in each of the connections.");
0492: System.out.println("Begin direct SQL tests:"
0493: + DateTime.getDateTimeString());
0494:
0495: for (int i = 0; i <= retryCount; i++) {
0496: DBConnection conn1 = myPool
0497: .getConnection("Test " + (i + 1));
0498: conn1
0499: .execute("SELECT * FROM USERLOGIN WHERE UserName = 'Admin'");
0500:
0501: DBConnection conn2 = myPool
0502: .getConnection("Test " + (i + 2));
0503: conn2
0504: .execute("SELECT * FROM GROUPMEMBERS WHERE UserName = 'Admin'");
0505:
0506: DBConnection conn3 = myPool
0507: .getConnection("Test " + (i + 4));
0508: conn3
0509: .execute("SELECT * FROM SETUP WHERE SetupCode = 'ServletEvent'");
0510:
0511: DBConnection conn4 = myPool
0512: .getConnection("Test " + (i + 5));
0513: conn4
0514: .execute("SELECT * FROM DBOBJSECURITY WHERE GroupName = 'Admin'");
0515:
0516: DBConnection conn5 = myPool
0517: .getConnection("Test " + (i + 6));
0518: conn5
0519: .execute("SELECT * FROM EVENT WHERE Event = 'SYSERROR'");
0520: myPool.release(conn1);
0521: myPool.release(conn2);
0522: myPool.release(conn3);
0523: myPool.release(conn4);
0524: myPool.release(conn5);
0525: }
0526:
0527: System.out.println("End direct SQL tests:"
0528: + DateTime.getDateTimeString());
0529: System.out
0530: .println("DB Object tests - the above test is repeated, "
0531: + "but with db objects \n"
0532: + " doing the queries rather than direct sql");
0533: System.out.println("Begin db object tests:"
0534: + DateTime.getDateTimeString());
0535: gm = new GroupMembers();
0536: oneUser = new DefaultUserInfo();
0537: s1 = new Setup();
0538: dbo = new DBObjSecurity();
0539: e = new Event();
0540:
0541: for (int i = 0; i <= retryCount; i++) {
0542: DBConnection conn1 = myPool
0543: .getConnection("Test " + (i + 1));
0544:
0545: // Modified 05/20/01 by Shash Chatterjee
0546: // Used to use UserDBObj directly....but Uid as key complicates things....
0547: // oneUser.setConnection(conn1);
0548: oneUser.setField("UserName", User.ADMIN_USER);
0549: oneUser.find();
0550:
0551: DBConnection conn2 = myPool
0552: .getConnection("Test " + (i + 2));
0553: gm.setConnection(conn2);
0554: gm.setField("UserName", User.ADMIN_USER);
0555: gm.find();
0556:
0557: DBConnection conn3 = myPool
0558: .getConnection("Test " + (i + 4));
0559: s1.setConnection(conn3);
0560: s1.setField("SetupCode", "ServletEvent");
0561: s1.find();
0562:
0563: DBConnection conn4 = myPool
0564: .getConnection("Test " + (i + 5));
0565: dbo.setConnection(conn4);
0566: dbo.setField("GroupName", User.ADMIN_USER);
0567: dbo.find();
0568:
0569: DBConnection conn5 = myPool
0570: .getConnection("Test " + (i + 6));
0571: e.setConnection(conn5);
0572: e.setField("Event", "SYSERROR");
0573: e.find();
0574: myPool.release(conn1);
0575: myPool.release(conn2);
0576: myPool.release(conn3);
0577: myPool.release(conn4);
0578: myPool.release(conn5);
0579: }
0580:
0581: System.out.println("End dbobject tests:"
0582: + DateTime.getDateTimeString());
0583: System.out.println("Benchmarks end at "
0584: + DateTime.getDateTimeString());
0585: } /* doBenchMarks() */
0586:
0587: /**
0588: * Delete Table - Deletes a table from the specified db
0589: *
0590: * @param dbName - the name of the db that contains this table
0591: * @param tableName - The name of the table to delete.
0592: */
0593: public static void deleteTable(String dbName, String tableName)
0594: throws DBException {
0595: DBConnectionPool pool = DBConnectionPool.getInstance(dbName);
0596: String stmnt = "DROP TABLE " + tableName;
0597: pool.executeExclusiveUpdate(stmnt);
0598: }
0599:
0600: /**
0601: * Method wipes out more than one installed schema.
0602: *
0603: * @param myPage an HTML page to render output to (optional)
0604: * @param dbName The database context to create the database in.
0605: * @param schemas List of the schema objects to delete
0606: * @throws HtmlException if an error occurs constructing the HTML code
0607: */
0608: public static synchronized void deleteSchema(Page myPage,
0609: String dbName, Vector schemas) throws DBException,
0610: HtmlException, IllegalArgumentException {
0611: log.info("Removing " + Integer.toString(schemas.size())
0612: + " schemas");
0613:
0614: for (Enumeration e = schemas.elements(); e.hasMoreElements();) {
0615: String oneName = (e.nextElement()).getClass().getName();
0616: deleteSchema(myPage, dbName, oneName);
0617: }
0618:
0619: log.info("Schema Deletion Complete");
0620: }
0621:
0622: /**
0623: * Method to remove an installed schema. Deletes all the tables associated
0624: * with the schema
0625: *
0626: * @param myPage - The page to output the 'log' to.
0627: * @param dbName - the name of the database to perform this operation
0628: * @param schemaName - the full classname of the schema to delete.
0629: * @throws IllegalArgumentException if the schema doesn't exist.
0630: * @throws DBException If there is a database problem creating
0631: * the new default values
0632: * @throws HtmlException If there is a problem building the
0633: * confirmation page
0634: * <p/>
0635: * Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
0636: * @since $DatabaseSchema $Date: 2004/11/20 20:11:53 $
0637: */
0638: public static synchronized void deleteSchema(Page myPage,
0639: String dbName, String schemaName) throws DBException,
0640: HtmlException, IllegalArgumentException {
0641: final String myName = (this Class + "deleteSchema(Page,String,String)");
0642: boolean expressoDelete = false;
0643: log.info(myName + ": removing schema: " + schemaName
0644: + " from db " + dbName);
0645:
0646: if (schemaName
0647: .equals("com.jcorporate.expresso.core.ExpressoSchema")) {
0648: expressoDelete = true;
0649: }
0650:
0651: Schema oneSchema = null;
0652:
0653: try {
0654: oneSchema = (Schema) Class.forName(schemaName)
0655: .newInstance();
0656: } catch (Throwable e) {
0657: throw new IllegalArgumentException("Unable to load class "
0658: + schemaName + " " + e.getMessage());
0659: }
0660:
0661: DBObject oneObject;
0662:
0663: try {
0664:
0665: //Make sure all connections are dropped first - otherwise tables
0666: //will be locked
0667: DBConnectionPool.reInitialize();
0668: } catch (DBException e) {
0669: }
0670: for (Enumeration e = oneSchema.getMembers(); e
0671: .hasMoreElements();) {
0672: oneObject = (DBObject) e.nextElement();
0673:
0674: if (myPage != null) {
0675: myPage.add(new Paragraph(new Text("Removing Table"
0676: + " "
0677: + oneObject.getJDBCMetaData()
0678: .getTargetSQLTable(
0679: oneObject.getDataContext()))));
0680: }
0681: try {
0682: deleteTable(dbName, oneObject.getJDBCMetaData()
0683: .getTargetSQLTable(oneObject.getDataContext()));
0684: } catch (DBException dbe) {
0685: log.warn("Unable To Delete Table: "
0686: + oneObject.getJDBCMetaData()
0687: .getTargetSQLTable(
0688: oneObject.getDataContext())
0689: + " DB Message: " + dbe.getDBMessage());
0690: }
0691: }
0692: //If schema is not expresso, we also have to clear the
0693: //setup table
0694: if (expressoDelete == false) {
0695: try {
0696:
0697: //First remove the schema entries
0698: SchemaList schemaEntry = new SchemaList(
0699: SecuredDBObject.SYSTEM_ACCOUNT);
0700: schemaEntry.setDataContext(dbName);
0701: schemaEntry.setField("SchemaClass", schemaName);
0702: schemaEntry.delete();
0703: } catch (DBException e) {
0704: log.info("Unable to delete schema entry.", e);
0705: }
0706:
0707: //Now remove the setup values
0708: Setup setupList = new Setup(SecuredDBObject.SYSTEM_ACCOUNT);
0709: setupList.setDataContext(dbName);
0710: setupList.setField("SchemaClass", schemaName);
0711:
0712: List list = setupList.searchAndRetrieveList();
0713: for (Iterator iterator = list.iterator(); iterator
0714: .hasNext();) {
0715: Setup s = (Setup) iterator.next();
0716: try {
0717: s.setDataContext(dbName);
0718: s.delete();
0719: } catch (DBException e) {
0720: if (s != null) {
0721: log.info("Unable to delete setup value: "
0722: + s.getField("SetupCode"), e);
0723: } else {
0724: log
0725: .info(
0726: "Unable to delete setup value: (s=null)",
0727: e);
0728: }
0729: }
0730: }
0731: }
0732: if (myPage != null) {
0733: myPage.add(new Paragraph(new Text("All Tables Removed")));
0734: }
0735: } /* otherSetups(PrintWriter, Vector, String) */
0736:
0737: /**
0738: * @param dbName The datacontext to use
0739: * @param schemaClass The classname of the Schema Object to use
0740: */
0741: private static void enterConfig(String dbName, String schemaClass)
0742: throws DBException, IOException {
0743: System.out.println("Setup/Configuration values: (Database "
0744: + dbName + ", Schema " + schemaClass + ")");
0745:
0746: Setup setupList = new Setup();
0747: setupList.setDataContext(dbName);
0748:
0749: String command = ("");
0750: setupList.setField("SchemaClass", schemaClass);
0751:
0752: List list = setupList.searchAndRetrieveList();
0753: if (list.size() == 0) {
0754: System.out
0755: .println("There were no default setup values in database/context '"
0756: + dbName
0757: + "'. You must run initial setup to create the defaults "
0758: + "first.");
0759: }
0760:
0761: for (Iterator iterator = list.iterator(); iterator.hasNext();) {
0762: Setup oneSetup = (Setup) iterator.next();
0763: System.out.println("---------------------------------");
0764: System.out.println("Setup Code :"
0765: + oneSetup.getField("SetupCode"));
0766: System.out.println("Description :"
0767: + oneSetup.getField("Descrip"));
0768: System.out.println("Current Value:"
0769: + oneSetup.getField("SetupValue"));
0770: System.out.println("");
0771: System.out
0772: .print("Press enter to leave current value, or enter new value:");
0773:
0774: BufferedReader br = new BufferedReader(
0775: new InputStreamReader(System.in));
0776: command = StringUtil.notNull(br.readLine());
0777:
0778: if (!command.equals("")) {
0779: System.out.println("Value for code '"
0780: + oneSetup.getField("SetupCode") + "' "
0781: + " now '" + command + "'");
0782: oneSetup.setField("SetupValue", command);
0783: oneSetup.update();
0784: System.out.println("Database updated");
0785: } else {
0786: System.out.println("Current value retained.");
0787: }
0788: } /* while more values */
0789:
0790: System.out
0791: .println("All setup values have been edited & stored.");
0792: } /* enterConfig(String, String) */
0793:
0794: /**
0795: * Export data from the named dbobject to the specified filename
0796: *
0797: * @param exportCmd The DBobject class name to export
0798: * @param fileName The filename to export to
0799: * @param format The format to export to, either 'xml', or 'tab'
0800: */
0801: private static void exportFile(String exportCmd, String fileName,
0802: String format) throws DBException, IOException,
0803: IllegalAccessException, InstantiationException,
0804: ClassNotFoundException {
0805: DBObject myObj = (DBObject) Class.forName(exportCmd)
0806: .newInstance();
0807:
0808: //myObj.setConnection(myConnection);
0809: if (format == null) {
0810: format = ("tab");
0811: }
0812: if (format.equals("tab")) {
0813: exportTabFile(myObj, fileName);
0814: } else if (format.equals("xml")) {
0815: throw new IOException("not implemented yet");
0816: }
0817: } /* exportFile(String, String, String, DBConnection) */
0818:
0819: /**
0820: * Export the named database object into the given file, where the file
0821: * is tab delimited, and the fields are in the order of the database
0822: * object's fields
0823: *
0824: * @param myObj The DBOBject to export
0825: * @param fileName The filename to export to
0826: */
0827: private static void exportTabFile(DBObject myObj, String fileName)
0828: throws IOException, DBException {
0829: FileOutputStream fout = new FileOutputStream(fileName, false);
0830: BufferedOutputStream bout = new BufferedOutputStream(fout);
0831: PrintStream out = new PrintStream(bout);
0832: int lineCount = 0;
0833: DBObject oneObj = null;
0834: String fieldName = null;
0835:
0836: for (Iterator rc = myObj.searchAndRetrieveList().iterator(); rc
0837: .hasNext();) {
0838: oneObj = (DBObject) rc.next();
0839:
0840: for (Iterator e = myObj.getJDBCMetaData()
0841: .getFieldListArray().iterator(); e.hasNext();) {
0842: fieldName = (String) e.next();
0843: out.print(oneObj.getField(fieldName) + "\t");
0844: } /* for each field */
0845:
0846: out.println("");
0847: lineCount++;
0848: } /* for each record */
0849:
0850: out.flush();
0851: out.close();
0852: System.out.println("Wrote " + lineCount + " records from "
0853: + myObj.getJDBCMetaData().getDescription() + " to "
0854: + fileName);
0855: } /* exportTabFile(DBObject, String) */
0856:
0857: /**
0858: * Recursively generate a Java DBObject file for every table
0859: * in the specified database.
0860: * <p/>
0861: * The schemaPattern and tableNamePattern attributes take a String
0862: * that can match the JDBC pattern-matching format.
0863: * A percent ("%") character will match 0
0864: * or more characters in a String, while an underscore ("_") character
0865: * will match any single character.
0866: * So, if you wanted to retrieve information on all tables in schemas
0867: * containing the string "Employee", you could use "%Employee%"
0868: * for the schemaPattern parameter.
0869: * <p/>
0870: * Both schemaPattern and tableNamePattern may be null, in which case
0871: * all tables will be returned.
0872: *
0873: * @param myConnection The dbconnection to use.
0874: * @param schemaPattern - Only used by databases that support schemas.
0875: * @param tableNamePattern - Name of the table to export or ALL
0876: * @param packageName The base name of the package to generate all the DBObjects
0877: * into
0878: * @param dbKey The data context to generate from
0879: */
0880: private static void genAllDBObject(DBConnection myConnection,
0881: String schemaPattern, String tableNamePattern,
0882: String dbKey, String packageName) throws IOException,
0883: DBException, SQLException {
0884: System.out
0885: .println("Fetching all table names to generate JAVA source files.");
0886:
0887: String tableName = null;
0888: String schemaName = null;
0889: DatabaseMetaData dm = myConnection.getDBMetaData();
0890: ResultSet rs = dm.getTables(null, schemaPattern,
0891: tableNamePattern, new String[] { "TABLE" });
0892: System.out
0893: .println("Table names obtained. Beginning JAVA source file generation.");
0894: System.out.println("Using schemaPattern = " + schemaPattern
0895: + " and tableNamePattern = " + tableNamePattern + ".");
0896:
0897: while (rs.next()) {
0898: tableName = rs.getString("TABLE_NAME");
0899: schemaName = rs.getString("TABLE_SCHEM");
0900:
0901: if (tableName != null && tableName.length() > 0) {
0902: String genStr = "\tTable = " + tableName;
0903: if (StringUtil.notNull(schemaName).length() > 0) {
0904: genStr += " and schema = " + schemaName;
0905: }
0906: System.out.println(genStr);
0907:
0908: genDBObject(myConnection, tableName, dbKey, packageName);
0909: } else {
0910: System.out.println("ignoring null table = " + tableName
0911: + " and schema = "
0912: + StringUtil.notNull(schemaName));
0913:
0914: }
0915: }
0916:
0917: System.out.println("JAVA source file generation completed.");
0918: } /* genAllDBObjects(DBConnection, String) */
0919:
0920: /**
0921: * Generate a Java file as a database object for the given table
0922: *
0923: * @param myConnection The DBConnection to use
0924: * @param generate The table name to generate
0925: * @param dbKey The data context to generate from
0926: * @param packageName the base java package name to generate the dbobjects
0927: * into
0928: */
0929: private static void genDBObject(DBConnection myConnection,
0930: String generate, String dbKey, String packageName)
0931: throws IOException, DBException, SQLException {
0932: DatabaseMetaData dm = myConnection.getDBMetaData();
0933: // String thisCatalog = myConnection.getCatalog();
0934: //System.out.println("Catalog: " + thisCatalog);
0935:
0936: String tableName = generate;
0937: String javaClassName = getJavaClassName(tableName);
0938: File file = new File(javaClassName + ".java");
0939: FileOutputStream fout = new FileOutputStream(file.getName(),
0940: false);
0941: System.out.println("File: " + file.getAbsoluteFile());
0942: BufferedOutputStream bout = new BufferedOutputStream(fout);
0943: PrintStream f = new PrintStream(bout);
0944: f.println("/*");
0945: f.println("* " + javaClassName + ".java");
0946: f.println("*");
0947: f.println("* Automatically Generated by Expresso's DBTool on "
0948: + (new Date()).toString());
0949: f.println("*/");
0950: f.println("");
0951:
0952: if (packageName != null) {
0953: f.println("package " + packageName + ";");
0954: }
0955: f.println("");
0956: f.println("import com.jcorporate.expresso.core.dbobj.*;");
0957: f.println("import com.jcorporate.expresso.core.db.*;");
0958: // f.println("import java.util.Hashtable;");
0959: // f.println("import java.util.Enumeration;");
0960: f.println("");
0961: f.println("public class " + javaClassName
0962: + " extends SecuredDBObject {");
0963: f.println("");
0964: f.println("\t/**");
0965: f.println("\t * Constructor");
0966: f
0967: .println("\t * Create a new object of this type with no connection");
0968: f.println("\t * yet allocated.");
0969: f.println("\t */");
0970: f.println("\tpublic " + javaClassName
0971: + "() throws DBException {");
0972: f.println("\t} ");
0973: f.println("");
0974: f.println("");
0975: f.println("\t/**");
0976: f.println("\t * Constructor");
0977: f.println("\t *");
0978: f
0979: .println("\t * @param theConnection Database connection to ");
0980: f.println("\t * communicate with the database");
0981: f
0982: .println("\t * @throws DBException If the new object cannot be ");
0983: f.println("\t * created");
0984: f.println("\t */");
0985: f.println("\tpublic " + javaClassName
0986: + "(DBConnection theConnection) "
0987: + "throws DBException {");
0988: f.println("\t\tsuper(theConnection);");
0989: f.println("\t} ");
0990: f.println("");
0991: f.println("");
0992: f.println("\t/**");
0993: f.println("\t * Constructor");
0994: f.println("\t *");
0995: f
0996: .println("\t * @param theConnection DBConnection to be used to ");
0997: f.println("\t * communicate with the database");
0998: f
0999: .println("\t * @param theUser User name attempting to access the ");
1000: f.println("\t * object");
1001: f
1002: .println("\t * @throws DBException If the user cannot access this ");
1003: f.println("\t * object or the object cannot be initialized");
1004: f.println("\t */");
1005: f.println("\tpublic " + javaClassName
1006: + "(DBConnection theConnection, "
1007: + "String theUser) throws DBException {");
1008: f.println("\t\tsuper(theConnection, theUser);");
1009: f.println("\t} ");
1010: f.println("");
1011: f.println("");
1012: f.println("\t/**");
1013: f.println("\t * Define the fields for this object");
1014: f.println("\t *");
1015: f.println("\t * @throws DBException");
1016: f.println("\t */");
1017: f.println("\tprotected synchronized void setupFields() throws "
1018: + "DBException {");
1019: f.println("\t\tsetTargetTable(\"" + tableName + "\");");
1020: f.println("");
1021: f
1022: .println("\t\tsetDescription(\"Object Description Goes Here\");");
1023: f.println("");
1024: //Postgresql JDBC 7.2 driver bug. Tablename must be lower case
1025: //which doesn't apply to other databases such as Oracle
1026: try {
1027: if (ConfigManager.getJdbcRequired(dbName).getDriver()
1028: .equals("org.postgresql.Driver")) {
1029:
1030: tableName = tableName.toLowerCase();
1031: }
1032: } catch (ConfigurationException ce) {
1033: log.error("Error getting config for " + dbName + " ", ce);
1034: throw new DBException(ce);
1035: }
1036:
1037: ArrayList listOfColumnNames = new ArrayList();
1038: ResultSet rs = dm.getColumns(null, "%", tableName, "%");
1039: String fieldName = null;
1040: String fieldType;
1041: String expressoType = null;
1042: int sqlType = 0;
1043: int fieldSize;
1044: int nullField = 0;
1045: boolean nullable;
1046: String fieldDescrip = null;
1047: TypeMapper tm = TypeMapper.getInstance(dbKey);
1048: while (rs.next()) {
1049:
1050: sqlType = rs.getInt(5);
1051: expressoType = tm.getTypeForExpresso(sqlType);
1052:
1053: if (expressoType == null || expressoType.length() == 0) {
1054:
1055: expressoType = "UNMAPPED_TYPE";
1056:
1057: }
1058:
1059: fieldName = rs.getString(4);
1060: listOfColumnNames.add("\tpublic static final String "
1061: + fieldName + " = \"" + fieldName + "\";");
1062:
1063: fieldSize = rs.getInt(7);
1064:
1065: fieldDescrip = rs.getString(12);
1066:
1067: fieldType = rs.getString(6);
1068:
1069: nullField = rs.getInt(11);
1070:
1071: if (nullField == DatabaseMetaData.columnNoNulls) {
1072:
1073: nullable = false;
1074:
1075: } else {
1076:
1077: nullable = true;
1078:
1079: }
1080:
1081: f
1082: .print("\t\taddField(" + fieldName + ", \""
1083: + expressoType);
1084:
1085: f.print("\", " + fieldSize + ", ");
1086:
1087: if (nullable) {
1088:
1089: f.print("true");
1090:
1091: } else {
1092:
1093: f.print("false");
1094:
1095: }
1096:
1097: f.print(", \"" + StringUtil.notNull(fieldDescrip) + "\");");
1098:
1099: f.println("\t // " + fieldName + " had DB type: "
1100: + fieldType
1101: + " in the database that was reverse-engineered.");
1102:
1103: } /* for each field */
1104:
1105: f.println("");
1106: ResultSet rspk = dm.getPrimaryKeys(null, "%", tableName);
1107:
1108: while (rspk.next()) {
1109: f.println("\t\taddKey(" + rspk.getString("COLUMN_NAME")
1110: + ");");
1111: }
1112:
1113: f.println("\t} /* setupFields() */");
1114: f.println("");
1115:
1116: // it would have been nice to do this at top of class, but it is easier to
1117: // declare these statics here
1118: for (Iterator iter = listOfColumnNames.iterator(); iter
1119: .hasNext();) {
1120: String fieldDecl = (String) iter.next();
1121: f.println(fieldDecl);
1122: }
1123: f.println("");
1124: f.println("\t/**");
1125: f.println("\t * Standard method to create a new copy of this ");
1126: f.println("\t * particular database object");
1127: f.println("\t * ");
1128: f
1129: .println("\t * @return DBObject A newly created instance of this "
1130: + "object");
1131: f
1132: .println("\t * @throws DBException If the new object cannot be "
1133: + "created");
1134: f.println("\t */");
1135: f
1136: .println("\tpublic DBObject getThisDBObj() throws DBException {");
1137: f.println(" return new " + javaClassName + "();");
1138: f.println("\t} ");
1139: f.println("} /* " + javaClassName + " */");
1140: f.println("");
1141: f.close();
1142: } /* genDBObject(DBConnection, String) */
1143:
1144: /**
1145: * Reverse engineer the table for each db object for every known schema, then
1146: * compare the fields in the database to the fields in the db object and report
1147: * on the differences to the the log and to System.err
1148: * <p/>
1149: * todo why isn't this log passed in used?
1150: *
1151: * @param theLog the Install log to output to
1152: * @param allSchemas a vector of all the schemas to compare
1153: * @param dbName the data context to use
1154: * @return list of string error messages
1155: */
1156: public static List compareTables(InstallLog theLog,
1157: Vector allSchemas, String dbName) throws DBException,
1158: ConfigurationException {
1159: String defaultDbName = dbName;
1160: ArrayList messages = new ArrayList();
1161: messages.add("Comparing tables for database '" + dbName + "'");
1162:
1163: boolean compareLengths = true;
1164:
1165: /* Some drivers can't provide length information, notably Hsql */
1166: if (StringUtil.notNull(
1167: ConfigManager.getJdbcRequired(dbName).getDriver())
1168: .equals("org.hsqldb.jdbcDriver")) {
1169: compareLengths = false;
1170: }
1171:
1172: DBConnectionPool myPool = null;
1173: DBConnection myConnection = null;
1174:
1175: try {
1176:
1177: /* For each schema */
1178: for (Enumeration e = allSchemas.elements(); e
1179: .hasMoreElements();) {
1180: Schema oneSchema = (Schema) e.nextElement();
1181: messages
1182: .add("Schema:" + oneSchema.getClass().getName());
1183:
1184: if (log.isDebugEnabled()) {
1185: log.debug("Schema:"
1186: + oneSchema.getClass().getName());
1187: }
1188:
1189: /* for each database object in the schema */
1190: DBObject oneDBObject = null;
1191:
1192: for (Enumeration dbo = oneSchema.getMembers(); dbo
1193: .hasMoreElements();) {
1194: oneDBObject = (DBObject) dbo.nextElement();
1195:
1196: if (log.isDebugEnabled()) {
1197: log.debug("DBObject:"
1198: + oneDBObject.getClass().getName());
1199: }
1200:
1201: oneDBObject.setDataContext(defaultDbName);
1202:
1203: //STOP HERE
1204: //This dbobject may be in an "otherdb" location, so we get it
1205: //back to see...
1206: dbName = oneDBObject.getMappedDataContext();
1207: myPool = DBConnectionPool.getInstance(dbName);
1208: myConnection = myPool.getConnection();
1209:
1210: DatabaseMetaData dm = myConnection.getDBMetaData();
1211: ArrayList allFieldsFromObj = oneDBObject
1212: .getMetaData().getFieldListArray();
1213: ArrayList allFields = new ArrayList();
1214: String oneFieldName = null;
1215:
1216: for (Iterator of = allFieldsFromObj.iterator(); of
1217: .hasNext();) {
1218: oneFieldName = (String) of.next();
1219: allFields.add(oneFieldName);
1220: }
1221:
1222: String tableName = oneDBObject.getJDBCMetaData()
1223: .getTargetSQLTable(
1224: oneDBObject.getDataContext());
1225: //Postgresql JDBC 7.2 driver bug. Tablename must be lower case
1226: //which doesn't apply to other databases such as Oracle
1227: if (ConfigManager.getJdbcRequired(dbName)
1228: .getDriver()
1229: .equals("org.postgresql.Driver")) {
1230:
1231: tableName = tableName.toLowerCase();
1232: }
1233: ResultSet rs = dm.getColumns(null, "%", tableName,
1234: "%");
1235: String fieldName = null;
1236: // String fieldType;
1237: int fieldSize;
1238: int nullField = 0;
1239: boolean nullable;
1240: String nullableByDBObj = null;
1241:
1242: while (rs.next()) {
1243: fieldName = rs.getString(4);
1244: fieldSize = rs.getInt(7);
1245: //fieldDescrip = rs.getString(12);
1246: //fieldType = rs.getString(6);
1247: nullField = rs.getInt(11);
1248:
1249: if (nullField == DatabaseMetaData.columnNoNulls) {
1250: nullable = false;
1251: } else {
1252: nullable = true;
1253: }
1254: if (log.isDebugEnabled()) {
1255: log.debug("Field:" + fieldName);
1256: }
1257: /* Now compare */
1258: String internalFieldName = oneDBObject
1259: .getJDBCMetaData().isFieldIgnoreCase(
1260: fieldName);
1261: if (internalFieldName != null) {
1262: nullableByDBObj = "N";
1263:
1264: if (oneDBObject.getFieldMetaData(
1265: internalFieldName).allowsNull()) {
1266: nullableByDBObj = "Y";
1267: }
1268: /* Drop it from the list of field names, so we know we've */
1269: /* done it */
1270: if (compareLengths) {
1271: int dbObjLength = oneDBObject
1272: .getLengthInt(internalFieldName);
1273:
1274: if ((dbObjLength != fieldSize)
1275: && (dbObjLength != 0)) {
1276: messages
1277: .add("Length does not match: Field '"
1278: + fieldName
1279: + "' in table '"
1280: + tableName
1281: + "' is defined as length "
1282: + fieldSize
1283: + ", "
1284: + " but in DBObject '"
1285: + oneDBObject
1286: .getClass()
1287: .getName()
1288: + "' is defined as type "
1289: + oneDBObject
1290: .getFieldMetaData(
1291: internalFieldName)
1292: .getTypeString()
1293: + " size "
1294: + dbObjLength
1295: + " and null allowed = "
1296: + nullableByDBObj
1297: + ". The table should be "
1298: + " altered to match.");
1299: }
1300: }
1301: if (nullableByDBObj.equals("N") && nullable) {
1302: messages
1303: .add("Field '"
1304: + fieldName
1305: + "' in table '"
1306: + tableName
1307: + "' allows nulls in the database, but the "
1308: + oneDBObject
1309: .getClass()
1310: .getName()
1311: + " DBObject does not allow nulls for this "
1312: + " field. It should be set to not allow "
1313: + " nulls in the database as well."
1314: + " It is defined as type "
1315: + oneDBObject
1316: .getFieldMetaData(
1317: internalFieldName)
1318: .getTypeString()
1319: + ", length "
1320: + oneDBObject
1321: .getFieldMetaData(
1322: internalFieldName)
1323: .getLengthInt()
1324: + ".");
1325: }
1326: if (nullableByDBObj.equals("Y")
1327: && (!nullable)) {
1328: messages
1329: .add("Field '"
1330: + fieldName
1331: + "' in table '"
1332: + tableName
1333: + "' does not allow nulls in the database, "
1334: + "but the "
1335: + oneDBObject
1336: .getClass()
1337: .getName()
1338: + " DBObject *does* allow nulls for this "
1339: + " field. It should be set to allow "
1340: + " nulls in the database as well."
1341: + " It is defined as type "
1342: + oneDBObject
1343: .getFieldMetaData(
1344: internalFieldName)
1345: .getTypeString()
1346: + ", length "
1347: + oneDBObject
1348: .getFieldMetaData(
1349: internalFieldName)
1350: .getLengthInt()
1351: + ".");
1352: }
1353:
1354: allFields.remove(internalFieldName);
1355: } else {
1356: messages.add("Field '" + fieldName
1357: + "' is in the table '" + tableName
1358: + "', but is not "
1359: + "a field in DBObject '"
1360: + oneDBObject.getClass().getName()
1361: + "'. It should be "
1362: + "dropped from the table.");
1363: }
1364: } /* for each field */
1365:
1366: String oneLeftOverFieldName = null;
1367:
1368: for (Iterator leftOvers = allFields.iterator(); leftOvers
1369: .hasNext();) {
1370: oneLeftOverFieldName = (String) leftOvers
1371: .next();
1372:
1373: if (!oneDBObject.getMetaData().isVirtual(
1374: oneLeftOverFieldName)) {
1375: messages
1376: .add("Field '"
1377: + oneLeftOverFieldName
1378: + "' is defined in "
1379: + "db object '"
1380: + oneDBObject.getClass()
1381: .getName()
1382: + "', but "
1383: + "is not defined as part of the table '"
1384: + oneDBObject
1385: .getJDBCMetaData()
1386: .getTargetSQLTable(
1387: oneDBObject
1388: .getDataContext())
1389: + "' in the database. You "
1390: + "must alter this table to add this field."
1391: + " It is defined as type "
1392: + oneDBObject
1393: .getFieldMetaData(
1394: oneLeftOverFieldName)
1395: .getTypeString()
1396: + ", length "
1397: + oneDBObject
1398: .getFieldMetaData(
1399: oneLeftOverFieldName)
1400: .getLengthInt()
1401: + " and allows null = "
1402: + nullableByDBObj + ".");
1403: }
1404: }
1405: if (myPool != null) {
1406: myPool.release(myConnection);
1407: }
1408:
1409: myPool = null;
1410: } /* for each DB Object in this schema */
1411:
1412: } /* for each schema */
1413:
1414: } catch (SQLException se) {
1415: throw new DBException(se);
1416: } finally {
1417: if (myPool != null) {
1418: myPool.release(myConnection);
1419: }
1420: }
1421:
1422: String oneMessage = null;
1423: for (Iterator i = messages.iterator(); i.hasNext();) {
1424: oneMessage = (String) i.next();
1425: log.info(oneMessage);
1426: System.out.println(oneMessage);
1427: } /* for each message */
1428:
1429: return messages;
1430: } /* compareTables(DBConnection, String) */
1431:
1432: /**
1433: * Instantiate & load all Schema objects that we know about,
1434: * get a list of their DBObjects, and call the import or export
1435: * for each DBObject as appropriate
1436: *
1437: * @param myConnection The DBConnection to use
1438: * @param choice either 'import' or 'export'
1439: * @param format The import format, either 'tab' or 'xml'
1440: * @throws ServerException Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
1441: * @since $DatabaseSchema $Date: 2004/11/20 20:11:53 $
1442: */
1443: private static void importExportAll(DBConnection myConnection,
1444: String choice, String format) throws DBException,
1445: IllegalAccessException, InstantiationException,
1446: ClassNotFoundException, IOException, ServerException {
1447: String extension;
1448:
1449: if (format == null) {
1450: format = ("tab");
1451: }
1452: if (format.equals("xml")) {
1453: extension = ("xml");
1454: } else {
1455: extension = ("dat");
1456: }
1457:
1458: Vector allSchemas = new Vector(5);
1459: {
1460: ExpressoSchema jcs = new ExpressoSchema();
1461: allSchemas.addElement(jcs);
1462:
1463: SchemaList sl = new SchemaList(
1464: SecuredDBObject.SYSTEM_ACCOUNT);
1465: List list = sl.searchAndRetrieveList();
1466: for (Iterator iterator = list.iterator(); iterator
1467: .hasNext();) {
1468: SchemaList oneSchema = (SchemaList) iterator.next();
1469:
1470: Schema mySchema2 = SchemaFactory.getInstance()
1471: .getSchema(oneSchema.getField("SchemaClass"));
1472:
1473: if (mySchema2 != null) {
1474: allSchemas.addElement(mySchema2);
1475: }
1476: }
1477: }
1478:
1479: System.out.println("Loaded " + allSchemas.size()
1480: + " schema objects.");
1481:
1482: Schema this Schema = null;
1483:
1484: for (Enumeration als = allSchemas.elements(); als
1485: .hasMoreElements();) {
1486: this Schema = (Schema) als.nextElement();
1487: System.out.println(choice + "ing objects in Schema "
1488: + this Schema.getClass().getName());
1489:
1490: DBObject oneObject = null;
1491:
1492: for (Enumeration dbo = this Schema.getMembers(); dbo
1493: .hasMoreElements();) {
1494: oneObject = (DBObject) dbo.nextElement();
1495: System.out.println(choice + "ing database object "
1496: + oneObject.getJDBCMetaData().getName() + " ("
1497: + oneObject.getJDBCMetaData().getDescription()
1498: + ")");
1499:
1500: //oneObject.setConnection(myConnection);
1501: if (choice.equals("import")) {
1502: importFile(oneObject.getClass().getName(),
1503: oneObject.getJDBCMetaData()
1504: .getTargetSQLTable(
1505: oneObject.getDataContext())
1506: + "." + extension, format,
1507: myConnection);
1508: } else {
1509: exportFile(oneObject.getClass().getName(),
1510: oneObject.getJDBCMetaData()
1511: .getTargetSQLTable(
1512: oneObject.getDataContext())
1513: + "." + extension, format);
1514: }
1515: } /* for each database object */
1516:
1517: } /* for each schema in the list */
1518:
1519: } /* importExportAll(DBConnection, String, String) */
1520:
1521: /**
1522: * Import data into the named dbobject from the specified filename
1523: *
1524: * @param importCmd The DBObject class name to import
1525: * @param fileName The filename to use
1526: * @param format either 'tab' or 'xml'
1527: * @param myConnection The DBConnection to use for import
1528: * @throws ServerException Modify by Yves Henri AMAIZO <amy_amaizo@compuserve.com>
1529: * @since $DatabaseSchema $Date: 2004/11/20 20:11:53 $
1530: */
1531: private static void importFile(String importCmd, String fileName,
1532: String format, DBConnection myConnection)
1533: throws DBException, IOException, IllegalAccessException,
1534: InstantiationException, ClassNotFoundException,
1535: ServerException {
1536: DBObject myObj = (DBObject) Class.forName(importCmd)
1537: .newInstance();
1538:
1539: //myObj.setConnection(myConnection);
1540:
1541: /* Clear existing data */
1542: System.out.println("Clearing existing data from "
1543: + myObj.getJDBCMetaData().getTargetSQLTable(
1544: myObj.getDataContext()));
1545: myConnection.executeUpdate("DELETE FROM "
1546: + myObj.getJDBCMetaData().getTargetSQLTable(
1547: myObj.getDataContext()));
1548:
1549: if (format == null) {
1550: format = ("tab");
1551: }
1552: if (format.equals("tab")) {
1553: importTabFile(myObj, fileName);
1554: } else if (format.equals("xml")) {
1555: throw new ServerException(
1556: ":XML import not yet implemented.");
1557: }
1558: } /* importFile(String, String, String, DBConnection) */
1559:
1560: /**
1561: * Import the named file into the given database object, where the file
1562: * is tab delimited, and the fields are in the order of the database
1563: * object's fields
1564: *
1565: * @param myObj The DBObject to import to
1566: * @param fileName The filename of the tab delimited file.
1567: */
1568: private static void importTabFile(DBObject myObj, String fileName)
1569: throws IOException, DBException, ServerException {
1570: FileInputStream fin = new FileInputStream(fileName);
1571: BufferedInputStream bin = new BufferedInputStream(fin);
1572: BufferedReader ds = new BufferedReader(new InputStreamReader(
1573: bin));
1574: int lineCount = 0;
1575: String oneLine = ds.readLine();
1576:
1577: while (oneLine != null) {
1578: importTabLine(oneLine, myObj, lineCount);
1579: lineCount++;
1580: oneLine = ds.readLine();
1581: }
1582:
1583: System.out.println("Loaded " + lineCount + " records into "
1584: + myObj.getJDBCMetaData().getDescription());
1585: } /* importTabFile(DBObject, String) */
1586:
1587: /**
1588: * Process a single line of tab-delimited data into a record for the
1589: * given database object, and add the object to the database
1590: *
1591: * @param oneLine One tab delimited line.
1592: * @param myObj The target DBObject
1593: * @param lineNumber Line Number in the tab file, used for error tracking
1594: */
1595: private static void importTabLine(String oneLine, DBObject myObj,
1596: int lineNumber) throws DBException, ServerException {
1597: String fieldName = null;
1598: myObj.clear();
1599:
1600: StringTokenizer stk = new StringTokenizer(oneLine, "\t");
1601:
1602: for (Iterator e = myObj.getJDBCMetaData().getFieldListArray()
1603: .iterator(); e.hasNext();) {
1604: fieldName = (String) e.next();
1605:
1606: if (!stk.hasMoreTokens()) {
1607: throw new ServerException("Error on line " + lineNumber
1608: + " of import file. No value for field '"
1609: + fieldName + "'");
1610: }
1611:
1612: myObj.setField(fieldName, stk.nextToken());
1613: } /* for each field */
1614:
1615: myObj.add();
1616: } /* importTabLine(String, DBObject, int) */
1617:
1618: /**
1619: * Main method so that DBTool can be launched from a command line
1620: *
1621: * @param args Command line arguments to supply the information to
1622: * connect to the database
1623: */
1624: public static void main(String[] args) {
1625: String myName = (this Class + "main(String[])");
1626: Hashtable commandArgs = new Hashtable(10);
1627: String paramCode = null;
1628: String paramValue = null;
1629:
1630: for (int i = 0; i < args.length; i++) {
1631: StringTokenizer stk = new StringTokenizer(args[i], "=");
1632:
1633: if (!stk.hasMoreTokens()) {
1634: usage();
1635: }
1636:
1637: paramCode = stk.nextToken();
1638:
1639: if (!stk.hasMoreTokens()) {
1640: usage();
1641: }
1642:
1643: paramValue = stk.nextToken();
1644: commandArgs.put(paramCode, paramValue);
1645: } /* for each command-line argument */
1646:
1647: try {
1648: if (commandArgs.get("configDir") == null) {
1649: usage();
1650: System.exit(0);
1651: }
1652:
1653: String logDir = (String) commandArgs.get("logDir");
1654: String logConfig = (String) commandArgs.get("logConfig");
1655: if (logConfig == null) {
1656: logConfig = (String) commandArgs.get("configDir")
1657: + "/expressoLogging.xml";
1658: }
1659:
1660: new LogManager(logConfig, logDir); // todo necessary?
1661:
1662: // set up ConfigManager first
1663: ConfigManager.setWebAppDir((String) commandArgs
1664: .get("webAppDir"));
1665: ConfigManager.load((String) commandArgs.get("configDir"));
1666: //initialize the db pool
1667: ConfigManager.dbInitialize();
1668:
1669: //Load DBOtherMaps
1670: ConfigManager.mapOtherDBs();
1671:
1672: //call the LoadLists method and load up the lists used by this application
1673: dbName = StringUtil.notNull((String) commandArgs.get("db"));
1674:
1675: if (dbName.equals("")) {
1676: dbName = "default";
1677: }
1678:
1679: //Set the permission of the request context.
1680: new MutableRequestRegistry(dbName, SuperUser.SUPER_USER);
1681:
1682: String setup = (String) commandArgs.get("setup");
1683: String poolTest = (String) commandArgs.get("pooltest");
1684: String testMode = (String) commandArgs.get("test");
1685: String generate = (String) commandArgs.get("generate");
1686: String fileName = (String) commandArgs.get("file");
1687: String importCmd = (String) commandArgs.get("import");
1688: String exportCmd = (String) commandArgs.get("export");
1689: String format = (String) commandArgs.get("format");
1690: // String updPassword = (String) commandArgs.get("passwords");
1691: String benchMark = (String) commandArgs.get("bench");
1692: String config = (String) commandArgs.get("config");
1693: String nameChange = (String) commandArgs.get("nameChange");
1694: // String uidChange = (String) commandArgs.get("uidChange");
1695: String schemaPattern = (String) commandArgs
1696: .get("schemaPattern");
1697: String tableNamePattern = (String) commandArgs
1698: .get("tableNamePattern");
1699: String packageName = (String) commandArgs
1700: .get("gen_package");
1701:
1702: if (setup != null) {
1703: setup(dbName);
1704:
1705: System.out.println("Exiting....");
1706: ConfigManager.destroy();
1707: return;
1708: }
1709: if (config != null) {
1710: chooseConfig(dbName);
1711:
1712: System.out.println("Exiting....");
1713: ConfigManager.destroy();
1714: return;
1715: }
1716: if (nameChange != null) {
1717: nameChange(dbName);
1718:
1719: System.out.println("Exiting....");
1720: ConfigManager.destroy();
1721: return;
1722: }
1723: if (benchMark != null) {
1724: doBenchMarks();
1725:
1726: System.out.println("Exiting....");
1727: ConfigManager.destroy();
1728: return;
1729: }
1730: // if (uidChange != null) {
1731: // doUidChange();
1732: //
1733: // return;
1734: // }
1735:
1736: DBConnectionPool myPool = DBConnectionPool
1737: .getInstance(dbName);
1738:
1739: if (poolTest != null) {
1740: System.out
1741: .println("Database Connection Pool Test Mode");
1742: poolTest();
1743: System.out.println("Connection pool tests completed.");
1744: System.exit(1);
1745: }
1746:
1747: DBConnection myConnection = myPool.getConnection("DBTool");
1748:
1749: if (testMode != null) {
1750: System.out
1751: .println("Database/Database Object Test Mode");
1752: testAllSchemas();
1753: System.out.println("All tests completed.");
1754: }
1755: if (generate != null) {
1756: System.out.println("Generate DBObject Mode");
1757:
1758: if ("ALL".equalsIgnoreCase(generate)) {
1759:
1760: //We are generating source files for all database tables.
1761: //Now we call genAllDBOBjects with the schemaPattern and
1762: //tableNamePattern values. If these arguments where not
1763: //given, then they will be passed as nulls with no harm done
1764: //(they will be ignored).
1765: genAllDBObject(myConnection, schemaPattern,
1766: tableNamePattern, dbName, packageName);
1767: } else {
1768: genDBObject(myConnection, generate, dbName,
1769: packageName);
1770: }
1771: }
1772: if (importCmd != null) {
1773: System.out.println("Import Data Mode");
1774:
1775: if (importCmd.equalsIgnoreCase("ALL")) {
1776: importExportAll(myConnection, "import", format);
1777: }
1778: if (fileName == null) {
1779: throw new ServerException(myName
1780: + ":You must supply a "
1781: + "file=xxx argument for import.");
1782: }
1783:
1784: importFile(importCmd, fileName, format, myConnection);
1785: }
1786: if (exportCmd != null) {
1787: System.out.println("Export Data Mode");
1788:
1789: if (exportCmd.equalsIgnoreCase("ALL")) {
1790: importExportAll(myConnection, "export", format);
1791: } else {
1792: if (fileName == null) {
1793: throw new ServerException(myName
1794: + ":You must supply a "
1795: + "file=xxx argument for export.");
1796: }
1797:
1798: exportFile(exportCmd, fileName, format);
1799: }
1800: } /* if export */
1801:
1802: myPool.release(myConnection);
1803: } catch (Exception de) {
1804: System.out.println("DBTool Error:" + de.getMessage());
1805: de.printStackTrace();
1806: System.exit(1);
1807: }
1808: System.out.println("Exiting....");
1809: ConfigManager.destroy();
1810: } /* main(String) */
1811:
1812: /**
1813: * This method returns true if the string contains both upper and lowercase
1814: * letters, false otherwise.
1815: *
1816: * @param stringToCheck The string to check against.
1817: * @return true if the string has mixed case letters in it.
1818: */
1819: private static boolean isMixedCase(String stringToCheck) {
1820: if (stringToCheck == null) {
1821: return false;
1822: }
1823:
1824: char[] cArray = stringToCheck.toCharArray();
1825: boolean hasLowerCase = false;
1826: boolean hasUpperCase = false;
1827:
1828: for (int i = 0; i < cArray.length; i++) {
1829: if (hasLowerCase && hasUpperCase) {
1830: return true;
1831: }
1832: if (Character.isUpperCase(cArray[i])) {
1833: hasUpperCase = true;
1834: }
1835: if (Character.isLowerCase(cArray[i])) {
1836: hasLowerCase = true;
1837: }
1838: }
1839:
1840: return false;
1841: } /* isMixedCase(String) */
1842:
1843: /**
1844: * Creates a Java Class name from a database table name.
1845: * Removes underscore characters and spaces, capitalizes the first
1846: * letter of each word.
1847: *
1848: * @param tableName The tablename to check
1849: * @return java.lang.String The classname to be used.
1850: */
1851: private static String getJavaClassName(String tableName) {
1852: if (tableName == null) {
1853: return "";
1854: }
1855: //if the name is mixed case, we do not transform it.
1856: if (isMixedCase(tableName)) {
1857: return tableName;
1858: }
1859:
1860: StringBuffer nameBuf = new StringBuffer();
1861: StringTokenizer st = new StringTokenizer(tableName, "_ ");
1862:
1863: while (st.hasMoreTokens()) {
1864: nameBuf.append(prepareWord(st.nextToken()));
1865: }
1866:
1867: return nameBuf.toString();
1868: } /* getJavaClassName(String tableName) */
1869:
1870: /**
1871: * prepareWord prepares a single word for use in a Java class name
1872: * by capitalizing the first letter and lowecasing the rest.
1873: *
1874: * @param wordToPrepare the String to processs
1875: * @return the appropriate mixed case word
1876: */
1877: private static String prepareWord(String wordToPrepare) {
1878: String preparedWord = null;
1879:
1880: if (wordToPrepare == null) {
1881: return "";
1882: }
1883: if (wordToPrepare.length() <= 1) {
1884: return wordToPrepare;
1885: }
1886:
1887: //lowercase the word
1888: wordToPrepare = wordToPrepare.toLowerCase();
1889:
1890: //now uppercase the first letter
1891: String firstLetter = wordToPrepare.substring(0, 1);
1892: firstLetter = firstLetter.toUpperCase();
1893: preparedWord = firstLetter + wordToPrepare.substring(1);
1894:
1895: return preparedWord;
1896: } /* prepareWord(String) */
1897:
1898: /**
1899: * Performs the Expresso 3 to Expresso 4 name changes
1900: *
1901: * @param dbName The data context to correct
1902: */
1903: private static void nameChange(String dbName) throws DBException {
1904: System.out.println("Beginning name change update...");
1905:
1906: ControllerSecurity secList = new ControllerSecurity();
1907: secList.setDataContext(dbName);
1908:
1909: String currClass = null;
1910: int updateCount = 0;
1911: ControllerSecurity newSec = null;
1912: String newClass = null;
1913:
1914: List list = secList.searchAndRetrieveList();
1915: for (Iterator iter = list.iterator(); iter.hasNext();) {
1916: ControllerSecurity oneSec = (ControllerSecurity) iter
1917: .next();
1918: currClass = oneSec.getField("ControllerClass");
1919:
1920: if (currClass.indexOf(".trx.") > 0) {
1921: newSec = new ControllerSecurity();
1922: newSec.setDataContext(dbName);
1923: newClass = StringUtil.replace(currClass, ".trx.",
1924: ".controller.");
1925: newSec.setField("GroupName", oneSec
1926: .getField("GroupName"));
1927:
1928: if (!newSec.find()) {
1929: newSec
1930: .setField("States", oneSec
1931: .getField("States"));
1932: newSec.setField("GroupName", oneSec
1933: .getField("GroupName"));
1934: newSec.setField("ControllerClass", newClass);
1935: newSec.add();
1936: }
1937:
1938: oneSec.delete();
1939: updateCount++;
1940: }
1941: }
1942:
1943: System.out.println("\n" + updateCount + " entries changed");
1944: } /* nameChange(String) */
1945:
1946: private static void poolTest() {
1947: throw new java.lang.UnsupportedOperationException(
1948: "pool test has been "
1949: + "moved to it's own junit test suite in "
1950: + "com.jcorporate.expresso.core.db.tests");
1951: } /* poolTest() */
1952:
1953: /**
1954: * Command line setup
1955: *
1956: * @param dbName The data context to use
1957: * @throws ConfigurationException if we're working with a data context
1958: * that does not exist in the config files.
1959: */
1960: private static void setup(String dbName) throws DBException,
1961: ConfigurationException {
1962: System.out.println("Beginning system setup...");
1963:
1964: if (StringUtil.notNull(dbName).equals("")) {
1965: dbName = "default";
1966: }
1967:
1968: Vector allSchemas = new Vector(5);
1969: ExpressoSchema jcs = new ExpressoSchema();
1970: allSchemas.addElement(jcs);
1971:
1972: SchemaList sl = null;
1973: SchemaList oneSchema = null;
1974: boolean noOtherSchemas = true;
1975:
1976: try {
1977: sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
1978: sl.setDataContext(dbName);
1979:
1980: if (sl.count() > 0) {
1981: noOtherSchemas = false;
1982: }
1983: } catch (DBException de) {
1984: noOtherSchemas = true;
1985: }
1986: if (!noOtherSchemas) {
1987:
1988: List list = sl.searchAndRetrieveList();
1989: for (Iterator iterator = list.iterator(); iterator
1990: .hasNext();) {
1991: oneSchema = (SchemaList) iterator.next();
1992:
1993: boolean schemaWarning = false;
1994:
1995: Schema mySchema2 = SchemaFactory.getInstance()
1996: .getSchema(oneSchema.getField("SchemaClass"));
1997: if (mySchema2 != null) {
1998: allSchemas.addElement(mySchema2);
1999: System.out.println("Adding Schema "
2000: + oneSchema.getField("SchemaClass"));
2001: } else {
2002: schemaWarning = true;
2003: }
2004: if (schemaWarning) {
2005: System.err
2006: .println("Warning: Unable to process schema "
2007: + oneSchema.getField("SchemaClass")
2008: + " - see log for details");
2009: }
2010: }
2011:
2012: } /* if we read other schemas */
2013:
2014: com.jcorporate.expresso.kernel.InstallLog installLog = new com.jcorporate.expresso.kernel.ConsoleInstallLog();
2015:
2016: System.out.println("Creating tables...");
2017: createTables(installLog, allSchemas, dbName);
2018: System.out.println("Comaring tables...");
2019: compareTables(installLog, allSchemas, dbName);
2020: System.out.println("Setting up security...");
2021: setupSecurity(installLog, allSchemas, dbName);
2022: System.out.println("Populating default values...");
2023: populateTables(installLog, allSchemas, dbName);
2024: System.out.println("Other setup functions...");
2025: otherSetups(installLog, allSchemas, dbName);
2026: Setup.setTableExists(dbName);
2027: ConfigManager.initializeAllDBObjects();
2028: System.out.println("\nAll setups complete");
2029: } /* setup(String) */
2030:
2031: /**
2032: * Instantiate & load all Schema objects that we know about,
2033: * get a list of their DBObjects, and call the verify() method
2034: * of each DBObject
2035: */
2036: private static void testAllSchemas() throws DBException {
2037: System.out.println("Begin schema tests:"
2038: + DateTime.getDateTimeString());
2039:
2040: Vector allSchemas = new Vector(5);
2041: {
2042: ExpressoSchema jcs = new ExpressoSchema();
2043: allSchemas.addElement(jcs);
2044:
2045: SchemaList sl = new SchemaList(
2046: SecuredDBObject.SYSTEM_ACCOUNT);
2047:
2048: List list = sl.searchAndRetrieveList();
2049: for (Iterator iterator = list.iterator(); iterator
2050: .hasNext();) {
2051: SchemaList oneSchema = (SchemaList) iterator.next();
2052:
2053: Schema mySchema2 = SchemaFactory.getInstance()
2054: .getSchema(oneSchema.getField("SchemaClass"));
2055: if (mySchema2 != null) {
2056: allSchemas.addElement(mySchema2);
2057: }
2058: }
2059: }
2060:
2061: System.out.println("Loaded " + allSchemas.size()
2062: + " schema objects.");
2063:
2064: Schema this Schema = null;
2065:
2066: for (Enumeration als = allSchemas.elements(); als
2067: .hasMoreElements();) {
2068: this Schema = (Schema) als.nextElement();
2069: System.out.println("Verifying Schema "
2070: + this Schema.getClass().getName());
2071:
2072: DBObject oneObject = null;
2073:
2074: for (Enumeration dbo = this Schema.getMembers(); dbo
2075: .hasMoreElements();) {
2076: oneObject = (DBObject) dbo.nextElement();
2077: System.out.println("Verifying database object "
2078: + oneObject.getJDBCMetaData().getName() + " ("
2079: + oneObject.getJDBCMetaData().getDescription()
2080: + ")");
2081:
2082: //oneObject.setConnection(myConnection);
2083: try {
2084: oneObject.verify();
2085: } catch (DBException de) {
2086: System.out.println("Error in object "
2087: + oneObject.getJDBCMetaData().getName()
2088: + ":" + de.getMessage());
2089: de.printStackTrace();
2090: }
2091: } /* for each database object */
2092:
2093: } /* for each schema in the list */
2094:
2095: System.out.println("End schema tests:"
2096: + DateTime.getDateTimeString());
2097: } /* testAllSchemas(DBConnection) */
2098:
2099: /**
2100: * Show the user a usage message
2101: */
2102: private static void usage() {
2103: System.out
2104: .println("Usage: DBTool configDir=directory "
2105: + "webAppDir=webdir [logDir=directory] [logConfig=file] [db=dbname] [arg=value] ... ");
2106: System.out
2107: .println("Where 'directory' is the directory containing "
2108: + "the expresso configuration files (if any)");
2109: System.out
2110: .println("\tand webdir is the directory in which this web "
2111: + "application is installed, if used as a web-application");
2112: System.out
2113: .println("\tand dbname is the name of the db/context to use "
2114: + "- 'default' is used if no dbname argument is specified");
2115: System.out.println(" ");
2116: System.out.println("Optional arguments:");
2117: System.out.println("\tsetup=yes: Initial system setup");
2118: System.out
2119: .println("\tconfig=yes: Enter/edit Setup/configuration "
2120: + "values");
2121: System.out.println("\ttest=yes: Invoke test mode");
2122: System.out
2123: .println("\tgenerate=dbobjname: Generate database object "
2124: + "source code from named table in the database. Use 'all' to "
2125: + "generate source code for every table in the database.");
2126: System.out
2127: .println("\tschemaPattern=schema pattern string: Add a "
2128: + "schema pattern using JDBC wildcards to match SQL schemas. Only "
2129: + "applicable when used with generate=all. Omit if you want all tables in all schemas.");
2130: System.out
2131: .println("\ttableNamePattern=table name pattern String: Add a "
2132: + "pattern using JDBC wildcards to match table names. Only applicable "
2133: + "when used with generate=all. Omit if you want all tables in all tables.");
2134: System.out
2135: .println("\timport=dbobjname: Import data into named database"
2136: + " object, use 'all' to import into all known database objects "
2137: + "for which files exist.");
2138: System.out
2139: .println("\tfile=filename: File name to import from/export "
2140: + "to. Not required if 'all' is used for the import parameter.");
2141: System.out
2142: .println("\tformat=formatCode: Format for import/export. "
2143: + "Options are xml, tab");
2144: System.out
2145: .println("\tgen_package=com.whatever: package name for generated"
2146: + " java files. Only applicable when generating.");
2147:
2148: System.out.println("\tbench=yes: Run benchmarks");
2149: System.exit(1);
2150: } /* usage() */
2151:
2152: /**
2153: * Create the tables required by the database objects in the list
2154: * of schemas.
2155: * Each database object knows how to create the database table it
2156: * requires - this
2157: * method goes through the list
2158: * of registered schemas and calls the create method for all of the
2159: * database objects in the schema. If the table is already there,
2160: * nothing is done.
2161: *
2162: * @param theLog The installLog object. Use ConsoleInstallLog if you
2163: * don't know what this does.
2164: * @param allSchemas List of the schema objects
2165: * @param dataContext The database context to create the database in.
2166: * @throws DBException If there is a problem creating the tables
2167: */
2168: public static synchronized void createTables(InstallLog theLog,
2169: Vector allSchemas, String dataContext) throws DBException {
2170:
2171: theLog.info(Messages.getString("Creating_Tables_for_databa")
2172: + " '" + dataContext + "'");
2173: TableCreator tc = TableCreator.getInstance();
2174: for (Enumeration e = allSchemas.elements(); e.hasMoreElements();) {
2175: Schema oneSchema = (Schema) e.nextElement();
2176: Vector v = tc.createAsNeeded(oneSchema, dataContext);
2177:
2178: if (v.size() > 0) {
2179: String oneTableName = null;
2180:
2181: for (Enumeration et = v.elements(); et
2182: .hasMoreElements();) {
2183: oneTableName = (String) et.nextElement();
2184:
2185: theLog.info(Messages.getString("Created_table_")
2186: + " " + oneTableName);
2187: }
2188:
2189: theLog.info("Schema " + oneSchema.getClass().getName()
2190: + " " + Messages.getString("__Created_") + " "
2191: + v.size() + " "
2192: + Messages.getString("_tables_in_database"));
2193: } else {
2194: theLog
2195: .info(Messages.getString("Schema_")
2196: + " "
2197: + oneSchema.getClass().getName()
2198: + " "
2199: + Messages
2200: .getString("_Tables_are_all_already_in"));
2201: }
2202:
2203: DBConnectionPool.reInitialize();
2204: } /* for each schema */
2205:
2206: } /* createTables(PrintWriter, Vector, String) */
2207:
2208: /**
2209: * Method to perform any other additonal setup required by each
2210: * schema
2211: *
2212: * @param theLog InstallLog object to save the data to
2213: * @param allSchemas List of the schema objects
2214: * @param dbName The database context to create the database in.
2215: * @throws DBException If there is a database problem creating
2216: * the new default values
2217: */
2218: public static synchronized void otherSetups(InstallLog theLog,
2219: Vector allSchemas, String dbName) throws DBException {
2220: Schema oneSchema = null;
2221:
2222: for (Enumeration e = allSchemas.elements(); e.hasMoreElements();) {
2223: oneSchema = (Schema) e.nextElement();
2224:
2225: theLog.info(Messages.getString("Additional_setup_on_")
2226: + " " + oneSchema.getClass().getName());
2227:
2228: oneSchema.otherSetup(theLog, dbName);
2229:
2230: /*
2231: call to Schema.otherSetup(String) until that method is removed after deprecation.
2232: This otherSetup(String)
2233: was previously called indirectly by a deprecated method, now removed.
2234: The problem is that Schema.otherSetup(String) was not itself
2235: deprecated previously (it now is), so end users did not have a
2236: notification to move away in previous releases.
2237: */
2238: oneSchema.otherSetup(dbName);
2239: }
2240:
2241: theLog.info(Messages.getString("All_Additional_Setup_funct"));
2242: System.gc();
2243: } /* otherSetups(PrintWriter, Vector, String) */
2244:
2245: /**
2246: * This method goes through the schemas and populates tables with default values
2247: * if they do not exist. Works closely with
2248: *
2249: * @param installLog The InstallLog to save the output traces to
2250: * @param allSchemas List of the schema objects
2251: * @param dbName The database context to create the database in.
2252: * @throws DBException If a problem occurrs putting the default records
2253: * in the database
2254: */
2255: public static synchronized void populateTables(
2256: InstallLog installLog, Vector allSchemas, String dbName)
2257: throws DBException {
2258: Schema oneSchema = null;
2259: Vector errors = new Vector();
2260:
2261: for (Enumeration e = allSchemas.elements(); e.hasMoreElements();) {
2262: oneSchema = (Schema) e.nextElement();
2263:
2264: installLog.info("Populate Tables on "
2265: + oneSchema.getClass().getName());
2266: try {
2267: oneSchema.setupDefaultValuesWithException(dbName);
2268: } catch (DBException de) {
2269: log.error(de);
2270: de.printStackTrace(System.err);
2271: errors.addElement(de);
2272: }
2273:
2274: installLog.info("Adding Default Cache Settings on "
2275: + oneSchema.getClass().getName());
2276: //
2277: //Setup cache settings for all the dbobjects.
2278: //
2279: DBObjLimit cacheSettings = new DBObjLimit(
2280: Securable.SYSTEM_ACCOUNT);
2281: cacheSettings.setDataContext(dbName);
2282: for (Enumeration dbobjects = oneSchema.getMembers(); dbobjects
2283: .hasMoreElements();) {
2284: DBObject oneObj = (DBObject) dbobjects.nextElement();
2285: cacheSettings.setField("DBObjectName", oneObj
2286: .getClass().getName());
2287: cacheSettings.setField("PageLimit", 50);
2288: cacheSettings.setField("CacheSize", 50);
2289: cacheSettings.setField("TTL", 10);
2290: cacheSettings.addIfNeeded();
2291: }
2292: }
2293:
2294: if (errors.size() > 0) {
2295: installLog
2296: .warn(""
2297: + errors.size()
2298: + " error(s) were encountered when populating defaults:");
2299:
2300: Throwable oneException = null;
2301:
2302: for (Enumeration ee = errors.elements(); ee
2303: .hasMoreElements();) {
2304: oneException = (Throwable) ee.nextElement();
2305: installLog
2306: .error("Populate Default Error", oneException);
2307: }
2308: }
2309: installLog
2310: .info("All Additional Table Populations have been performed.");
2311:
2312: setupConfig(installLog, allSchemas, dbName);
2313: } /* populateTables(PrintWriter, Vector, String) */
2314:
2315: /**
2316: * Method to set up the default Setup values for each schema.
2317: * Every schema object has a list of the Setup values and default
2318: * values for them that are required by the application that the
2319: * schema applies to. The default schema is done first, then
2320: * any other registered schema objects
2321: *
2322: * @param installLog - The installation log to log output to
2323: * @param allSchemas A list of all of the schema objects
2324: * @param dbName The database context to setup the config in.
2325: * @throws DBException If there is a database problem creating
2326: * the new default values
2327: */
2328: public static synchronized void setupConfig(InstallLog installLog,
2329: Vector allSchemas, String dbName) throws DBException {
2330: Schema oneSchema = null;
2331: Setup oneSetup = null;
2332: Setup findSetup = null;
2333:
2334: for (Enumeration e = allSchemas.elements(); e.hasMoreElements();) {
2335: oneSchema = (Schema) e.nextElement();
2336:
2337: for (Enumeration rl = oneSchema.getConfig().elements(); rl
2338: .hasMoreElements();) {
2339: oneSetup = (Setup) rl.nextElement();
2340: oneSetup.setDataContext(dbName);
2341: findSetup = new Setup();
2342: findSetup.setDataContext(dbName);
2343: findSetup.clear();
2344: findSetup.setField("SetupCode", oneSetup
2345: .getField("SetupCode"));
2346: findSetup.setField("SchemaClass", oneSetup
2347: .getField("SchemaClass"));
2348:
2349: if (!findSetup.find()) {
2350: oneSetup.setDataContext(dbName);
2351: oneSetup.add();
2352:
2353: installLog.info(Messages
2354: .getString("Added_default_config_")
2355: + " "
2356: + Messages.getString("value_for_")
2357: + " " + oneSetup.getField("SetupCode"));
2358: }
2359: }
2360: }
2361: installLog.info(Messages
2362: .getString("All_Setup/Configuration_Va")
2363: + " " + Messages.getString("are_set_up."));
2364:
2365: Setup.setTableExists(dbName);
2366: System.gc();
2367: } /* setupConfig(PrintWriter, Vector, String) */
2368:
2369: /**
2370: * This method creates default security entries for all of the
2371: * database objects and controller objects for the known schemas.
2372: * This includes full access for a group and user called User.ADMIN_USER
2373: *
2374: * @param theLog Installation Log
2375: * @param allSchemas List of the schema objects
2376: * @param dbName The database context to create the database in.
2377: * @throws DBException If a problem occurrs putting the security info
2378: * in the database
2379: */
2380: public static synchronized void setupSecurity(InstallLog theLog,
2381: Vector allSchemas, String dbName) throws DBException {
2382: /* Group 'Everybody' */
2383: UserGroup oneGroup = new UserGroup();
2384: oneGroup.setDataContext(dbName);
2385: oneGroup.setGroupName(UserGroup.ALL_USERS_GROUP);
2386:
2387: if (!oneGroup.find()) {
2388: oneGroup.setField(UserGroup.GROUP_DESCRIPTION, Messages
2389: .getString("All_Users"));
2390: oneGroup.add();
2391: }
2392:
2393: /* Group 'Nobody' */
2394: oneGroup.clear();
2395: oneGroup.setGroupName(UserGroup.UNKNOWN_USERS_GROUP);
2396: if (!oneGroup.find()) {
2397: oneGroup.setField(UserGroup.GROUP_DESCRIPTION, Messages
2398: .getString("Unknown_Users"));
2399: oneGroup.add();
2400: }
2401:
2402: /* Group 'NotReg' */
2403: oneGroup.clear();
2404: oneGroup.setGroupName(UserGroup.NOT_REG_USERS_GROUP);
2405:
2406: if (!oneGroup.find()) {
2407: oneGroup.setField(UserGroup.GROUP_DESCRIPTION, Messages
2408: .getString("NotReg_Users"));
2409: oneGroup.add();
2410: }
2411:
2412: /* Group 'Admin' */
2413: oneGroup.clear();
2414: oneGroup.setGroupName(UserGroup.ADMIN_GROUP);
2415: if (!oneGroup.find()) {
2416: oneGroup.setField(UserGroup.GROUP_DESCRIPTION, Messages
2417: .getString("Administrative_Users"));
2418: oneGroup.add();
2419:
2420: theLog.info(Messages.getString("Added_'Admin'_user_group")
2421: + " ");
2422: }
2423:
2424: //
2425: //Now create the registration domains.
2426: //
2427: RegistrationDomain rd = new RegistrationDomain();
2428: rd.setDataContext(dbName);
2429: rd.setField("Name", "default");
2430:
2431: if (!rd.find()) {
2432: rd.setField("Description", "Default Registration Domain");
2433: rd.setField("RegRequired", "Y");
2434: rd.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2435: rd
2436: .setField(
2437: "ControllerClass",
2438: com.jcorporate.expresso.services.controller.SimpleRegistration.class
2439: .getName());
2440: rd.setField("RegRequired", "N");
2441: rd.setField("Approve", "N");
2442: rd.setField("UserPasswd", "Y");
2443: rd.setField("EmailValidate", "N");
2444: rd.setField("EmailAsLogin", "N");
2445: rd.add();
2446: }
2447:
2448: RegistrationObjectMap rdm = new RegistrationObjectMap();
2449: rdm.setDataContext(dbName);
2450: rdm.setField("RegDomId", rd.getField("RegDomId"));
2451: rdm.setField("RegObj",
2452: com.jcorporate.expresso.ext.dbobj.RegisteredUser.class
2453: .getName());
2454:
2455: if (!rdm.find()) {
2456: rdm.setField("UidField", "ExpUid");
2457: rdm.setField("RecMin", "1");
2458: rdm.setField("RecMax", "1");
2459: rdm.setField("AllowEdit", "Y");
2460: rdm.setField("AllowDel", "N");
2461: rdm.setField("RegFields", "!IsActive" + ",!UserName"
2462: + ",!InternalComment" + ",!AddedOn" + ",!UpdatedOn"
2463: + ",!URL" + ",!EmailPrivate" + ",!Occupation"
2464: + ",!Location" + ",!Expertise" + ",!OtherProjects"
2465: + ",!Contributions" + ",!Phone" + ",!Testimonial"
2466: + ",!IPAddress");
2467: rdm.add();
2468: }
2469:
2470: rd.clear();
2471: rd.setField("Name", "extended");
2472:
2473: if (!rd.find()) {
2474: rd.setField("Description", "Extended Registration Domain");
2475: rd.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2476: rd
2477: .setField(
2478: "ControllerClass",
2479: com.jcorporate.expresso.services.controller.Registration.class
2480: .getName());
2481: rd.setField("RegRequired", "Y");
2482: rd.setField("Approve", "N");
2483: rd.setField("UserPasswd", "Y");
2484: rd.setField("EmailValidate", "Y");
2485: rd.setField("EmailAsLogin", "N");
2486: rd.add();
2487: }
2488:
2489: rdm.clear();
2490: rdm.setField("RegDomId", rd.getField("RegDomId"));
2491: rdm.setField("RegObj",
2492: com.jcorporate.expresso.ext.dbobj.regobj.Person.class
2493: .getName());
2494:
2495: if (!rdm.find()) {
2496: rdm.setField("UidField", "ExpUid");
2497: rdm.setField("RecMin", "1");
2498: rdm.setField("RecMax", "1");
2499: rdm.setField("AllowEdit", "Y");
2500: rdm.setField("AllowDel", "N");
2501: rdm.setField("RegFields", "!ExpUid,!AddedOn,!UpdatedOn");
2502: rdm.add();
2503: }
2504:
2505: rdm.clear();
2506: rdm.setField("RegDomId", rd.getField("RegDomId"));
2507: rdm.setField("RegObj",
2508: com.jcorporate.expresso.ext.dbobj.regobj.Phone.class
2509: .getName());
2510:
2511: if (!rdm.find()) {
2512: rdm.setField("UidField", "ExpUid");
2513: rdm.setField("RecMin", "1");
2514: rdm.setField("RecMax", "0");
2515: rdm.setField("AllowEdit", "Y");
2516: rdm.setField("AllowDel", "N");
2517: rdm.setField("RegFields",
2518: "!PhoneId,!ExpUid,!AddedOn,!UpdatedOn,+Type");
2519: rdm.add();
2520: }
2521:
2522: rdm.clear();
2523: rdm.setField("RegDomId", rd.getField("RegDomId"));
2524: rdm.setField("RegObj",
2525: com.jcorporate.expresso.ext.dbobj.regobj.Address.class
2526: .getName());
2527:
2528: if (!rdm.find()) {
2529: rdm.setField("UidField", "ExpUid");
2530: rdm.setField("RecMin", "1");
2531: rdm.setField("RecMax", "1");
2532: rdm.setField("AllowEdit", "Y");
2533: rdm.setField("AllowDel", "N");
2534: rdm.setField("RegFields",
2535: "!AddressId,!ExpUid,!AddedOn,!UpdatedOn");
2536: rdm.add();
2537: }
2538:
2539: rdm.clear();
2540: rdm.setField("RegDomId", rd.getField("RegDomId"));
2541: rdm.setField("RegObj",
2542: com.jcorporate.expresso.ext.dbobj.regobj.Contact.class
2543: .getName());
2544:
2545: if (!rdm.find()) {
2546: rdm.setField("UidField", "ExpUid");
2547: rdm.setField("RecMin", "0");
2548: rdm.setField("RecMax", "0");
2549: rdm.setField("AllowEdit", "Y");
2550: rdm.setField("AllowDel", "N");
2551: rdm.setField("RegFields",
2552: "!ContactId,!ExpUid,!AddedOn,!UpdatedOn,+Type");
2553: rdm.add();
2554: }
2555:
2556: //
2557: //Add the default users to the system
2558: //
2559: User oneUser = new User();
2560: oneUser.setDataContext(dbName);
2561: oneUser.setLoginName("Anonymous"); //$NON-NLS-2$//$NON-NLS-1$
2562:
2563: if (!oneUser.find()) {
2564: oneUser
2565: .setDisplayName(Messages
2566: .getString("Anonymous_User"));
2567: oneUser.setEmail("none"); //$NON-NLS-2$//$NON-NLS-1$
2568: oneUser.setAccountStatus("D");
2569: oneUser.add();
2570:
2571: theLog.info(Messages.getString("Added_'Anonymous'_user")
2572: + " ");
2573:
2574: GroupMembers oneMember = new GroupMembers();
2575: oneMember.setDataContext(dbName);
2576: oneMember.setField("GroupName", UserGroup.ALL_USERS_GROUP);
2577: oneMember.setField("ExpUid", oneUser.getUid());
2578:
2579: if (!oneMember.find()) {
2580: oneMember.add();
2581:
2582: theLog.info(Messages
2583: .getString("Added_'Anonymous'_user_")
2584: + " "
2585: + Messages
2586: .getString("to_the_group_'Everybody'"));
2587: }
2588: } /* if we didn't find the Anonymous user */
2589:
2590: oneUser.clear();
2591: oneUser.setLoginName(User.UNKNOWN_USER);
2592:
2593: if (!oneUser.find()) {
2594: oneUser.setDisplayName(Messages
2595: .getString("Default_user_before_login"));
2596: oneUser.setEmail("none");
2597: oneUser.setAccountStatus("D");
2598: oneUser.add();
2599:
2600: theLog.info(Messages.getString("Added_'NONE'_user_") + " ");
2601: }
2602:
2603: GroupMembers oneMember = new GroupMembers();
2604: oneMember.setDataContext(dbName);
2605: oneMember.setField("GroupName", UserGroup.UNKNOWN_USERS_GROUP);
2606: oneMember.setField("ExpUid", oneUser.getUid());
2607:
2608: if (!oneMember.find()) {
2609: oneMember.add();
2610:
2611: theLog.info(Messages
2612: .getString("Added_NONE'_user_to_the_'N")
2613: + " ");
2614: }
2615:
2616: oneUser.clear();
2617: oneUser.setLoginName(User.ADMIN_USER);
2618:
2619: if (!oneUser.find()) {
2620: oneUser.setDisplayName(Messages
2621: .getString("Administrative_User"));
2622: oneUser.setEmail("none");
2623: oneUser.setAccountStatus("A");
2624: oneUser.add();
2625:
2626: theLog.info(Messages
2627: .getString("Added_'Admin'_user_-_SET_A")
2628: + " ");
2629: }
2630:
2631: oneMember.clear();
2632: oneMember.setField("GroupName", User.ADMIN_USER);
2633: oneMember.setField("ExpUid", oneUser.getUid());
2634:
2635: if (!oneMember.find()) {
2636: oneMember.add();
2637:
2638: theLog.info(Messages
2639: .getString("Added_'Admin'_user_to_the_")
2640: + " ");
2641: }
2642:
2643: //
2644: //Set up default DBObject Security
2645: //
2646: DBObjSecurity oneSecurity = new DBObjSecurity();
2647: oneSecurity.setDataContext(dbName);
2648:
2649: DBObject oneObj = null;
2650: Schema oneSchema = null;
2651:
2652: for (Enumeration sl = allSchemas.elements(); sl
2653: .hasMoreElements();) {
2654: oneSchema = (Schema) sl.nextElement();
2655:
2656: for (Enumeration ee = oneSchema.getMembers(); ee
2657: .hasMoreElements();) {
2658:
2659: oneObj = (DBObject) ee.nextElement();
2660: oneSecurity.setField("GroupName", User.ADMIN_USER);
2661:
2662: //$NON-NLS-2$//$NON-NLS-1$
2663: oneSecurity.setField("DBObjectName", oneObj.getClass()
2664: .getName());
2665:
2666: //$NON-NLS-1$
2667: oneSecurity.setField("MethodCode", "A");
2668:
2669: //$NON-NLS-2$//$NON-NLS-1$
2670: if (!oneSecurity.find()) {
2671: oneSecurity.add();
2672:
2673: theLog
2674: .info(Messages
2675: .getString("Added_permission_for_")
2676: + " "
2677: + Messages
2678: .getString("'Admin'_group_to_add_new_e")
2679: + " " + oneObj.getClass().getName());
2680: }
2681:
2682: oneSecurity.setField("MethodCode", "U"); //$NON-NLS-2$//$NON-NLS-1$
2683:
2684: if (!oneSecurity.find()) {
2685: oneSecurity.add();
2686:
2687: theLog
2688: .info(Messages
2689: .getString("Added_permission_for_")
2690: + " "
2691: + Messages
2692: .getString("'Admin'_group_to_update_en")
2693: + " " + oneObj.getClass().getName());
2694: }
2695:
2696: oneSecurity.setField("MethodCode", "S"); //$NON-NLS-2$//$NON-NLS-1$
2697:
2698: if (!oneSecurity.find()) {
2699: oneSecurity.add();
2700:
2701: theLog
2702: .info(Messages
2703: .getString("Added_permission_for_")
2704: + " "
2705: + Messages
2706: .getString("'Admin'_group_to_search_on")
2707: + " " + oneObj.getClass().getName());
2708: }
2709:
2710: oneSecurity.setField("MethodCode", "D"); //$NON-NLS-2$//$NON-NLS-1$
2711:
2712: if (!oneSecurity.find()) {
2713: oneSecurity.add();
2714:
2715: theLog
2716: .info(Messages
2717: .getString("Added_permission_for_")
2718: + " "
2719: + Messages
2720: .getString("'Admin'_group_to_delete_fr")
2721: + " '"
2722: + oneObj.getClass().getName() + "'");
2723: }
2724: } /* for every object in the schema */
2725:
2726: Controller con;
2727: ControllerSecurity oneControllerSecurity = new ControllerSecurity(
2728: SecuredDBObject.SYSTEM_ACCOUNT);
2729: oneControllerSecurity.setDataContext(dbName);
2730:
2731: //
2732: //Setup default controller access.
2733: //
2734: for (Iterator et = oneSchema.getControllerList().iterator(); et
2735: .hasNext();) {
2736: con = (Controller) et.next();
2737: oneControllerSecurity.clear();
2738: oneControllerSecurity.setField("ControllerClass", con
2739: .getClass().getName());
2740: oneControllerSecurity.setField("GroupName",
2741: User.ADMIN_USER);
2742: oneControllerSecurity.setField("States", "*");
2743:
2744: if (!oneControllerSecurity.find()) {
2745: theLog
2746: .info(Messages
2747: .getString("Adding_access_to_")
2748: + " "
2749: + Messages
2750: .getString("all_states_of_Controller_")
2751: + " '" + con.getTitle() + "'");
2752: oneControllerSecurity.add();
2753: }
2754:
2755: //
2756: //Special cases in login controller some states should be
2757: //enabled by default.
2758: //
2759: if (con instanceof com.jcorporate.expresso.services.controller.LoginController) {
2760: oneControllerSecurity.clear();
2761: oneControllerSecurity.setField("ControllerClass",
2762: con.getClass().getName());
2763: oneControllerSecurity.setField("GroupName",
2764: UserGroup.ALL_USERS_GROUP);
2765: oneControllerSecurity.setField("States", "*");
2766:
2767: if (!oneControllerSecurity.find()) {
2768: theLog
2769: .info("Adding general access to Login controller");
2770: oneControllerSecurity.add();
2771: }
2772:
2773: oneControllerSecurity.clear();
2774: oneControllerSecurity.setField("ControllerClass",
2775: con.getClass().getName());
2776: oneControllerSecurity.setField("GroupName",
2777: UserGroup.UNKNOWN_USERS_GROUP);
2778: oneControllerSecurity
2779: .setField(
2780: "States",
2781: "promptLogin,processLogin,"
2782: + "emailValidate,promptSendPassword,processSendPassword,processRevalidate");
2783:
2784: if (!oneControllerSecurity.find()) {
2785: theLog.info("Adding default anonymous "
2786: + "access to Login controller");
2787: oneControllerSecurity.add();
2788: }
2789:
2790: } /* special case for login controller */
2791:
2792: //
2793: //Special case for registration controller
2794: //
2795: if (con instanceof com.jcorporate.expresso.services.controller.Registration) {
2796: oneControllerSecurity.clear();
2797: oneControllerSecurity.setField("ControllerClass",
2798: con.getClass().getName());
2799: oneControllerSecurity.setField("GroupName",
2800: UserGroup.ALL_USERS_GROUP);
2801: oneControllerSecurity
2802: .setField(
2803: "States",
2804: "showDBMenu,emailValidate,"
2805: + "promptSelfRegister,processSelfRegister,promptAddRecord,"
2806: + "processAddRecord,promptUpdateRecord,"
2807: + "processUpdateRecord,promptDeleteRecord,"
2808: + "processDeleteRecord,processListRecords,processRevalidate");
2809:
2810: if (!oneControllerSecurity.find()) {
2811: theLog.info("Adding general "
2812: + "access to Registration controller");
2813:
2814: oneControllerSecurity.add();
2815: }
2816:
2817: oneControllerSecurity.clear();
2818: oneControllerSecurity.setField("ControllerClass",
2819: con.getClass().getName());
2820: oneControllerSecurity.setField("GroupName",
2821: UserGroup.UNKNOWN_USERS_GROUP);
2822: oneControllerSecurity
2823: .setField(
2824: "States",
2825: "showDBMenu,emailValidate,"
2826: + "promptSelfRegister,processSelfRegister,processRevalidate");
2827:
2828: if (!oneControllerSecurity.find()) {
2829: theLog.info("Adding default anonymous "
2830: + "access to Registration controller");
2831:
2832: oneControllerSecurity.add();
2833: }
2834:
2835: }
2836:
2837: } /* for each controller */
2838:
2839: StdServlet oneServlet;
2840:
2841: //
2842: //Set up the servlet Security
2843: //
2844: for (Enumeration es = oneSchema.getServlets(); es
2845: .hasMoreElements();) {
2846: oneServlet = (StdServlet) es.nextElement();
2847: oneControllerSecurity.clear();
2848: oneControllerSecurity.setField("ControllerClass",
2849: oneServlet.getClass().getName());
2850: oneControllerSecurity.setField("GroupName",
2851: User.ADMIN_USER);
2852:
2853: //$NON-NLS-2$//$NON-NLS-1$
2854: oneControllerSecurity.setField("States", "*");
2855:
2856: //$NON-NLS-2$//$NON-NLS-1$
2857: if (!oneControllerSecurity.find()) {
2858: theLog.info(Messages.getString("Adding_access_to_")
2859: + Messages.getString("Servlet_'") + " '"
2860: + oneServlet.getTitle() + "'");
2861:
2862: oneControllerSecurity.add();
2863: }
2864: } /* for each servlet */
2865:
2866: //
2867: //Set up the default Job security
2868: //
2869: Job j;
2870: JobSecurity oneJobSecurity = new JobSecurity(
2871: SecuredDBObject.SYSTEM_ACCOUNT); //$NON-NLS-1$
2872: oneJobSecurity.setDataContext(dbName);
2873:
2874: for (Enumeration ej = oneSchema.getJobs(); ej
2875: .hasMoreElements();) {
2876: j = (Job) ej.nextElement();
2877: oneJobSecurity.clear();
2878: oneJobSecurity.setField("JobClass", j.getClass()
2879: .getName());
2880:
2881: //$NON-NLS-1$
2882: oneJobSecurity.setField("GroupName", User.ADMIN_USER);
2883:
2884: //$NON-NLS-2$//$NON-NLS-1$
2885: oneJobSecurity.setField("Functions", "*");
2886:
2887: //$NON-NLS-2$//$NON-NLS-1$
2888: if (!oneJobSecurity.find()) {
2889: theLog
2890: .info(Messages
2891: .getString("Adding_access_to_")
2892: + " "
2893: + Messages
2894: .getString("all_functions_of_Job_'")
2895: + " '" + j.getTitle() + "'");
2896: oneJobSecurity.add();
2897: } /* if job security not found */
2898:
2899: } /* for each job*/
2900:
2901: } /* for each schema */
2902:
2903: theLog.info(Messages.getString("Security_Checks_Complete"));
2904: } /* setupSecurity(PrintWriter, Vector, String) */
2905:
2906: } /* DBTool */
|