KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > tigris > scarab > services > DatabaseInitializer


1 package org.tigris.scarab.services;
2
3 /* ================================================================
4  * Copyright (c) 2000-2002 CollabNet. 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 are
8  * 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 the
15  * documentation and/or other materials provided with the distribution.
16  *
17  * 3. The end-user documentation included with the redistribution, if
18  * any, must include the following acknowlegement: "This product includes
19  * software developed by Collab.Net <http://www.Collab.Net/>."
20  * Alternately, this acknowlegement may appear in the software itself, if
21  * and wherever such third-party acknowlegements normally appear.
22  *
23  * 4. The hosted project names must not be used to endorse or promote
24  * products derived from this software without prior written
25  * permission. For written permission, please contact info@collab.net.
26  *
27  * 5. Products derived from this software may not use the "Tigris" or
28  * "Scarab" names nor may "Tigris" or "Scarab" appear in their names without
29  * prior written permission of Collab.Net.
30  *
31  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
32  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34  * IN NO EVENT SHALL COLLAB.NET OR ITS CONTRIBUTORS BE LIABLE FOR ANY
35  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
37  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
39  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
40  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  * ====================================================================
44  *
45  * This software consists of voluntary contributions made by many
46  * individuals on behalf of Collab.Net.
47  */

48
49 import java.lang.reflect.Method JavaDoc;
50 import java.sql.Connection JavaDoc;
51 import java.sql.Statement JavaDoc;
52 import java.sql.ResultSet JavaDoc;
53 import java.util.Locale JavaDoc;
54 import java.util.List JavaDoc;
55 import java.util.MissingResourceException JavaDoc;
56 import java.util.Iterator JavaDoc;
57
58 import org.apache.fulcrum.BaseService;
59 import org.apache.fulcrum.InitializationException;
60 import org.apache.fulcrum.localization.Localization;
61 import org.apache.turbine.Turbine;
62
63 import org.apache.torque.Torque;
64 import org.apache.torque.util.Criteria;
65
66 import org.tigris.scarab.om.GlobalParameter;
67 import org.tigris.scarab.om.GlobalParameterManager;
68 import org.tigris.scarab.om.GlobalParameterPeer;
69 import org.tigris.scarab.util.Log;
70 import org.tigris.scarab.util.ScarabConstants;
71
72 /**
73  * Transforms localization keys stored in the database into their
74  * respective localized values upon initial startup of Fulcrum.
75  *
76  * @author <a HREF="mailto:jmcnally@collab.net">John McNally</a>
77  * @version $Id: DatabaseInitializer.java 9318 2004-12-13 13:00:55Z dabbous $
78  */

