KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > jdbc > ReferenceableDataSource


1 /*
2
3    Derby - Class org.apache.derby.jdbc.ReferenceableDataSource
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21 package org.apache.derby.jdbc;
22
23 import java.sql.SQLException JavaDoc;
24 import java.lang.reflect.*;
25
26
27 import java.io.Serializable JavaDoc;
28 import java.io.PrintWriter JavaDoc;
29 import java.util.Properties JavaDoc;
30
31 /* -- JNDI -- */
32 import javax.naming.NamingException JavaDoc;
33 import javax.naming.Referenceable JavaDoc;
34 import javax.naming.Reference JavaDoc;
35 import javax.naming.StringRefAddr JavaDoc;
36 import javax.naming.spi.ObjectFactory JavaDoc;
37 import javax.naming.Context JavaDoc;
38 import javax.naming.Name JavaDoc;
39 import javax.naming.Reference JavaDoc;
40 import javax.naming.RefAddr JavaDoc;
41 import java.util.Hashtable JavaDoc;
42 import java.util.Enumeration JavaDoc;
43
44 /**
45
46     Cloudscape DataSource implementation base class.
47     ReferenceableDataSource provides support for JDBC standard DataSource attributes and acts
48     as the ObjectFactory to generate Cloudscape DataSource implementations.
49     <P>
50     The standard attributes provided by this class are:
51     <UL>
52     <LI>databaseName
53     <LI>dataSourceName
54     <LI>description
55     <LI>password
56     <LI>user
57     </UL>
58     <BR>
59     See the specific Cloudscape DataSource implementation for details on their meaning.
60     <BR>
61     See the JDBC 3.0 specification for more details.
62
63
64 */

