KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > persist > db > connectionpool > J2EEDatabaseConnectionFactoryImpl


1 /*
2  * Copyright (c) 2005 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: J2EEDatabaseConnectionFactoryImpl.java,v 1.6 2007/01/07 06:14:58 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program 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 General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.persist.db.connectionpool;
23
24 import java.sql.Connection JavaDoc;
25 import java.sql.SQLException JavaDoc;
26 import java.util.logging.Level JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28
29 import javax.naming.InitialContext JavaDoc;
30 import javax.naming.NamingException JavaDoc;
31 import javax.sql.DataSource JavaDoc;
32 import javax.transaction.SystemException JavaDoc;
33
34 import org.opensubsystems.core.error.OSSDatabaseAccessException;
35 import org.opensubsystems.core.error.OSSException;
36 import org.opensubsystems.core.util.J2EEUtils;
37 import org.opensubsystems.core.util.Log;
38
39 /**
40  * Base class for implementation of j2ee factories for retrieving and returning of
41  * database connections, which are maintained in a pool of always ready connections.
42  *
43  * @version $Id: J2EEDatabaseConnectionFactoryImpl.java,v 1.6 2007/01/07 06:14:58 bastafidli Exp $
44  * @author Julo Legeny
45  * @code.reviewer Miroslav Halas
46  * @code.reviewed 1.3 2005/11/08 06:12:47 bastafidli
47  */

