KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mchange > v2 > c3p0 > cfg > C3P0Config


1 /*
2  * Distributed as part of c3p0 v.0.9.1
3  *
4  * Copyright (C) 2005 Machinery For Change, Inc.
5  *
6  * Author: Steve Waldman <swaldman@mchange.com>
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License version 2.1, as
10  * published by the Free Software Foundation.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this software; see the file LICENSE. If not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */

22
23
24 package com.mchange.v2.c3p0.cfg;
25
26 import java.beans.*;
27 import java.util.*;
28 import com.mchange.v2.c3p0.impl.*;
29 import com.mchange.v2.beans.*;
30 import com.mchange.v2.cfg.*;
31 import com.mchange.v2.log.*;
32
33 import java.io.IOException JavaDoc;
34 import java.lang.reflect.Method JavaDoc;
35 import com.mchange.v1.lang.BooleanUtils;
36
37 //all internal maps should be HashMaps (the implementation presumes HashMaps)
38

39 public final class C3P0Config
40 {
41     public final static String JavaDoc CFG_FINDER_CLASSNAME_KEY = "com.mchange.v2.c3p0.cfg.finder";
42
43     public final static String JavaDoc DEFAULT_CONFIG_NAME = "default";
44
45     public final static C3P0Config MAIN;
46
47     final static MLogger logger = MLog.getLogger( C3P0Config.class );
48
49     static
50     {
51 // Set knownProps = new HashSet();
52
// knownProps.add("acquireIncrement");
53
// knownProps.add("acquireRetryAttempts");
54
// knownProps.add("acquireRetryDelay");
55
// knownProps.add("autoCommitOnClose");
56
// knownProps.add("automaticTestTable");
57
// knownProps.add("breakAfterAcqireFailure");
58
// knownProps.add("checkoutTimeout");
59
// knownProps.add("connectionTesterClassName");
60
// knownProps.add("factoryClassLocation");
61
// knownProps.add("forceIgnoreUnresolvedTransactions");
62
// knownProps.add("idleConnectionTestPeriod");
63
// knownProps.add("initialPoolSize");
64
// knownProps.add("maxIdleTime");
65
// knownProps.add("maxPoolSize");
66

67     C3P0Config protoMain;
68
69     String JavaDoc cname = MultiPropertiesConfig.readVmConfig().getProperty( CFG_FINDER_CLASSNAME_KEY );
70
71     C3P0ConfigFinder cfgFinder = null;
72     try
73         {
74         if (cname != null)
75             cfgFinder = (C3P0ConfigFinder) Class.forName( cname ).newInstance();
76         
77         }
78     catch (Exception JavaDoc e)
79         {
80         if ( logger.isLoggable(MLevel.WARNING) )
81             logger.log( MLevel.WARNING, "Could not load specified C3P0ConfigFinder class'" + cname + "'.", e);
82         }
83
84     try
85         {
86         if (cfgFinder == null)
87             {
88             Class.forName("org.w3c.dom.Node");
89             Class.forName("com.mchange.v2.c3p0.cfg.C3P0ConfigXmlUtils"); //fail nicely if we don't have XML libs
90
cfgFinder = new DefaultC3P0ConfigFinder();
91             }
92         protoMain = cfgFinder.findConfig();
93         }
94     catch (Exception JavaDoc e)
95         {
96         
97         if ( logger.isLoggable(MLevel.WARNING) )
98             logger.log( MLevel.WARNING, "XML configuration disabled! Verify that standard XML libs are available.", e);
99
100         HashMap flatDefaults = C3P0ConfigUtils.extractHardcodedC3P0Defaults();
101         flatDefaults.putAll( C3P0ConfigUtils.extractC3P0PropertiesResources() );
102         protoMain = C3P0ConfigUtils.configFromFlatDefaults( flatDefaults );
103         }
104     MAIN = protoMain;
105
106     warnOnUnknownProperties( MAIN );
107     }
108
109     private static void warnOnUnknownProperties( C3P0Config cfg )
110     {
111     warnOnUnknownProperties( cfg.defaultConfig );
112     for (Iterator ii = cfg.configNamesToNamedScopes.values().iterator(); ii.hasNext(); )
113         warnOnUnknownProperties( (NamedScope) ii.next() );
114     }
115
116     private static void warnOnUnknownProperties( NamedScope scope )
117     {
118     warnOnUnknownProperties( scope.props );
119     for (Iterator ii = scope.userNamesToOverrides.values().iterator(); ii.hasNext(); )
120         warnOnUnknownProperties( (Map) ii.next() );
121     }
122
123     private static void warnOnUnknownProperties( Map propMap )
124     {
125     for (Iterator ii = propMap.keySet().iterator(); ii.hasNext(); )
126         {
127         String JavaDoc prop = (String JavaDoc) ii.next();
128         if (! C3P0Defaults.isKnownProperty( prop ) && logger.isLoggable( MLevel.WARNING ))
129             logger.log( MLevel.WARNING, "Unknown c3p0-config property: " + prop);
130         }
131     }
132
133     public static String JavaDoc getUnspecifiedUserProperty( String JavaDoc propKey, String JavaDoc configName )
134     {
135       String JavaDoc out = null;
136
137       if (configName == null)
138           out = (String JavaDoc) MAIN.defaultConfig.props.get( propKey );
139       else
140           {
141           NamedScope named = (NamedScope) MAIN.configNamesToNamedScopes.get( configName );
142           if (named != null)
143               out = (String JavaDoc) named.props.get(propKey);
144           else
145               logger.warning("named-config with name '" + configName + "' does not exist. Using default-config for property '" + propKey + "'.");
146
147           if (out == null)
148               out = (String JavaDoc) MAIN.defaultConfig.props.get( propKey );
149           }
150       
151       return out;
152     }
153
154     public static Map getUnspecifiedUserProperties(String JavaDoc configName)
155     {
156     Map out = new HashMap();
157
158     out.putAll( MAIN.defaultConfig.props );
159
160     if (configName != null)
161         {
162           NamedScope named = (NamedScope) MAIN.configNamesToNamedScopes.get( configName );
163           if (named != null)
164               out.putAll( named.props );
165           else
166               logger.warning("named-config with name '" + configName + "' does not exist. Using default-config.");
167         }
168
169     return out;
170     }
171
172     public static Map getUserOverrides( String JavaDoc configName )
173     {
174     Map out = new HashMap();
175
176     NamedScope namedConfigScope = null;
177
178     if (configName != null)
179         namedConfigScope = (NamedScope) MAIN.configNamesToNamedScopes.get( configName );
180
181     out.putAll( MAIN.defaultConfig.userNamesToOverrides );
182
183     if (namedConfigScope != null)
184         out.putAll( namedConfigScope.userNamesToOverrides );
185
186     return (out.isEmpty() ? null : out );
187     }
188
189     public static String JavaDoc getUserOverridesAsString(String JavaDoc configName) throws IOException JavaDoc
190     {
191     Map userOverrides = getUserOverrides( configName );
192     if (userOverrides == null)
193         return null;
194     else
195         return C3P0ImplUtils.createUserOverridesAsString( userOverrides ).intern();
196     }
197
198     final static Class JavaDoc[] SUOAS_ARGS = new Class JavaDoc[] { String JavaDoc.class };
199
200     final static Collection SKIP_BIND_PROPS = Arrays.asList( new String JavaDoc[] {"loginTimeout", "properties"} );
201
202     public static void bindNamedConfigToBean(Object JavaDoc bean, String JavaDoc configName) throws IntrospectionException
203     {
204     Map defaultUserProps = C3P0Config.getUnspecifiedUserProperties( configName );
205     BeansUtils.overwriteAccessiblePropertiesFromMap( defaultUserProps,
206                              bean,
207                              false,
208                              SKIP_BIND_PROPS,
209                              true,
210                              MLevel.FINEST,
211                              MLevel.WARNING,
212                              false);
213     try
214         {
215         Method JavaDoc m = bean.getClass().getMethod( "setUserOverridesAsString", SUOAS_ARGS );
216         m.invoke( bean, new Object JavaDoc[] {getUserOverridesAsString( configName )} );
217         }
218     catch (NoSuchMethodException JavaDoc e)
219         {
220         e.printStackTrace();
221         /* ignore */
222         }
223     catch (Exception JavaDoc e)
224         {
225         if (logger.isLoggable( MLevel.WARNING ))
226             logger.log( MLevel.WARNING,
227                 "An exception occurred while trying to bind user overrides " +
228                 "for named config '" + configName + "'. Only default user configs " +
229                 "will be used."
230                 , e);
231         }
232     }
233
234     /*
235      * Note that on initialization of a DataSource, no config name is known.
236      * We initialize local vars using the default config. The DataSources class
237      * and/or constructors that accept a configName then overwrite the initial
238      * values with namedConfig overrides if supplied.
239      */

240     public static String JavaDoc initializeUserOverridesAsString()
241     {
242     try
243         { return getUserOverridesAsString( null ); }
244     catch (Exception JavaDoc e)
245         {
246         if (logger.isLoggable( MLevel.WARNING ))
247             logger.log( MLevel.WARNING, "Error initializing default user overrides. User overrides may be ignored.", e);
248         return null;
249         }
250     }
251
252     public static String JavaDoc initializeStringPropertyVar(String JavaDoc propKey, String JavaDoc dflt)
253     {
254     String JavaDoc out = getUnspecifiedUserProperty( propKey, null );
255     if (out == null) out = dflt;
256     return out;
257     }
258
259     public static int initializeIntPropertyVar(String JavaDoc propKey, int dflt)
260     {
261     boolean set = false;
262     int out = -1;
263
264     String JavaDoc outStr = getUnspecifiedUserProperty( propKey, null );
265     if (outStr != null)
266         {
267         try
268             {
269             out = Integer.parseInt( outStr.trim() );
270             set = true;
271             }
272         catch (NumberFormatException JavaDoc e)
273             {
274             logger.info("'" + outStr + "' is not a legal value for property '" + propKey +
275                     "'. Using default value: " + dflt);
276             }
277         }
278
279     if (!set)
280         out = dflt;
281
282     //System.err.println("initializing " + propKey + " to " + out);
283
return out;
284     }
285
286     public static boolean initializeBooleanPropertyVar(String JavaDoc propKey, boolean dflt)
287     {
288     boolean set = false;
289     boolean out = false;
290
291     String JavaDoc outStr = getUnspecifiedUserProperty( propKey, null );
292     if (outStr != null)
293         {
294         try
295             {
296             out = BooleanUtils.parseBoolean( outStr.trim() );
297             set = true;
298             }
299         catch (IllegalArgumentException JavaDoc e)
300             {
301             logger.info("'" + outStr + "' is not a legal value for property '" + propKey +
302                     "'. Using default value: " + dflt);
303             }
304         }
305
306     if (!set)
307         out = dflt;
308
309     return out;
310     }
311
312
313
314     NamedScope defaultConfig;
315     HashMap configNamesToNamedScopes;
316
317     C3P0Config( NamedScope defaultConfig, HashMap configNamesToNamedScopes)
318     {
319     this.defaultConfig = defaultConfig;
320     this.configNamesToNamedScopes = configNamesToNamedScopes;
321     }
322
323 // C3P0Config()
324
// {
325
// this.defaultConfig = new NamedScope();
326
// this.configNamesToNamedScopes = new HashMap();
327
// }
328

329 }
Popular Tags