KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > services > servlet > DBCreate


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

64
65 /**
66  * DBCreate.java
67  *
68  * Copyright 1999, 2000, 2001 Jcorporate Ltd.
69  */

70 package com.jcorporate.expresso.services.servlet;
71
72 import com.jcorporate.expresso.core.ExpressoSchema;
73 import com.jcorporate.expresso.core.db.DBException;
74 import com.jcorporate.expresso.core.dbobj.Schema;
75 import com.jcorporate.expresso.core.dbobj.SchemaFactory;
76 import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
77 import com.jcorporate.expresso.core.jsdkapi.GenericSession;
78 import com.jcorporate.expresso.core.misc.ConfigManager;
79 import com.jcorporate.expresso.core.misc.ConfigurationException;
80 import com.jcorporate.expresso.core.misc.CurrentLogin;
81 import com.jcorporate.expresso.core.misc.StringUtil;
82 import com.jcorporate.expresso.core.security.User;
83 import com.jcorporate.expresso.core.servlet.DBServlet;
84 import com.jcorporate.expresso.core.servlet.ServletInstallLog;
85 import com.jcorporate.expresso.core.utility.DBTool;
86 import com.jcorporate.expresso.services.dbobj.SchemaList;
87 import com.jcorporate.expresso.services.html.Button;
88 import com.jcorporate.expresso.services.html.Cell;
89 import com.jcorporate.expresso.services.html.CheckBox;
90 import com.jcorporate.expresso.services.html.DropDown;
91 import com.jcorporate.expresso.services.html.Form;
92 import com.jcorporate.expresso.services.html.HiddenField;
93 import com.jcorporate.expresso.services.html.Page;
94 import com.jcorporate.expresso.services.html.Paragraph;
95 import com.jcorporate.expresso.services.html.Row;
96 import com.jcorporate.expresso.services.html.Table;
97 import com.jcorporate.expresso.services.html.Text;
98 import org.apache.log4j.Logger;
99
100 import javax.servlet.ServletConfig JavaDoc;
101 import javax.servlet.ServletException JavaDoc;
102 import javax.servlet.http.HttpServletRequest JavaDoc;
103 import javax.servlet.http.HttpServletResponse JavaDoc;
104 import java.io.IOException JavaDoc;
105 import java.util.Enumeration JavaDoc;
106 import java.util.Iterator JavaDoc;
107 import java.util.List JavaDoc;
108 import java.util.Vector JavaDoc;
109
110
111 /**
112  * Servlet to initialize the database and various default items
113  * in it. Use it as a friendly alternative to the DBTool command line
114  * utility.
115  *
116  * @author Michael Nash
117  * @version $Revision: 1.25 $ $Date: 2004/11/17 20:48:18 $
118  */