79 public class DatabaseInitializer
80     extends BaseService
81 {
82     private static final String JavaDoc PRE_L10N = "pre-l10n";
83     private static final String JavaDoc STARTED_L10N = "started";
84     private static final String JavaDoc POST_L10N = "post-l10n";
85     private static final String JavaDoc DB_L10N_STATE = "db-l10n-state";
86
87     // some old parameter keys for the http parameters
88
private static final String JavaDoc MODULE_DOMAIN = "module-domain";
89     private static final String JavaDoc MODULE_PORT = "module-port";
90     private static final String JavaDoc MODULE_SCHEME = "module-scheme";
91     private static final String JavaDoc MODULE_SCRIPT_NAME = "module-script-name";
92
93
94     /**
95      * The values returned by {@link #getInputData()}.
96      */

97     private static final String JavaDoc[][] BEAN_METHODS =
98     {
99         {"InitDbScarabBundle", "MITList", "Name"},
100         {"InitDbScarabBundle", "Attribute", "Name", "Description"},
101         {"InitDbScarabBundle", "AttributeOption", "Name"},
102         {"InitDbScarabBundle", "IssueType", "Name", "Description"},
103         {"InitDbScarabBundle", "AttributeGroup", "Name", "Description"},
104         {"InitDbScarabBundle", "RModuleAttribute", "DisplayValue"},
105         {"InitDbScarabBundle", "Scope", "Name"}
106     };
107
108     /**
109      * Initializes the service by setting up Torque.
110      */

111     public void init()
112         throws InitializationException
113     {
114         try
115         {
116             String JavaDoc dbState =
117                 GlobalParameterManager.getString(DB_L10N_STATE);
118             if (PRE_L10N.equals(dbState) || STARTED_L10N.equals(dbState))
119             {
120                 long start = System.currentTimeMillis();
121                 Log.get().info("New scarab database; localizing strings for '" +
122                                ScarabConstants.DEFAULT_LOCALE.getDisplayName() + "'...");
123                 GlobalParameterManager.setString(DB_L10N_STATE, STARTED_L10N);
124                 initdb(ScarabConstants.DEFAULT_LOCALE);
125                 GlobalParameterManager.setString(DB_L10N_STATE, POST_L10N);
126                 Log.get().info("Done localizing. Time elapsed = " +
127                     (System.currentTimeMillis()-start)/1000.0 + " s");
128             }
129
130             checkNewHttpParameters();
131         }
132         catch (Exception JavaDoc e)
133         {
134             e.printStackTrace();
135             throw new InitializationException(
136                 "Failed to localize default data!", e); //EXCEPTION
137
}
138
139         // indicate that the service initialized correctly
140
setInit(true);
141     }
142
143     protected String JavaDoc[][] getInputData()
144     {
145         return BEAN_METHODS;
146     }
147
148     private void initdb(Locale JavaDoc defaultLocale)
149         throws Exception JavaDoc
150     {
151         String JavaDoc[][] methodNames = getInputData();
152         Class JavaDoc[] stringSig = {String JavaDoc.class};
153         Class JavaDoc[] critSig = {Criteria.class};
154
155         for (int m=0; m<methodNames.length; m++)
156         {
157             String JavaDoc[] row = methodNames[m];
158             String JavaDoc omClassName = "org.tigris.scarab.om." + row[1];
159             Class JavaDoc peerClass = Class.forName(omClassName + "Peer");
160             Object JavaDoc peerObject = peerClass.newInstance();
161
162             Method JavaDoc doSelect = peerClass.getMethod("doSelect", critSig);
163             Object JavaDoc[] critArg = {new Criteria()};
164             List JavaDoc omlist = (List JavaDoc)doSelect.invoke(peerObject, critArg);
165             if (!omlist.isEmpty())
166             {
167                 Class JavaDoc omClass = Class.forName(omClassName);
168                 int nbrBeanMethods = row.length - 2;
169                 Method JavaDoc[] getters = new Method JavaDoc[nbrBeanMethods];
170                 Method JavaDoc[] setters = new Method JavaDoc[nbrBeanMethods];
171                 for (int n=2; n<row.length; n++)
172                 {
173                     getters[n-2] = omClass.getMethod("get"+row[n], null);
174                     setters[n-2] = omClass.getMethod("set"+row[n], stringSig);
175                 }
176                 Method JavaDoc save = omClass.getMethod("save", null);
177
178                 Iterator JavaDoc i = omlist.iterator();
179                 while (i.hasNext())
180                 {
181                     Object JavaDoc om = i.next();
182                     for (int n=0; n<getters.length; n++)
183                     {
184                         Log.get().debug("Converting " + row[1] + '.' +
185                                         getters[n].getName());
186                         String JavaDoc key = (String JavaDoc)getters[n].invoke(om, null);
187                         String JavaDoc value = null;
188
189                         // Oracle returns null on empty field.
190
if (key != null)
191                         {
192                             try
193                             {
194                                 value = Localization.getString(row[0],
195                                                                defaultLocale,
196                                                                key);
197                             }
198                             catch (MissingResourceException JavaDoc e)
199                             {
200                                 Log.get().debug("Missing database initialization "
201                                                 + "resource: " + e.getMessage());
202                             }
203                         }
204                         if (value != null)
205                         {
206                             Object JavaDoc[] arg = {value};
207                             setters[n].invoke(om, arg);
208                         }
209                     }
210                     save.invoke(om, null);
211                 }
212             }
213         }
214     }
215
216     private void checkNewHttpParameters()
217         throws Exception JavaDoc
218     {
219         String JavaDoc oldDomain = GlobalParameterManager
220             .getString(ScarabConstants.HTTP_DOMAIN);
221         String JavaDoc oldScheme = GlobalParameterManager
222             .getString(ScarabConstants.HTTP_SCHEME);
223         String JavaDoc oldScriptName = GlobalParameterManager
224             .getString(ScarabConstants.HTTP_SCRIPT_NAME);
225         String JavaDoc oldPort = GlobalParameterManager
226             .getString(ScarabConstants.HTTP_PORT);
227
228         if (oldDomain.equals(""))
229         {
230             // installations with post-b15 but pre-b16 may have module
231
// specific values.
232
Criteria crit = new Criteria();
233             crit.add(GlobalParameterPeer.NAME, MODULE_DOMAIN);
234             List JavaDoc parameters = GlobalParameterPeer.doSelect(crit);
235             if (!parameters.isEmpty())
236             {
237                 oldDomain = ((GlobalParameter)parameters.get(0)).getValue();
238             }
239
240             crit = new Criteria();
241             crit.add(GlobalParameterPeer.NAME, MODULE_SCHEME);
242             parameters = GlobalParameterPeer.doSelect(crit);
243             if (!parameters.isEmpty())
244             {
245                 oldScheme = ((GlobalParameter)parameters.get(0)).getValue();
246             }
247
248             crit = new Criteria();
249             crit.add(GlobalParameterPeer.NAME, MODULE_SCRIPT_NAME);
250             parameters = GlobalParameterPeer.doSelect(crit);
251             if (!parameters.isEmpty())
252             {
253                 oldScriptName =
254                     ((GlobalParameter)parameters.get(0)).getValue();
255             }
256
257             crit = new Criteria();
258             crit.add(GlobalParameterPeer.NAME, MODULE_PORT);
259             parameters = GlobalParameterPeer.doSelect(crit);
260             if (!parameters.isEmpty())
261             {
262                 oldPort = ((GlobalParameter)parameters.get(0)).getValue();
263             }
264         }
265
266         String JavaDoc newValue = Turbine.getConfiguration()
267             .getString(ScarabConstants.HTTP_DOMAIN);
268         if (newValue != null && newValue.trim().length() != 0
269             && !newValue.equals(oldDomain))
270         {
271             GlobalParameterManager
272                 .setString(ScarabConstants.HTTP_DOMAIN, newValue);
273             fixIssueIdCounters(oldDomain, newValue);
274         }
275
276         newValue = Turbine.getConfiguration()
277             .getString(ScarabConstants.HTTP_SCHEME);
278         if (newValue != null && newValue.trim().length() != 0
279             && !newValue.equals(oldScheme))
280         {
281             GlobalParameterManager
282                 .setString(ScarabConstants.HTTP_SCHEME, newValue);
283         }
284
285         newValue = Turbine.getConfiguration()
286             .getString(ScarabConstants.HTTP_SCRIPT_NAME);
287         if (newValue != null && newValue.trim().length() != 0
288             && !newValue.equals(oldScriptName))
289         {
290             GlobalParameterManager
291                 .setString(ScarabConstants.HTTP_SCRIPT_NAME, newValue);
292         }
293
294         newValue = Turbine.getConfiguration()
295             .getString(ScarabConstants.HTTP_PORT);
296         if (newValue != null && newValue.trim().length() != 0
297             && !newValue.equals(oldPort))
298         {
299             GlobalParameterManager
300                 .setString(ScarabConstants.HTTP_PORT, newValue);
301         }
302     }
303
304     private void fixIssueIdCounters(String JavaDoc oldDomain, String JavaDoc newDomain)
305         throws Exception JavaDoc
306     {
307         String JavaDoc sql =
308             "select NEXT_ID from ID_TABLE where TABLE_NAME='ID_TABLE'";
309         Connection JavaDoc con = null;
310         try
311         {
312             con = Torque.getConnection();
313             Statement JavaDoc s = con.createStatement();
314             ResultSet JavaDoc rs = s.executeQuery(sql);
315             int maxId = 0;
316             if (rs.next())
317             {
318                 maxId = rs.getInt(1);
319             }
320             s.close();
321
322             for (int id = 1000; id <= maxId; id++)
323             {
324                 sql = "select TABLE_NAME from ID_TABLE where ID_TABLE_ID="
325                     + id;
326                 s = con.createStatement();
327                 rs = s.executeQuery(sql);
328                 if (rs.next())
329                 {
330                     String JavaDoc oldKey = rs.getString(1);
331                     s.close();
332                     int hyphenPos = oldKey.indexOf('-');
333                     String JavaDoc newKey = null;
334                     if ( (oldDomain == null || oldDomain.length() == 0)
335                          && hyphenPos <= 0)
336                     {
337                         newKey = newDomain + '-' + oldKey;
338                     }
339                     else
340                     {
341                         String JavaDoc prefix = oldKey.substring(0, hyphenPos);
342                         String JavaDoc code = oldKey.substring(hyphenPos+1);
343                         if (prefix.equals(oldDomain))
344                         {
345                             newKey = newDomain + '-' + code;
346                         }
347                     }
348                     
349                     if (newKey != null)
350                     {
351                         sql = "update ID_TABLE set TABLE_NAME='" + newKey +
352                             "' where ID_TABLE_ID=" + id;
353                         s = con.createStatement();
354                         s.executeUpdate(sql);
355                         s.close();
356                     }
357                 }
358             }
359         }
360         finally
361         {
362             if (con != null)
363             {
364                 con.close();
365             }
366         }
367     }
368 }
369
Popular Tags