KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > jdo > spi > persistence > support > sqlstore > impl > ConnectionFactoryImpl


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * ConnectionFactoryImpl.java
26  *
27  * Created on March 10, 2000, 5:09 PM
28  */

29  
30 package com.sun.jdo.spi.persistence.support.sqlstore.impl;
31
32 import java.lang.String JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.sql.Connection JavaDoc;
35 import java.sql.DatabaseMetaData JavaDoc;
36 import java.sql.SQLException JavaDoc;
37 import java.util.ResourceBundle JavaDoc;
38
39
40 import com.sun.jdo.api.persistence.support.*;
41 import com.sun.jdo.spi.persistence.support.sqlstore.connection.ConnectionManager;
42 import com.sun.jdo.spi.persistence.utility.I18NHelper;
43
44 /**
45  *
46  * @author Craig Russell
47  * @version 0.1
48  */

49 public class ConnectionFactoryImpl implements ConnectionFactory, java.io.Serializable JavaDoc {
50
51     // Delegate all connection variables to ConnectionManager:
52

53         private String JavaDoc URL = null;
54         private String JavaDoc userName = null;
55         private String JavaDoc password = null;
56         private String JavaDoc driverName = null;
57         private int maxPool = 0;
58         private int minPool = 0;
59         private int msInterval = 0;
60         private int loginTimeout = 0;
61         private int msWait = 0;
62         private int _txIsolation = -1;
63         private PrintWriter JavaDoc logWriter = null;
64
65     private transient boolean _configured = false;
66     private transient ConnectionManager connectionManager = null;
67
68         /**
69          * I18N message handler
70          */

71         private transient final static ResourceBundle JavaDoc messages = I18NHelper.loadBundle(
72                                 ConnectionFactoryImpl.class);
73
74     
75
76   /**
77    * Creates new default <code>ConnectionFactoryImpl</code> object
78    */

79   public ConnectionFactoryImpl()
80   {
81     //connectionManager = new ConnectionManager();
82
}
83
84   /**
85    * Creates new <code>ConnectionFactoryImpl</code> object with user info
86    * @param URL connection URL
87    * @param userName database user
88    * @param password database user password
89    * @param driverName driver name
90    */

91   public ConnectionFactoryImpl(
92         String JavaDoc URL,
93         String JavaDoc userName,
94         String JavaDoc password,
95         String JavaDoc driverName
96         )
97   {
98         this.driverName = driverName;
99         this.URL = URL;
100         this.userName = userName;
101         this.password = password;
102
103   }
104
105   /**
106    * Creates new <code>ConnectionFactoryImpl</code> object with user and connection info
107    * @param URL connection URL
108    * @param userName database user
109    * @param password database user password
110    * @param driverName driver name
111    * @param minPool minimum number of connections
112    * @param maxPool maximum number of connections
113    */

114   public ConnectionFactoryImpl(
115         String JavaDoc URL,
116         String JavaDoc userName,
117         String JavaDoc password,
118         String JavaDoc driverName,
119         int minPool,
120                 int maxPool
121         )
122   {
123         this.driverName = driverName;
124         this.URL = URL;
125         this.userName = userName;
126         this.password = password;
127         this.minPool = minPool;
128         this.maxPool = maxPool;
129
130   }
131
132   /**
133    * Sets JDBC driver name
134    * @param driverName JDBC driver name
135    */

136   public void setDriverName (String JavaDoc driverName)
137   {
138     // REMOVE WHEN SUPPORTED:
139
//unsupported();
140

141     assertNotConfigured();
142     // Delegate to ConnectionManager: this.driverName = driverName;
143
if(connectionManager == null)
144     {
145         this.driverName = driverName;
146     }
147     else
148     {
149         try {
150             connectionManager.setDriverName(driverName);
151         } catch (Exception JavaDoc e) {
152             throw new JDOFatalException(null, e);
153         }
154     }
155   }
156
157   /**
158    * Returns JDBC driver name
159    * @return driver name
160    */

161   public String JavaDoc getDriverName ()
162   {
163     return driverName;
164     //return connectionManager.getDriverName();
165
}
166
167   
168   /**
169    * Sets JDBC connection URL
170    * @param URL connection URL
171    */

172   public void setURL (String JavaDoc URL)
173   {
174     // REMOVE WHEN SUPPORTED:
175
//unsupported();
176

177     assertNotConfigured();
178     // Delegate to ConnectionManager: this.URL = URL;
179
if(connectionManager == null)
180         {
181                 this.URL = URL;
182         }
183         else
184         {
185                 try {
186                     connectionManager.setURL(URL);
187         } catch (Exception JavaDoc e) {
188             throw new JDOFatalException(null, e);
189         }
190     }
191   }
192
193   /**
194    * Returns connection URL
195    * @return connection URL
196    */

197   public String JavaDoc getURL ()
198   {
199     return URL;
200     //return connectionManager.getURL();
201
}
202
203   
204   /**
205    * Sets database user
206    * @param userName database user
207    */

208   public void setUserName (String JavaDoc userName)
209   {
210     // REMOVE WHEN SUPPORTED:
211
//unsupported();
212

213     assertNotConfigured();
214     // Delegate to ConnectionManager: this.userName = userName;
215
if(connectionManager == null)
216         {
217                 this.userName = userName;
218     }
219     else
220         {
221                 try {
222                     connectionManager.setUserName(userName);
223         } catch (Exception JavaDoc e) {
224             throw new JDOFatalException(null, e);
225         }
226     }
227   }
228
229   /**
230    * Returns database user name
231    * @return current database user name
232    */

233   public String JavaDoc getUserName ()
234   {
235     return userName;
236     //return connectionManager.getUserName();
237
}
238
239   
240   /**
241    * Sets database user password
242    * @param password database user password
243    */

244   public void setPassword (String JavaDoc password)
245   {
246     // REMOVE WHEN SUPPORTED:
247
//unsupported();
248

249     assertNotConfigured();
250     // Delegate to ConnectionManager: this.password = password;
251
if(connectionManager == null)
252         {
253                 this.password = password;
254         }
255         else
256         {
257         try {
258                     connectionManager.setPassword(password);
259         } catch (Exception JavaDoc e) {
260             throw new JDOFatalException(null, e);
261         }
262     }
263   }
264
265   
266   /**
267    * Sets minimum number of connections in the connection pool
268    * @param minPool minimum number of connections
269    */

270   public void setMinPool (int minPool)
271   {
272     assertNotConfigured();
273     if(connectionManager == null) {
274                 // Nothing to do yet
275
this.minPool = minPool;
276                 return;
277         }
278
279     // Delegate to ConnectionManager: this.minPool = minPool;
280
try {
281                 connectionManager.setMinPool(minPool);
282     } catch (Exception JavaDoc e) {
283         throw new JDOFatalException(null, e);
284     }
285   }
286
287   /**
288    * Returns minimum number of connections in the connection pool
289    * @return connection minPool
290    */

291   public int getMinPool ()
292   {
293     return minPool;
294     //return connectionManager.getMinPool();
295
}
296
297   
298   /**
299    * Sets maximum number of connections in the connection pool
300    * @param maxPool maximum number of connections
301    */

302   public void setMaxPool (int maxPool)
303   {
304     assertNotConfigured();
305     if(connectionManager == null) {
306                 // Nothing to do yet
307
this.maxPool = maxPool;
308                 return;
309         }
310
311     // Delegate to ConnectionManager: this.maxPool = maxPool;
312
try {
313                 connectionManager.setMaxPool(maxPool);
314     } catch (Exception JavaDoc e) {
315         throw new JDOFatalException(null, e);
316     }
317   }
318
319   /**
320    * Returns maximum number of connections in the connection pool
321    * @return connection maxPool
322    */

323   public int getMaxPool ()
324   {
325     return maxPool;
326     // return connectionManager.getMaxPool();
327
}
328
329   
330   /**
331    * Sets the amount of time, in milliseconds, between the connection
332    * manager's attempts to get a pooled connection.
333    * @param msInterval the interval between attempts to get a database
334    * connection, in milliseconds.
335    */

336   public void setMsInterval (int msInterval)
337   {
338     assertNotConfigured();
339     if(connectionManager == null) {
340                 // Nothing to do yet
341
this.msInterval = msInterval;
342                 return;
343         }
344
345     // Delegate to ConnectionManager: this.msInterval = msInterval;
346
try {
347                 connectionManager.setMsInterval(msInterval);
348     } catch (Exception JavaDoc e) {
349         throw new JDOFatalException(null, e);
350     }
351   }
352
353   /**
354    * Returns the amount of time, in milliseconds, between the connection
355    * manager's attempts to get a pooled connection.
356    * @return the length of the interval between tries in milliseconds
357    */

358   public int getMsInterval ()
359   {
360     if (connectionManager == null)
361         return msInterval;
362
363     return connectionManager.getMsInterval();
364   }
365
366   
367   /**
368    * Sets the number of milliseconds to wait for an available connection
369    * from the connection pool before throwing an exception
370    * @param msWait number in milliseconds
371    */

372   public void setMsWait (int msWait)
373   {
374     assertNotConfigured();
375     if(connectionManager == null) {
376                 // Nothing to do yet
377
this.msWait = msWait;
378                 return;
379         }
380
381     // Delegate to ConnectionManager: this.msWait = msWait;
382
try {
383                 connectionManager.setMsWait(msWait);
384     } catch (Exception JavaDoc e) {
385         throw new JDOFatalException(null, e);
386     }
387   }
388
389   /**
390    * Returns the number of milliseconds to wait for an available connection
391    * from the connection pool before throwing an exception
392    * @return number in milliseconds
393    */

394   public int getMsWait ()
395   {
396     if (connectionManager == null)
397                 return msWait;
398
399     return connectionManager.getMsWait();
400   }
401
402   
403   /**
404    * Sets the LogWriter to which messages should be sent
405    * @param pw logWriter
406    */

407   public void setLogWriter (PrintWriter JavaDoc logWriter)
408   {
409     assertNotConfigured();
410     this.logWriter = logWriter; //RESOLVE
411
}
412
413   /**
414    * Returns the LogWriter to which messages should be sent
415    * @return logWriter
416    */

417   public PrintWriter JavaDoc getLogWriter ()
418   {
419     return logWriter;
420   }
421
422  
423   /**
424    * Sets the number of seconds to wait for a new connection to be
425    * established to the data source
426    * @param loginTimeout wait time in seconds
427    */

428   public void setLoginTimeout (int loginTimeout)
429   {
430     assertNotConfigured();
431     if(connectionManager == null) {
432                 // Nothing to do yet
433
this.loginTimeout = loginTimeout;
434                 return;
435         }
436
437     // Delegate to ConnectionManager: this.loginTimeout = loginTimeout;
438
try {
439                 connectionManager.setLoginTimeout(loginTimeout);
440     } catch (Exception JavaDoc e) {
441         throw new JDOFatalException(null, e);
442     }
443   }
444
445   /**
446    * Returns the number of seconds to wait for a new connection to be
447    * established to the data source
448    * @return wait time in seconds
449    */

450   public int getLoginTimeout ()
451   {
452     if (connectionManager == null)
453                 return loginTimeout;
454
455     try {
456                 return connectionManager.getLoginTimeout();
457     } catch (Exception JavaDoc e) {
458                 return 0;
459     }
460   }
461   /**
462    **
463    * Sets transaction isolation level for all connections of this ConnectionFactory.
464    * All validation is done by java.sql.Connection itself, so e.g. while Oracle
465    * will not allow to set solation level to TRANSACTION_REPEATABLE_READ, this method
466    * does not have any explicit restrictions
467    *
468    * @param level - one of the java.sql.Connection.TRANSACTION_* isolation values
469    */

470   public void setTransactionIsolation (int level)
471   {
472     assertNotConfigured();
473     if(connectionManager == null) {
474         // Nothing to do yet
475
_txIsolation = level;
476         return;
477     }
478
479     // verify that database supports it
480
Connection JavaDoc conn = null;
481     try {
482         conn = connectionManager.getConnection();
483         DatabaseMetaData JavaDoc dbMetaData = conn.getMetaData();
484         if(dbMetaData.supportsTransactionIsolationLevel(level))
485         {
486                     _txIsolation = level;
487         }
488         else
489         {
490             throw new JDOFatalException(I18NHelper.getMessage(messages,
491                                 "connectionefactoryimpl.isolationlevel_notsupported", //NOI18N
492
level));
493         }
494     } catch (Exception JavaDoc e) {
495         throw new JDOFatalException(null, e);
496     }
497     finally
498     {
499         closeConnection(conn);
500     }
501   }
502
503   /**
504    * Gets this ConnectionFactory's current transaction isolation level.
505    * @return the current transaction isolation mode value as java.sql.Connection.TRANSACTION_*
506    */

507   public int getTransactionIsolation ()
508   {
509     if (connectionManager == null)
510                 return _txIsolation;
511
512     Connection JavaDoc conn = null;
513     try {
514         // Delegate to the Connection
515
if (_txIsolation == -1)
516         {
517             synchronized(this)
518             {
519             //Double check that it was not set before
520
if (_txIsolation == -1)
521             {
522                 conn = connectionManager.getConnection();
523                 _txIsolation = conn.getTransactionIsolation();
524             }
525             }
526         }
527
528         return _txIsolation;
529     } catch (Exception JavaDoc e) {
530                 throw new JDOFatalException(null, e);
531     }
532     finally
533     {
534         closeConnection(conn);
535     }
536   }
537
538
539   /**
540    * Returns java.sql.Connection
541    * @return connection as java.sql.Connection
542    */

543   public Connection JavaDoc getConnection()
544   {
545     // Delegate to ConnectionManager
546
try {
547         if (connectionManager == null)
548             initialize();
549
550                 Connection JavaDoc conn = connectionManager.getConnection();
551         conn.setTransactionIsolation(_txIsolation);
552
553         return conn;
554
555     } catch (SQLException JavaDoc e) {
556         String JavaDoc sqlState = e.getSQLState();
557         int errorCode = e.getErrorCode();
558
559         if (sqlState == null)
560         {
561             throw new JDODataStoreException(I18NHelper.getMessage(messages,
562                                 "connectionefactoryimpl.sqlexception", "null", "" + errorCode), e); //NOI18N
563
}
564         else
565         {
566             throw new JDODataStoreException(I18NHelper.getMessage(messages,
567                                 "connectionefactoryimpl.sqlexception", sqlState, "" + errorCode), e); //NOI18N
568
}
569     } catch (Exception JavaDoc e) {
570                 throw new JDOCanRetryException(I18NHelper.getMessage(messages,
571                                 "connectionefactoryimpl.getconnection"), e); //NOI18N
572
}
573   }
574
575   /**
576   * Determines whether obj is a ConnectionFactoryImpl with the same configuration
577   *
578   * @param obj The possibly null object to check.
579   * @return true if obj is equal to this ConnectionFactoryImpl; false otherwise.
580   */

581   public boolean equals(Object JavaDoc obj) {
582     if ((obj != null) && (obj instanceof ConnectionFactoryImpl) ) {
583         ConnectionFactoryImpl cf = (ConnectionFactoryImpl)obj;
584         return (cf.URL.equals(this.URL) && cf.userName.equals(this.userName) && cf.driverName.equals(this.driverName) && cf.password.equals(this.password));
585     }
586     return false;
587   }
588
589   /**
590   * Computes the hash code of this ConnectionFactoryImpl.
591   *
592   * @return A hash code of the owning ConnectionFactoryImpl as an int.
593   */

594   public int hashCode() {
595     return URL.hashCode() + userName.hashCode() + password.hashCode() + driverName.hashCode();
596   }
597
598
599     /**
600      * INTERNAL
601      * Marks Connectionfactory as fully configured
602      * @param flag boolean flag
603      */

604     public void configured(boolean flag)
605     {
606         _configured = flag;
607     }
608
609         /**
610          * INTERNAL
611          * Asserts that change to the property is allowed
612          */

613         private void assertNotConfigured() {
614                 if ( _configured) {
615                         throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages,
616                                 "persistencemanagerfactoryimpl.configured")); //NOI18N
617
}
618         }
619
620         /**
621          * INTERNAL
622          * Asserts that MsWait and MsInterval are properly configured
623          */