119 public class DBCreate
120         extends DBServlet {
121     private static Logger log = Logger.getLogger(DBCreate.class);
122
123     /**
124      * Initialize the serv.et
125      *
126      * @param sc The servlet config object given to us by the servlet container
127      */

128     public void init(ServletConfig JavaDoc sc)
129             throws ServletException JavaDoc {
130         super.init(sc);
131     } /* init(ServletConfig) */
132
133
134     /**
135      * doGet method presents a form allowing the user to select several
136      * intialize options
137      *
138      * @param request Standard request object
139      * @param response Standard response object
140      * @throws ServletException If an uncaught exception occurrs
141      * @throws IOException If an I/O error occurrs communicating with
142      * the client
143      */

144     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
145             throws ServletException JavaDoc, IOException JavaDoc {
146
147         try {
148             ExpressoSchema jc = (ExpressoSchema) ExpressoSchema.getInstance();
149
150             if (jc == null) {
151                 jc = new ExpressoSchema();
152             }
153
154             boolean databaseCreated = isInitialDatabaseCreated();
155             if (!databaseCreated) {
156                 setSkipLogin(true);
157             }
158
159             super.doGet(request, response);
160
161             if (databaseCreated && !isAdmin(request, response)) {
162                 throw new java.lang.SecurityException JavaDoc("You must have Administrative rights to execute DBCreate");
163             }
164
165
166             Page myPage = new Page("Initial Setup Options");
167             Paragraph para = new Paragraph(new Text(getString(request,
168                     "Initialize_Database")));
169             para.setCSSClass("jc-pageheader"); //$NON-NLS-1$
170
myPage.add(para);
171
172             Form myForm = new Form();
173             myPage.add(myForm);
174
175             Table formTable = new Table("formtable"); //$NON-NLS-1$
176
myForm.add(formTable);
177             myForm.setAction(getServletPrefix(request));
178
179             Row oneRow = new Row("db row");
180             Cell oneCell = new Cell(new Text(getString(request,
181                     "Context/Database_")));
182             oneCell.setCSSClass("jc-label");
183             oneRow.add(oneCell);
184
185             DropDown dbContext = new DropDown("dbContext", "default");
186             String JavaDoc oneConfigKey = null;
187             String JavaDoc oneDescrip = null;
188
189             for (Enumeration JavaDoc ie = ConfigManager.getAllConfigKeys();
190                  ie.hasMoreElements();) {
191                 oneConfigKey = (String JavaDoc) ie.nextElement();
192
193                 try {
194                     oneDescrip = StringUtil.notNull(ConfigManager.getContext(oneConfigKey).getDescription());
195                 } catch (ConfigurationException ce) {
196                     oneDescrip = "";
197                 }
198                 if (oneDescrip.equals("")) { //$NON-NLS-1$
199
oneDescrip = oneConfigKey;
200                 }
201
202                 dbContext.addOption(oneConfigKey, oneDescrip);
203             }
204
205             oneRow.add(new Cell(dbContext));
206             formTable.add(oneRow);
207             oneRow = new Row();
208             formTable.add(oneRow);
209
210             Text t = new Text(getString(request, "Create_Tables_"));
211             t.setCSSClass("jc-label");
212             oneRow.add(new Cell(t));
213             oneRow.add(new Cell(new CheckBox("CreateTables", "Y", true)));
214             oneRow = new Row();
215             formTable.add(oneRow);
216
217             t = new Text(getString(request, "Verify_Created_Tables_"));
218             t.setCSSClass("jc-label");
219             oneRow.add(new Cell(t));
220             oneRow.add(new Cell(new CheckBox("VerifyTables", "Y", true)));
221             oneRow = new Row();
222             formTable.add(oneRow);
223
224             t = new Text(getString(request, "Setup_Default_Security_"));
225             t.setCSSClass("jc-label");
226             oneRow.add(new Cell(t));
227             oneRow.add(new Cell(new CheckBox("SetupSecurity", "Y", true)));
228             oneRow = new Row();
229             formTable.add(oneRow);
230             t = new Text(getString(request, "Create_Default_Config_Valu"));
231             t.setCSSClass("jc-label");
232             oneRow.add(new Cell(t));
233             oneRow.add(new Cell(new CheckBox("ConfigValues", "Y", true)));
234             oneRow = new Row();
235             formTable.add(oneRow);
236             t = new Text(getString(request, "Perform_additonal_Setup_"));
237             t.setCSSClass("jc-label");
238             oneRow.add(new Cell(t));
239             oneRow.add(new Cell(new CheckBox("OtherSetup", "Y", true)));
240
241             Table buttonTable = new Table("button table");
242             buttonTable.setAlignment("center");
243             buttonTable.add(new Row(new Cell(new Button("Run",
244                     getString(request,
245                             "Run")))));
246             myForm.add(new HiddenField("back",
247                     StringUtil.notNull(request.getParameter("back"))));
248             myForm.add(buttonTable);
249             myPage.display(request, response, getString(request, "charset"));
250         } catch (Exception JavaDoc de) {
251             showError(de, request, response);
252         }
253     } /* doGet(HttpServletRequest, HttpServletResponse) */
254
255
256     /**
257      * doPost receives the options from the form & calls methods to actually
258      * perform the intiailizations
259      *
260      * @param request Standard request object
261      * @param response Standard reponse object
262      * @throws ServletException If an uncaught exception occurrs
263      * @throws IOException If an I/O error occurrs communicating with
264      * the client
265      */

266     public void doPost(HttpServletRequest JavaDoc request,
267                        HttpServletResponse JavaDoc response)
268             throws ServletException JavaDoc, IOException JavaDoc {
269         boolean databaseCreated = isInitialDatabaseCreated();
270         if (!databaseCreated) {
271             setSkipLogin(true);
272         }
273
274         super.doPost(request, response);
275
276         if (databaseCreated && !isAdmin(request, response)) {
277             throw new java.lang.SecurityException JavaDoc("You must have Administrative rights to execute DBCreate");
278         }
279
280
281         String JavaDoc createTables = StringUtil.notNull(request.getParameter("CreateTables"));
282         String JavaDoc validateTables = StringUtil.notNull(request.getParameter("VerifyTables"));
283         String JavaDoc setupSecurity = StringUtil.notNull(request.getParameter("SetupSecurity"));
284         String JavaDoc setupConfigValues = StringUtil.notNull(request.getParameter("ConfigValues"));
285         String JavaDoc otherSetup = StringUtil.notNull(request.getParameter("OtherSetup"));
286         String JavaDoc dbContext = StringUtil.notNull(request.getParameter("dbContext"));
287         response.setContentType("text/html; charset=iso-8859-1");
288         java.io.PrintWriter JavaDoc out = response.getWriter();
289
290         try {
291             ExpressoSchema jc = (ExpressoSchema) SchemaFactory.getInstance()
292                     .getSchema(com.jcorporate.expresso
293
                    .core.ExpressoSchema.class.getName());
294
295             if (jc == null) {
296                 throw new ServletException JavaDoc("Unable to construct Expresso Schema. Check logs for details");
297             }
298
299             out.println("<html><head><title>Database Initialization</title></head><body class=\"jc-default\">" +
300                     "<h1 align=\"center\">Database Initialization</h1>");
301
302             Vector JavaDoc allSchemas = new Vector JavaDoc(5);
303             allSchemas.addElement(jc);
304
305             SchemaList sl = null;
306             SchemaList oneSchema = null;
307             boolean noOtherSchemas = true;
308
309             try {
310                 sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
311                 sl.setDataContext(dbContext);
312                 sl.search();
313
314                 if (sl.getFoundCount() > 0) {
315                     noOtherSchemas = false;
316                 }
317
318                 // search for schema classes
319

320             } catch (DBException de) {
321                 noOtherSchemas = true;
322             }
323             if (!noOtherSchemas) {
324                 for (Iterator JavaDoc e = sl.searchAndRetrieveList().iterator();
325                      e.hasNext();) {
326                     oneSchema = (SchemaList) e.next();
327
328                     boolean schemaWarning = false;
329
330                     Schema mySchema2 = SchemaFactory.getInstance()
331                             .getSchema(oneSchema.getField("SchemaClass"));
332
333                     if (mySchema2 == null) {
334                         schemaWarning = true;
335                     } else {
336                         allSchemas.addElement(mySchema2);
337                     }
338
339                     if (schemaWarning) {
340                         out.println("<p>Warning: Unable to process schema " + oneSchema.getField("SchemaClass") +
341                                 " - see log for details</p>");
342                     }
343                 } /* for each registered schema in this db */
344
345             } /* if we read other schemas */
346
347             out.println("<p align=\"center\">" + getString(request,
348                     "Processing_initializations") + "</p>");
349
350             ServletInstallLog installLog = new ServletInstallLog(out);
351
352             if (createTables.equalsIgnoreCase("Y")) {
353                 DBTool.createTables(installLog, allSchemas, dbContext);
354             }
355
356             if (validateTables.equalsIgnoreCase("Y")) {
357                 List errors = DBTool.compareTables(installLog, allSchemas, dbContext);
358
359                 for (Iterator JavaDoc iterator = errors.iterator(); iterator.hasNext();) {
360                     String JavaDoc str = (String JavaDoc) iterator.next();
361                     out.println("<p align=\"center\">" + str + "</p>");
362                 }
363             }
364
365             try {
366                 //
367
//Setting up security goes before setting up default values.
368
//
369
if (setupSecurity.equalsIgnoreCase("Y")) {
370                     DBTool.setupSecurity(installLog, allSchemas, dbContext);
371                 } /* if we check security */
372
373                 if (setupConfigValues.equalsIgnoreCase("Y")) {
374                     DBTool.populateTables(installLog, allSchemas, dbContext);
375                 }
376                 if (otherSetup.equalsIgnoreCase("Y")) {
377                     DBTool.otherSetups(installLog, allSchemas, dbContext);
378                 }
379                 out.println("<p align=\"center\">" + getString(request,
380                         "All_functions_complete") + "</p>");
381
382                 //Now that things are created, let's try initializing again.
383
ConfigManager.initializeAllDBObjects();
384                 ConfigManager.mapOtherDBs();
385             } catch (Exception JavaDoc e) {
386
387                 // handle exception with local printing, to preserve previous output
388
out.println("<p align=\"center\"> PROBLEM with initialization of database: </p>");
389                 e.printStackTrace(out);
390             }
391
392
393         } catch (Exception JavaDoc de) {
394             log.error("Error performing setup", de);
395             showError(de, request, response);
396         }
397     } /* doPost(HttpServletRequest, HttpServletResponse) */
398
399
400     /**
401      * Checks to see if a database of any sort has already been created in
402      * the default context.
403      *
404      * @return True if the schemalist object exists in the system
405      */

406     protected boolean isInitialDatabaseCreated() {
407         try {
408             SchemaList sl = new SchemaList(SecuredDBObject.SYSTEM_ACCOUNT);
409             sl.setDataContext("default");
410             sl.count();
411         } catch (DBException dbe) {
412             return false;
413         }
414         return true;
415     }
416
417     /**
418      * Checks to see if the current user is an Admin.
419      *
420      * @param request The ServletRequest object
421      * @param response The Servlet Response object
422      * @return true if the CurrentLogin is an Admin User
423      * @throws ServletException if there's an error processing the request
424      */

425     protected boolean isAdmin(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc {
426         try {
427             CurrentLogin cl = (CurrentLogin) GenericSession.getAttribute(request, "CurrentLogin");
428             if (cl == null) {
429                 return false;
430             }
431
432             int uid = cl.getUid();
433             String JavaDoc dbName = cl.getDBName();
434             User u = new User();
435             u.setUid(uid);
436             u.setDataContext(dbName);
437             try {
438                 if (!u.find()) {
439                     return false;
440
441                 }
442             } catch (DBException ex1) {
443                 log.error("Error performing find", ex1);
444                 return false;
445             }
446
447
448             java.util.List JavaDoc groupList = u.getGroupsList();
449             return groupList.contains(User.ADMIN_USER);
450         } catch (ClassCastException JavaDoc e) {
451             return false;
452         } catch (Exception JavaDoc ex) {
453             throw new ServletException JavaDoc("Error checking isAdmin:", ex);
454         }
455     }
456
457
458 } /* DBCreate */
459
Popular Tags