65 public class ReferenceableDataSource implements
66                 javax.naming.Referenceable JavaDoc,
67                 java.io.Serializable JavaDoc,
68                 ObjectFactory JavaDoc
69 {
70
71
72     private static final long serialVersionUID = 1872877359127597176L;
73
74
75     private static final Class JavaDoc[] STRING_ARG = { "".getClass() };
76     private static final Class JavaDoc[] INT_ARG = { Integer.TYPE };
77     private static final Class JavaDoc[] BOOLEAN_ARG = { Boolean.TYPE };
78
79     private String JavaDoc description;
80     private String JavaDoc dataSourceName;
81     private String JavaDoc databaseName;
82     private String JavaDoc password;
83     private String JavaDoc user;
84     private int loginTimeout;
85
86
87     /** instance variables that will not be serialized */
88     transient private PrintWriter JavaDoc printer;
89
90     /**
91         No-arg constructor.
92      */

93     public ReferenceableDataSource() {
94         update();
95     }
96
97
98     /*
99      * Properties to be seen by Bean - access thru reflection.
100      */

101
102     /**
103         Set the database name. Setting this property is mandatory. If a
104         database named wombat at g:/db needs to be accessed, database name
105         should be set to "g:/db/wombat". The database will be booted if it
106         is not already running in the system.
107
108         @param databaseName the name of the database
109     */

110     public final synchronized void setDatabaseName(String JavaDoc databaseName) {
111         this.databaseName = databaseName;
112         update();
113     }
114     public String JavaDoc getDatabaseName() {
115         return databaseName;
116     }
117
118     /**
119         Set the data source name. The property is not mandatory. It is used
120         for informational purposes only.
121
122         @param dsn the name of the data source
123     */

124     public final void setDataSourceName(String JavaDoc dsn) {
125         dataSourceName = dsn;
126     }
127     /** @return data source name */
128     public final String JavaDoc getDataSourceName() {
129         return dataSourceName;
130     }
131
132     /**
133         Set the data source descripton. This property is not mandatory.
134         It is used for informational purposes only.
135
136         @param desc the description of the data source
137      */

138     public final void setDescription(String JavaDoc desc) {
139         description = desc;
140     }
141     /** @return description */
142     public final String JavaDoc getDescription() {
143         return description;
144     }
145
146     /**
147         Set the <code>user</code> property for the data source.
148         This is user name for any data source getConnection() call
149         that takes no arguments.
150     */

151     public final void setUser(String JavaDoc user) {
152         this.user = user;
153     }
154     /** @return user */
155     public final String JavaDoc getUser() {
156         return user;
157     }
158
159     /**
160         Set the <code>password</code> property for the data source.
161         This is user's password for any data source getConnection() call
162         that takes no arguments.
163     */

164     public final void setPassword(String JavaDoc password) {
165         this.password = password;
166     }
167     /** @return password */
168     public final String JavaDoc getPassword() {
169         return password;
170     }
171
172     /*
173      * DataSource methods
174      */

175
176
177     /**
178      * Gets the maximum time in seconds that this data source can wait
179      * while attempting to connect to a database. A value of zero
180      * means that the timeout is the default system timeout
181      * if there is one; otherwise it means that there is no timeout.
182      * When a data source object is created, the login timeout is
183      * initially zero.
184      *
185      * @return the data source login time limit
186      * @exception SQLException if a database access error occurs.
187      */

188     public int getLoginTimeout() throws SQLException JavaDoc
189     {
190         return loginTimeout;
191     }
192
193     /**
194      * Sets the maximum time in seconds that this data source will wait
195      * while attempting to connect to a database. A value of zero
196      * specifies that the timeout is the default system timeout
197      * if there is one; otherwise it specifies that there is no timeout.
198      * When a data source object is created, the login timeout is
199      * initially zero.
200      <P>
201         Cloudscape ignores this property.
202      * @param seconds the data source login time limit
203      * @exception SQLException if a database access error occurs.
204      */

205     public void setLoginTimeout(int seconds) throws SQLException JavaDoc
206     {
207         loginTimeout = seconds;
208     }
209
210
211     /**
212      * Get the log writer for this data source.
213      *
214      * <p>The log writer is a character output stream to which all logging
215      * and tracing messages for this data source object instance will be
216      * printed. This includes messages printed by the methods of this
217      * object, messages printed by methods of other objects manufactured
218      * by this object, and so on. Messages printed to a data source
219      * specific log writer are not printed to the log writer associated
220      * with the java.sql.Drivermanager class. When a data source object is
221      * created the log writer is initially null, in other words, logging
222      * is disabled.
223      *
224      * @return the log writer for this data source, null if disabled
225      * @exception SQLException if a database-access error occurs.
226      */

227     public PrintWriter JavaDoc getLogWriter() throws SQLException JavaDoc
228     {
229         return printer;
230     }
231
232     /**
233      * Set the log writer for this data source.
234      *
235      * <p>The log writer is a character output stream to which all logging
236      * and tracing messages for this data source object instance will be
237      * printed. This includes messages printed by the methods of this
238      * object, messages printed by methods of other objects manufactured
239      * by this object, and so on. Messages printed to a data source
240      * specific log writer are not printed to the log writer associated
241      * with the java.sql.Drivermanager class. When a data source object is
242      * created the log writer is initially null, in other words, logging
243      * is disabled.
244      *
245      * @param out the new log writer; to disable, set to null
246      * @exception SQLException if a database-access error occurs.
247      */

248     public void setLogWriter(PrintWriter JavaDoc out) throws SQLException JavaDoc
249     {
250         printer = out;
251     }
252
253     /*
254     ** Reference methods etc.
255     */

256
257     /*
258      * Object Factory method
259      */

260
261     /**
262         Re-Create Cloudscape datasource given a reference.
263
264         @param obj The possibly null object containing location or reference
265         information that can be used in creating an object.
266         @param name The name of this object relative to nameCtx, or null if no
267         name is specified.
268         @param nameCtx The context relative to which the name parameter is
269         specified, or null if name is relative to the default initial context.
270         @param environment The possibly null environment that is used in
271         creating the object.
272
273         @return One of the Cloudscape datasource object created; null if an
274         object cannot be created.
275
276         @exception Exception if this object factory encountered an exception
277         while attempting to create an object, and no other object factories are
278         to be tried.
279      */

280     public Object JavaDoc getObjectInstance(Object JavaDoc obj,
281                                     Name JavaDoc name,
282                                     Context JavaDoc nameCtx,
283                                     Hashtable JavaDoc environment)
284          throws Exception JavaDoc
285     {
286         Reference JavaDoc ref = (Reference JavaDoc)obj;
287         String JavaDoc classname = ref.getClassName();
288
289         Object JavaDoc ds = Class.forName(classname).newInstance();
290
291         for (Enumeration JavaDoc e = ref.getAll(); e.hasMoreElements(); ) {
292             
293             RefAddr JavaDoc attribute = (RefAddr JavaDoc) e.nextElement();
294
295             String JavaDoc propertyName = attribute.getType();
296
297             String JavaDoc value = (String JavaDoc) attribute.getContent();
298
299             String JavaDoc methodName = "set" + propertyName.substring(0,1).toUpperCase(java.util.Locale.ENGLISH) + propertyName.substring(1);
300
301             Method m;
302             
303             Object JavaDoc argValue;
304             try {
305                 m = ds.getClass().getMethod(methodName, STRING_ARG);
306                 argValue = value;
307             } catch (NoSuchMethodException JavaDoc nsme) {
308                 try {
309                     m = ds.getClass().getMethod(methodName, INT_ARG);
310                     argValue = Integer.valueOf(value);
311                 } catch (NoSuchMethodException JavaDoc nsme2) {
312                     m = ds.getClass().getMethod(methodName, BOOLEAN_ARG);
313                     argValue = Boolean.valueOf(value);
314                 }
315             }
316             m.invoke(ds, new Object JavaDoc[] { argValue });
317         }
318
319         return ds;
320     }
321
322     /**
323         Referenceable method.
324
325         @exception NamingException cannot find named object
326      */

327     public final Reference JavaDoc getReference() throws NamingException JavaDoc
328     {
329         // These fields will be set by the JNDI server when it decides to
330
// materialize a data source.
331
Reference JavaDoc ref = new Reference JavaDoc(this.getClass().getName(),
332                                       "org.apache.derby.jdbc.ReferenceableDataSource",
333                                       null);
334
335
336         // Look for all the getXXX methods in the class that take no arguments.
337
Method[] methods = this.getClass().getMethods();
338
339         for (int i = 0; i < methods.length; i++) {
340
341             Method m = methods[i];
342
343             // only look for simple getter methods.
344
if (m.getParameterTypes().length != 0)
345                 continue;
346
347             // only non-static methods
348
if (Modifier.isStatic(m.getModifiers()))
349                 continue;
350
351             // Only getXXX methods
352
String JavaDoc methodName = m.getName();
353             if ((methodName.length() < 5) || !methodName.startsWith("get"))
354                 continue;
355
356
357
358             Class JavaDoc returnType = m.getReturnType();
359
360             if (Integer.TYPE.equals(returnType) || STRING_ARG[0].equals(returnType) || Boolean.TYPE.equals(returnType)) {
361
362                 // setSomeProperty
363
// 01234
364

365                 String JavaDoc propertyName = methodName.substring(3,4).toLowerCase(java.util.Locale.ENGLISH).concat(methodName.substring(4));
366
367                 try {
368                     Object JavaDoc ov = m.invoke(this, null);
369
370                     //Need to check for nullability for all the properties, otherwise
371
//rather than null, "null" string gets stored in jndi.
372
if (ov != null) {
373                         ref.add(new StringRefAddr JavaDoc(propertyName, ov.toString()));
374                     }
375                 } catch (IllegalAccessException JavaDoc iae) {
376                 } catch (InvocationTargetException ite) {
377                 }
378
379
380             }
381         }
382
383         return ref;
384     }
385
386
387     void update() {
388     }
389
390     /**
391         Return a connection for the Cloudscape family of data source implementations.
392     */

393     java.sql.Connection JavaDoc getConnection(String JavaDoc username, String JavaDoc password, boolean requestPassword) throws SQLException JavaDoc {
394         return null;
395     }
396
397 }
398
Popular Tags