624         private void assertConnectionWait() {
625                 if ( msWait < 0 )
626                 {
627                         throw new JDOUserException(I18NHelper.getMessage(messages,
628                                              "connection.connectionmanager.mswaitvalue")); // NOI18N
629
}
630                 else if ( msInterval < 0 || msInterval > msWait || (msWait > 0 && msInterval == 0) )
631                 {
632                                 throw new JDOUserException(I18NHelper.getMessage(messages,
633                                              "connection.connectionmanager.msintervalvalue")); // NOI18N
634
}
635         }
636
637
638     /**
639          * INTERNAL
640      * Attempts to create new connectionManager
641          * Throws JDOFatalException
642      */

643     private synchronized void initialize() {
644         // If connectionManager was already initialized by another thread
645
if (connectionManager != null)
646             return;
647
648         try {
649         // Verify msWait/msInterval values
650
assertConnectionWait();
651
652                 // need to use this constructor, as it calls internaly startUp() method
653
// to initialize extra variables and enable pooling
654
//java.sql.DriverManager.setLogWriter(logWriter);
655
connectionManager = new ConnectionManager(
656                                 driverName,
657                                 URL,
658                                 userName,
659                                 password,
660                                 minPool,
661                                 maxPool
662                         );
663             // MsWait MUST be set BEFORE MsInterval
664
connectionManager.setMsWait(this.msWait);
665             connectionManager.setMsInterval(this.msInterval);
666                         connectionManager.setLoginTimeout(this.loginTimeout);
667
668                         if (_txIsolation > 0)
669                                 setTransactionIsolation(_txIsolation);
670                         else
671                                 _txIsolation = getTransactionIsolation();
672
673             // finished all configuration
674
this.configured(true);
675
676             } catch (JDOException e) {
677                     throw e;
678             } catch (Exception JavaDoc e) {
679                     throw new JDOFatalException(null, e);
680         }
681     }
682
683     /**
684          * INTERNAL
685          * Throws JDOUnsupportedOptionException
686      */

687     private void unsupported() {
688         throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages,
689             "persistencemanagerfactoryimpl.notsupported")); //NOI18N
690
}
691
692     /**
693          * Close a connection
694          */

695         private void closeConnection(Connection JavaDoc conn)
696         {
697                 try
698                 {
699             if (conn != null) conn.close();
700                 }
701                 catch (Exception JavaDoc e)
702                 {
703                         // Recover?
704
}
705  
706                 conn = null;
707  
708         }
709 }
710
Popular Tags