KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2
3    Derby - Class org.apache.derby.jdbc.EmbeddedSimpleDataSource
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
22 package org.apache.derby.jdbc;
23
24 import org.apache.derby.iapi.jdbc.JDBCBoot;
25 import org.apache.derby.iapi.reference.Attribute;
26 import org.apache.derby.iapi.reference.MessageId;
27
28 import java.sql.Connection JavaDoc;
29 import java.sql.SQLException JavaDoc;
30
31 import java.io.PrintWriter JavaDoc;
32 import java.util.Properties JavaDoc;
33
34 /* -- New jdbc 20 extension types --- */
35 import javax.sql.DataSource JavaDoc;
36
37 import org.apache.derby.iapi.reference.SQLState;
38 import org.apache.derby.iapi.services.i18n.MessageService;
39 import org.apache.derby.impl.jdbc.Util;
40
41 /**
42  *
43  *
44  * EmbeddedSimpleDataSource is Derby's DataSource implementation
45  * for J2ME/CDC/Foundation. It is also supports J2SE platforms.
46  *
47  *
48  * Supports the same properties as EmbeddedDataSource, see that class for details.
49  * <P>
50     EmbeddedSimpleDataSource automatically supports the correct JDBC specification version
51     for the Java Virtual Machine's environment.
52     <UL>
53     <LI> JDBC Optional Package for CDC/Foundation Profile(JSR-169) - J2ME - CDC/Foundation
54     <LI> JDBC 3.0 - Java 2 - JDK 1.4, J2SE 5.0
55     <LI> JDBC 2.0 - Java 2 - JDK 1.2,1.3
56     </UL>
57  * @see EmbeddedDataSource
58  *
59  */