48 public class J2EEDatabaseConnectionFactoryImpl extends PooledDatabaseConnectionFactoryImpl
49 {
50    // Cached values ////////////////////////////////////////////////////////////
51

52    /**
53     * Logger for this class
54     */

55    private static Logger JavaDoc s_logger = Log.getInstance(J2EEDatabaseConnectionFactoryImpl.class);
56    
57    /**
58     * Prefix of the data source that will be used for all data sources
59     * specified in JBoss server.
60     */

61    public static final String JavaDoc DATASOURCE_NAME_PREFIX_JBOSS = "java:/";
62
63    /**
64     * Prefix of the data source that will be used for all data sources
65     * specified in IBM WebSphere server.
66     * Originally WebSphere allowed to access datasources using JNDI name
67     * jdbc/datasourcename. Since version 6 WebSPphere prints warning that
68     * this naming convention and a full JNDI referrence should be used, see
69     * http://publib.boulder.ibm.com/infocenter/wasinfo/v6r0/topic/com.ibm.websphere.express.doc/info/exp/ae/rdat_jnditips.html
70     *
71     * I have tried to change this to java:comp/env/jdbc/ as described in
72     * http://publib.boulder.ibm.com/infocenter/wasinfo/v6r0/topic/com.ibm.websphere.express.doc/info/exp/ae/tdat_accdfac.html
73     * but when the war file was deployed in WebSphere, the application couldn't
74     * find the datasource.
75     */

76    public static final String JavaDoc DATASOURCE_NAME_PREFIX_WEBSPHERE = "jdbc/";
77    
78    // Public bethods ///////////////////////////////////////////////////////////
79

80    /**
81     * {@inheritDoc}
82     */

83    public String JavaDoc getRealDatabaseDriver(
84    )
85    {
86       // TODO: For Julo: We should be able to find this information by
87
// connecting to JMX MBean for a given data source and find out the
88
// information from the datasource
89
// If the datasource driver is spy, then we can read the spy properties
90
// to find out the real driver
91
return super.getRealDatabaseDriver();
92    }
93
94    /**
95     * {@inheritDoc}
96     */

97    public String JavaDoc getDatabaseDriver(
98    )
99    {
100       // TODO: For Julo: We should be able to find this information by
101
// connecting to JMX MBean for a given data source and find out the
102
// information from the datasource
103
return super.getDatabaseDriver();
104    }
105
106    /**
107     * {@inheritDoc}
108     */

109    public String JavaDoc getDatabaseURL(
110    )
111    {
112       // TODO: For Julo: We should be able to find this information by
113
// connecting to JMX MBean for a given data source and find out the
114
// information from the datasource
115
return super.getDatabaseURL();
116    }
117
118    /**
119     * {@inheritDoc}
120     */

121    public String JavaDoc getDatabaseAdminUser(
122    )
123    {
124       // TODO: For Julo: Finish this
125
return super.getDatabaseAdminUser();
126    }
127
128    /**
129     * {@inheritDoc}
130     */

131    public String JavaDoc getDatabaseAdminPassword(
132    )
133    {
134       // TODO: For Julo: Finish this
135
return super.getDatabaseAdminPassword();
136    }
137
138    /**
139     * {@inheritDoc}
140     */

141    public String JavaDoc getDatabaseUser(
142    )
143    {
144       // TODO: For Julo: We should be able to find this information by
145
// connecting to JMX MBean for a given data source and find out the
146
// information from the datasource
147
return super.getDatabaseUser();
148    }
149
150    /**
151     * {@inheritDoc}
152     */

153    public String JavaDoc getDatabasePassword(
154    )
155    {
156       // TODO: For Julo: Finish this
157
return super.getDatabasePassword();
158    }
159
160    // Helper bethods ///////////////////////////////////////////////////////////
161

162    /**
163     * {@inheritDoc}
164     */

165    protected Connection JavaDoc getPooledConnection(
166       ConnectionPoolDefinition connectionpool
167    ) throws OSSDatabaseAccessException
168    {
169       Connection JavaDoc conReturn;
170
171       try
172       {
173          conReturn = ((DataSource JavaDoc)connectionpool.getConnectionPool()).getConnection();
174       }
175       catch (SQLException JavaDoc sqlExc)
176       {
177          throw new OSSDatabaseAccessException("Cannot get database connection from pool.",
178                                               sqlExc);
179       }
180       
181       return conReturn;
182    }
183
184    /**
185     * {@inheritDoc}
186     */

187    protected Connection JavaDoc getPooledConnection(
188       ConnectionPoolDefinition connectionpool,
189       String JavaDoc strUser,
190       String JavaDoc strPassword
191    ) throws OSSDatabaseAccessException
192    {
193       Connection JavaDoc conReturn;
194
195       try
196       {
197          DataSource JavaDoc source;
198          
199          if (connectionpool != null)
200          {
201             source = (DataSource JavaDoc)connectionpool.getConnectionPool();
202             if (source != null)
203             {
204                conReturn = source.getConnection(strUser, strPassword);
205             }
206             else
207             {
208                // This is a normal situation e.g. in Jonas when if the user doesn't
209
// exists Jonas doesn't initialize the datasource
210
throw new OSSDatabaseAccessException(
211                             "Connection pool "
212                             + connectionpool.getConnectionPoolName()
213                             + " doesn't exist. Maybe it wasn't initialized yet.");
214             }
215          }
216          else
217          {
218             // This is a normal situation e.g. in Jonas when if the user doesn't
219
// exists Jonas doesn't initialize the datasource
220
throw new OSSDatabaseAccessException("Connection pool doesn't exist."
221                                                  + " Maybe it wasn't initialized yet.");
222          }
223       }
224       catch (SQLException JavaDoc sqlExc)
225       {
226          throw new OSSDatabaseAccessException(
227                       "Cannot get database connection from pool for specified"
228                       + " user/password.", sqlExc);
229       }
230       
231       return conReturn;
232    }
233
234    /**
235     * {@inheritDoc}
236     */

237    protected Object JavaDoc createConnectionPool(
238       String JavaDoc strConnectionPoolName,
239       String JavaDoc strDriverName,
240       String JavaDoc strUrl,
241       String JavaDoc strUser,
242       String JavaDoc strPassword
243    ) throws OSSException
244    {
245       // Try to check if particular pool exists (connect to the data source)
246
// and try to retrieve connection from it (and return immediately this
247
// connection). If it will pass it means that connection pool exists.
248
InitialContext JavaDoc context = null;
249       DataSource JavaDoc dsDataSource = null;
250       StringBuffer JavaDoc dataSourceName = new StringBuffer JavaDoc();
251       
252       try
253       {
254          
255          int iActualServerType = J2EEUtils.getJ2EEServerType();
256          
257          switch (iActualServerType)
258          {
259             case J2EEUtils.J2EE_SERVER_JBOSS:
260             {
261                // Add prefix for JBoss server.
262
dataSourceName.append(DATASOURCE_NAME_PREFIX_JBOSS);
263                break;
264             }
265             case J2EEUtils.J2EE_SERVER_WEBSPHERE:
266             {
267                // Add prefix for IBM WebSphere server.
268
dataSourceName.append(DATASOURCE_NAME_PREFIX_WEBSPHERE);
269                break;
270             }
271             default:
272             {
273                // Default don't add prefix. For JOnAS and BEA WebLogic servers
274
// will be used pure datasource name.
275
break;
276             }
277          }
278          
279          dataSourceName.append(strConnectionPoolName);
280          
281          s_logger.finest("Looking up datasource " + dataSourceName.toString());
282
283          // Obtain the DataSource object associated with the logical name.
284
context = new InitialContext JavaDoc();
285          dsDataSource = (DataSource JavaDoc) context.lookup(dataSourceName.toString());
286
287          s_logger.fine("Found datasource " + dataSourceName.toString());
288          // Given the logical name for the resource, the lookup method returns
289
// the DataSource object that is bound to the JNDI name in the directory.
290

291          // Get the Connection object from the DataSource object.
292
}
293       catch (NamingException JavaDoc neExc)
294       {
295          s_logger.finest("Datasource " + dataSourceName + " not found.");
296          // This has to be OSSDatabaseAccessException since we can detect it
297
// if user we are using for connection doesn't exist. This exception
298
// is encountered for example in Jonas if the user for the data source
299
// is not created yet
300
throw new OSSDatabaseAccessException(
301                       "Error occured while looking up data source.",
302                       neExc);
303       }
304       finally
305       {
306          try
307          {
308             context.close();
309          }
310          catch (NamingException JavaDoc nExc)
311          {
312             s_logger.log(Level.WARNING, "Unable to close context", nExc);
313          }
314       }
315
316       return dsDataSource;
317    }
318
319    /**
320     * {@inheritDoc}
321     */

322    protected void closeConnectionPool(
323       ConnectionPoolDefinition connectionpool
324    ) throws OSSException
325    {
326       // Here we cannot close connection pool because we are
327
// not create it in this class.
328
// This method will do nothing.
329
}
330
331    /**
332     * {@inheritDoc}
333     */

334    protected void initializeConnection(
335       Connection JavaDoc cntDBConnection,
336       boolean bAutoCommit
337    ) throws SQLException JavaDoc
338    {
339       int iActiveServerType = J2EEUtils.getJ2EEServerType();
340
341       if (iActiveServerType == J2EEUtils.J2EE_SERVER_JBOSS)
342       {
343          try
344          {
345             // Do not call initializeConnection() method we are in transaction.
346
// This is important to do only for JBoss server because there is
347
// problem to call setAutoCommit() method if transaction is in progress.
348
if (!m_transactionFactory.isTransactionInProgress())
349             {
350                super.initializeConnection(cntDBConnection, bAutoCommit);
351             }
352             else
353             {
354                s_logger.finest("Ignoring request to set autocommit to "
355                                + bAutoCommit + " since we are running inside of"
356                                + " JBoss and transaction is in progress.");
357             }
358          }
359          catch (SystemException JavaDoc sExc)
360          {
361             throw new SQLException JavaDoc("Error while getting transaction status.");
362          }
363          catch (OSSException ossExc)
364          {
365             throw new SQLException JavaDoc("Error while getting transaction status.");
366          }
367       }
368       else
369       {
370          super.initializeConnection(cntDBConnection, bAutoCommit);
371       }
372    }
373 }
374
Popular Tags