60 public final class EmbeddedSimpleDataSource implements DataSource JavaDoc {
61
62     private String JavaDoc password;
63
64     private String JavaDoc user;
65
66     /**
67      * The database name.
68      *
69      * @serial
70      */

71     private String JavaDoc databaseName;
72
73     /**
74      * The data source name.
75      *
76      * @serial
77      */

78     private String JavaDoc dataSourceName;
79
80     /**
81      * Description of the database.
82      *
83      * @serial
84      */

85     private String JavaDoc description;
86
87     /**
88      * Set to "create" if the database should be created.
89      *
90      * @serial
91      */

92     private String JavaDoc createDatabase;
93
94     /**
95      * Set to "shutdown" if the database should be shutdown.
96      *
97      * @serial
98      */

99     private String JavaDoc shutdownDatabase;
100
101     /**
102      * Cloudscape specific connection attributes.
103      *
104      * @serial
105      */

106     private String JavaDoc connectionAttributes;
107
108     /** instance variables that will not be serialized */
109     transient private PrintWriter JavaDoc printer;
110
111     transient private int loginTimeout;
112
113     // Unlike a DataSource, LocalDriver is shared by all
114
// Cloudscape databases in the same jvm.
115
transient private InternalDriver driver;
116
117     transient private String JavaDoc jdbcurl;
118
119     /**
120      * No-arg constructor.
121      */

122     public EmbeddedSimpleDataSource() {
123     }
124
125     /*
126      * DataSource methods
127      */

128
129     /**
130      * Gets the maximum time in seconds that this data source can wait while
131      * attempting to connect to a database. A value of zero means that the
132      * timeout is the default system timeout if there is one; otherwise it means
133      * that there is no timeout. When a data source object is created, the login
134      * timeout is initially zero.
135      *
136      * @return the data source login time limit
137      * @exception SQLException
138      * if a database access error occurs.
139      */

140     public int getLoginTimeout() throws SQLException JavaDoc {
141         return loginTimeout;
142     }
143
144     /**
145      * Sets the maximum time in seconds that this data source will wait while
146      * attempting to connect to a database. A value of zero specifies that the
147      * timeout is the default system timeout if there is one; otherwise it
148      * specifies that there is no timeout. When a data source object is created,
149      * the login timeout is initially zero.
150      * <P>
151      * Cloudscape ignores this property.
152      *
153      * @param seconds
154      * the data source login time limit
155      * @exception SQLException
156      * if a database access error occurs.
157      */

158     public void setLoginTimeout(int seconds) throws SQLException JavaDoc {
159         loginTimeout = seconds;
160     }
161
162     /**
163      * Get the log writer for this data source.
164      *
165      * <p>
166      * The log writer is a character output stream to which all logging and
167      * tracing messages for this data source object instance will be printed.
168      * This includes messages printed by the methods of this object, messages
169      * printed by methods of other objects manufactured by this object, and so
170      * on. Messages printed to a data source specific log writer are not printed
171      * to the log writer associated with the java.sql.Drivermanager class. When
172      * a data source object is created the log writer is initially null, in
173      * other words, logging is disabled.
174      *
175      * @return the log writer for this data source, null if disabled
176      * @exception SQLException
177      * if a database-access error occurs.
178      */

179     public PrintWriter JavaDoc getLogWriter() throws SQLException JavaDoc {
180         return printer;
181     }
182
183     /**
184      * Set the log writer for this data source.
185      *
186      * <p>
187      * The log writer is a character output stream to which all logging and
188      * tracing messages for this data source object instance will be printed.
189      * This includes messages printed by the methods of this object, messages
190      * printed by methods of other objects manufactured by this object, and so
191      * on. Messages printed to a data source specific log writer are not printed
192      * to the log writer associated with the java.sql.Drivermanager class. When
193      * a data source object is created the log writer is initially null, in
194      * other words, logging is disabled.
195      *
196      * @param out
197      * the new log writer; to disable, set to null
198      * @exception SQLException
199      * if a database-access error occurs.
200      */

201     public void setLogWriter(PrintWriter JavaDoc out) throws SQLException JavaDoc {
202         printer = out;
203     }
204
205     /*
206      * Properties to be seen by Bean - access thru reflection.
207      */

208     /**
209      * Set the database name. Setting this property is mandatory. If a database
210      * named wombat at g:/db needs to be accessed, database name should be set
211      * to "g:/db/wombat". The database will be booted if it is not already
212      * running in the system.
213      *
214      * @param databaseName
215      * the name of the database
216      */

217     public final synchronized void setDatabaseName(String JavaDoc databaseName) {
218         this.databaseName = databaseName;
219         update();
220     }
221
222     public String JavaDoc getDatabaseName() {
223         return databaseName;
224     }
225
226     /**
227      * Set the data source name. The property is not mandatory. It is used for
228      * informational purposes only.
229      *
230      * @param dsn
231      * the name of the data source
232      */

233     public final void setDataSourceName(String JavaDoc dsn) {
234         dataSourceName = dsn;
235     }
236
237     /** @return data source name */
238     public final String JavaDoc getDataSourceName() {
239         return dataSourceName;
240     }
241
242     /**
243      * Set the data source descripton. This property is not mandatory. It is
244      * used for informational purposes only.
245      *
246      * @param desc
247      * the description of the data source
248      */

249     public final void setDescription(String JavaDoc desc) {
250         description = desc;
251     }
252
253     /** @return description */
254     public final String JavaDoc getDescription() {
255         return description;
256     }
257
258     /**
259      * Set the <code>user</code> property for the data source. This is user
260      * name for any data source getConnection() call that takes no arguments.
261      */

262     public final void setUser(String JavaDoc user) {
263         this.user = user;
264     }
265
266     /** @return user */
267     public final String JavaDoc getUser() {
268         return user;
269     }
270
271     /**
272      * Set the <code>password</code> property for the data source. This is
273      * user's password for any data source getConnection() call that takes no
274      * arguments.
275      */

276     public final void setPassword(String JavaDoc password) {
277         this.password = password;
278     }
279
280     /** @return password */
281     public final String JavaDoc getPassword() {
282         return password;
283     }
284
285     /**
286      * Set this property to create a new database. If this property is not set,
287      * the database (identified by databaseName) is assumed to be already
288      * existing.
289      *
290      * @param create
291      * if set to the string "create", this data source will try to
292      * create a new database of databaseName, or boot the database if
293      * one by that name already exists.
294      */

295     public final void setCreateDatabase(String JavaDoc create) {
296         if (create != null
297                 && create.toLowerCase(java.util.Locale.ENGLISH)
298                         .equals("create"))
299             createDatabase = create;
300         else
301             createDatabase = null;
302     }
303
304     /** @return "create" if create is set, or null if not */
305     public final String JavaDoc getCreateDatabase() {
306         return createDatabase;
307     }
308
309     /**
310      * Set this property if one wishes to shutdown the database identified by
311      * databaseName.
312      *
313      * @param shutdown
314      * if set to the string "shutdown", this data source will
315      * shutdown the database if it is running.
316      */

317     public final void setShutdownDatabase(String JavaDoc shutdown) {
318         if (shutdown != null && shutdown.equalsIgnoreCase("shutdown"))
319             shutdownDatabase = shutdown;
320         else
321             shutdownDatabase = null;
322     }
323
324     /** @return "shutdown" if shutdown is set, or null if not */
325     public final String JavaDoc getShutdownDatabase() {
326         return shutdownDatabase;
327     }
328
329     /**
330      * Set this property to pass in more Cloudscape specific connection URL
331      * attributes.
332     <BR>
333    Any attributes that can be set using a property of this DataSource implementation
334    (e.g user, password) should not be set in connectionAttributes. Conflicting
335    settings in connectionAttributes and properties of the DataSource will lead to
336    unexpected behaviour.
337      *
338      * @param prop
339      * set to the list of Cloudscape connection attributes separated
340      * by semi-colons. E.g., to specify an encryption bootPassword of
341      * "x8hhk2adf", and set upgrade to true, do the following:
342      *
343      * <PRE>
344      *
345      * ds.setConnectionAttributes("bootPassword=x8hhk2adf;upgrade=true");
346      *
347      * </PRE>
348      *
349      * See Cloudscape's documentation for complete list.
350      */

351     public final void setConnectionAttributes(String JavaDoc prop) {
352         connectionAttributes = prop;
353         update();
354     }
355
356     /** @return Cloudscape specific connection URL attributes */
357     public final String JavaDoc getConnectionAttributes() {
358         return connectionAttributes;
359     }
360
361     /*
362      * DataSource methods
363      */

364
365     /**
366      * Attempt to establish a database connection.
367      *
368      * @return a Connection to the database
369      * @exception SQLException
370      * if a database-access error occurs.
371      */

372     public final Connection JavaDoc getConnection() throws SQLException JavaDoc {
373         return this.getConnection(getUser(), getPassword());
374     }
375
376     /**
377      * Attempt to establish a database connection with the given username and
378      * password. If the attributeAsPassword property is set to true then the
379      * password argument is taken to be a list of connection attributes with the
380      * same format as the connectionAttributes property.
381      *
382      *
383      * @param username
384      * the database user on whose behalf the Connection is being made
385      * @param password
386      * the user's password
387      * @return a Connection to the database
388      * @exception SQLException
389      * if a database-access error occurs.
390      */

391     public final Connection JavaDoc getConnection(String JavaDoc username, String JavaDoc password)
392             throws SQLException JavaDoc {
393
394         Properties JavaDoc info = new Properties JavaDoc();
395         if (username != null)
396             info.put(Attribute.USERNAME_ATTR, username);
397
398         if (password != null)
399             info.put(Attribute.PASSWORD_ATTR, password);
400
401         if (createDatabase != null)
402             info.put(Attribute.CREATE_ATTR, "true");
403         if (shutdownDatabase != null)
404             info.put(Attribute.SHUTDOWN_ATTR, "true");
405
406         Connection JavaDoc conn = findDriver().connect(jdbcurl, info);
407
408         // JDBC driver's getConnection method returns null if
409
// the driver does not handle the request's URL.
410
if (conn == null)
411             throw Util.generateCsSQLException(SQLState.PROPERTY_INVALID_VALUE,
412                     Attribute.DBNAME_ATTR, getDatabaseName());
413
414         return conn;
415     }
416
417     private InternalDriver findDriver() throws SQLException JavaDoc {
418         String JavaDoc url = jdbcurl;
419
420         if (driver == null || !driver.acceptsURL(url)) {
421             synchronized (this) {
422                 // The driver has either never been booted, or it has been
423
// shutdown by a 'jdbc:derby:;shutdown=true'
424
if (driver == null || !driver.acceptsURL(url)) {
425                     
426                     
427                     new JDBCBoot().boot(Attribute.PROTOCOL, System.err);
428                     
429                     // If we know the driver, we loaded it. Otherwise only
430
// work if DriverManager has already loaded it.
431

432                     driver = InternalDriver.activeDriver();
433                     
434                     if (driver == null)
435                         throw new SQLException JavaDoc(MessageService.getTextMessage(MessageId.CORE_JDBC_DRIVER_UNREGISTERED));
436                 }
437             }
438         }
439         return driver;
440         // else driver != null and driver can accept url
441
}
442
443     private void update() {
444         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(64);
445
446         sb.append(Attribute.PROTOCOL);
447
448         // Set the database name from the databaseName property
449
String JavaDoc dbName = getDatabaseName();
450
451         if (dbName != null) {
452             dbName = dbName.trim();
453         }
454
455         if (dbName == null || dbName.length() == 0) {
456             // need to put something in so that we do not allow the
457
// database name to be set from the request or from the
458
// connection attributes.
459

460             // this space will selected as the database name (and trimmed to an
461
// empty string)
462
// See the getDatabaseName() code in InternalDriver. Since this is a
463
// non-null
464
// value, it will be selected over any databaseName connection
465
// attribute.
466
dbName = " ";
467         }
468
469         sb.append(dbName);
470
471         String JavaDoc connAttrs = getConnectionAttributes();
472         if (connAttrs != null) {
473             connAttrs = connAttrs.trim();
474             if (connAttrs.length() != 0) {
475                 sb.append(';');
476                 sb.append(connectionAttributes);
477             }
478         }
479
480         jdbcurl = sb.toString();
481     }
482 }
483
484
Popular Tags