KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sape > carbon > services > sql > connection > NamedDataSourceConnectionFactory


1 /*
2  * The contents of this file are subject to the Sapient Public License
3  * Version 1.0 (the "License"); you may not use this file except in compliance
4  * with the License. You may obtain a copy of the License at
5  * http://carbon.sf.net/License.html.
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is The Carbon Component Framework.
12  *
13  * The Initial Developer of the Original Code is Sapient Corporation
14  *
15  * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
16  */

17
18 package org.sape.carbon.services.sql.connection;
19
20 import java.io.PrintWriter JavaDoc;
21 import java.sql.Connection JavaDoc;
22 import java.sql.SQLException JavaDoc;
23 import java.util.Hashtable JavaDoc;
24
25 import javax.naming.Context JavaDoc;
26 import javax.naming.InitialContext JavaDoc;
27 import javax.naming.NamingException JavaDoc;
28 import javax.sql.DataSource JavaDoc;
29
30 import org.sape.carbon.core.component.ComponentConfiguration;
31 import org.sape.carbon.core.component.lifecycle.Configurable;
32 import org.sape.carbon.core.component.lifecycle.StateTransitionException;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36
37 /**
38  * Decorator Component for a JNDI DataSource. This component should be used as
39  * a <code>javax.sql.DataSource<code>.
40  * On configuration, obtains a JDBC DataSource from JNDI and delegates
41  * requests for connections to it. Note that the DataSource instance is
42  * discarded and re-fetched each time this component is configured.
43  *
44  * Copyright 2002 Sapient
45  * @since carbon 1.0
46  * @author Chris Herron, March 2002
47  * @version $Revision: 1.12 $($Author: dvoet $ / $Date: 2003/05/05 21:21:36 $)
48  */

49 public class NamedDataSourceConnectionFactory
50 implements DataSourceConnectionFactory, Configurable {
51     /**
52      * <p>Stores a reference to the data source retrieve from JNDI. Prevents
53      * further calls to JNDI, thus improving performance on acquiring
54      * connections.</p>
55      */

56     protected DataSource JavaDoc dataSource = null;
57     /**
58      * <p>Stores the (optional) userid used to create the connection from the
59      * managed DataSource object.</p>
60      */

61     protected String JavaDoc dataSourceUserId = null;
62
63     /**
64      * <p>Stores the (optional) password used to create the connection from the
65      * managed DataSource object.</p>
66      */

67     protected String JavaDoc dataSourcePassword = null;
68
69
70     /**
71      * Provides a handle to Apache-commons logger
72      */

73     private Log log = LogFactory.getLog(this.getClass());
74
75     /**
76      * Delegates to the underlying DataSource to obtain a JDBC connection.
77      * If there is a configured dataSourceUserId, uses
78      * <code>this.getConnection(dataSourceUserId, dataSourcePassword)</code> to
79      * to obtain a JDBC connection. If no dataSourceUserId is configured, uses
80      * <code>DataSource.getConnection()</code>.
81      *
82      * @return Connection A JDBC Connection
83      * @throws SQLException When obtaining connection fails
84      */

85     public Connection JavaDoc getConnection()
86             throws SQLException JavaDoc {
87
88         if (log.isTraceEnabled()) {
89             log.trace("Obtaining JDBC Connection");
90         }
91
92         Connection JavaDoc conn = null;
93         //TODO: remove empty string check, since this may be intentional
94
//TODO: config currently returns empty string when it should be null
95
if (null == this.dataSourceUserId
96                 || this.dataSourceUserId.equals("")) {
97
98             conn = dataSource.getConnection();
99         } else {
100             conn = this.getConnection(this.dataSourceUserId,
101                                   this.dataSourcePassword);
102         }
103         return conn;
104     }
105
106     /**
107      * Delegates to the underlying DataSource to obtain a JDBC connection.
108      * Overrides the dataSourceUserId and dataSourcePassword, if configured.
109      *
110      * @param overridingDataSourceUserId The overriding dataSourceUserId
111      * @param overridingDataSourcePassword The overriding dataSourcePassword
112      * @return Connection A JDBC Connection
113      * @throws SQLException When obtaining connection fails
114      */

115     public Connection JavaDoc getConnection(String JavaDoc overridingDataSourceUserId,
116                                     String JavaDoc overridingDataSourcePassword)
117             throws SQLException JavaDoc {
118
119         if (log.isTraceEnabled()) {
120             log.trace("Obtaining JDBC Connection. "
121             + "(Overriding DataSource UserId and Password)");
122         }
123
124         Connection JavaDoc conn =
125             dataSource.getConnection(overridingDataSourceUserId,
126                 overridingDataSourcePassword);
127         return conn;
128     }
129
130     /**
131      * Delegates to {@link DataSource#getLogWriter}.
132      * @see DataSource#getLogWriter
133      */

134     public PrintWriter JavaDoc getLogWriter() throws SQLException JavaDoc {
135         return dataSource.getLogWriter();
136     }
137
138     /**
139      * Delegates to {@link DataSource#getLoginTimeout}.
140      * @see DataSource#getLoginTimeout
141      */

142     public int getLoginTimeout() throws SQLException JavaDoc {
143         return dataSource.getLoginTimeout();
144     }
145
146     /**
147      * Delegates to {@link DataSource#setLogWriter}.
148      * @see DataSource#setLogWriter
149      */

150     public void setLogWriter(PrintWriter JavaDoc printWriter) throws SQLException JavaDoc {
151         dataSource.setLogWriter(printWriter);
152     }
153
154     /**
155      * Delegates to {@link DataSource#setLoginTimeout}.
156      * @see DataSource#setLoginTimeout
157      */

158     public void setLoginTimeout(int param) throws SQLException JavaDoc {
159         dataSource.setLoginTimeout(param);
160     }
161
162     /**
163      * Obtains the DataSource and necessary connection properties.
164      * Note that the DataSource is replaced each time the component
165      * is configured.
166      *
167      * @param configuration An instance of
168      * NamedDataSourceConnectionFactoryConfiguration
169      */

170     public void configure(ComponentConfiguration configuration) {
171         NamedDataSourceConnectionFactoryConfiguration config =
172             (NamedDataSourceConnectionFactoryConfiguration) configuration;
173
174         //JNDI location of the DataSource
175
String JavaDoc jndiName = config.getJndiName();
176         //Class of the InitialContextFactory
177
String JavaDoc initialContextFactory = config.getInitialContextFactory();
178         //(optional) URL of the JNDI provider
179
String JavaDoc providerUrl = config.getProviderUrl();
180         //(optional) userid used to authenticate to the JNDI server
181
String JavaDoc jndiUserId = config.getJndiUserId();
182         //(optional) password used to authenticate to the JNDI server
183
String JavaDoc jndiPassword = config.getJndiPassword();
184         //(optional) DataSource userid
185
this.dataSourceUserId = config.getDataSourceUserId();
186         //(optional) DataSource password
187
this.dataSourcePassword = config.getDataSourcePassword();
188
189         try {
190             //Obtain an InitialContext to connect to JNDI
191
if (log.isTraceEnabled()) {
192                 log.trace("Fetching Initial Context");
193             }
194             Context JavaDoc ic = fetchInitialContext(initialContextFactory,
195                                              providerUrl,
196                                              jndiUserId,
197                                              jndiPassword);
198
199             //Obtain the DataSource from JNDI
200
if (log.isTraceEnabled()) {
201                 log.trace("Obtaining DataSource from:"
202                     + "["
203                     + jndiName
204                     + "]");
205             }
206
207             this.dataSource = (DataSource JavaDoc) ic.lookup(jndiName);
208
209         } catch (NamingException JavaDoc ne) {
210             throw new StateTransitionException(this.getClass(),
211                 "Error Obtaining DataSource: ["
212                     + jndiName
213                     + "]"
214                     + "from JNDI service: ["
215                     + providerUrl
216                     + "]",
217                   ne);
218         }
219     }
220
221     /**
222      * <p>Helper method that creates the InitialContext onto the JNDI tree based
223      * upon the configured properties.</p>
224      *
225      * @param initialContextFactory String representation of the class name to
226      * be used as the <code>InitialContextFactory</code>; this
227      * parameter is analagous to
228      * <code>Context.INITIAL_CONTEXT_FACTORY</code>
229      * @param providerUrl The JNDI provider URL as a Stringl this parameter is
230      * analagous to <code>Context.PROVIDER_URL</code>
231      * @param jndiUserId The security principal as a String; this parameter is
232      * analagous to <code>Context.SECURITY_PRINCIPAL</code>
233      * @param jndiPassword The credentials associated with the security
234      * principal as a String; this parameter is analagous to the
235      * <code>Context.SECURITY_CREDENTIALS</code>
236      * @return a new Context based on the given environment.
237      *
238      * @throws NamingException indicates an error building the Context based
239      * on the given environment. */

240     protected Context JavaDoc fetchInitialContext(String JavaDoc initialContextFactory,
241                                           String JavaDoc providerUrl,
242                                           String JavaDoc jndiUserId,
243                                           String JavaDoc jndiPassword)
244     throws NamingException JavaDoc {
245         // Local variables to hold the Context and parameters for creating it
246
Context JavaDoc context = null;
247         Hashtable JavaDoc environment = new Hashtable JavaDoc();
248
249         // Go through our four possible parameters for creating the
250
// InitialContext and add all the non-null ones to the environment
251
// Hashtable.
252
if (null != initialContextFactory) {
253             environment.put(Context.INITIAL_CONTEXT_FACTORY,
254                            initialContextFactory);
255         }
256         if (null != providerUrl) {
257             environment.put(Context.PROVIDER_URL, providerUrl);
258         }
259         if (null != jndiUserId) {
260             environment.put(Context.SECURITY_PRINCIPAL, jndiUserId);
261         }
262         if (null != jndiPassword) {
263             environment.put(Context.SECURITY_CREDENTIALS, jndiPassword);
264     }
265         // If there were any parameters then we call the factory method with the
266
// parameters, otherwise just call the no-arg factory method.
267
if (environment.size() > 0) {
268             //TODO:
269
//Logger.detail(Logger.PRODUCER_CONNECTION,
270
// "NamedDataSourceManager.getInitialContext() fetching "
271
// + "initial context with environment parameters: "
272
// + parameters.toString());
273
context = new InitialContext JavaDoc(environment);
274         } else {
275             //TODO:
276
//Logger.detail(Logger.PRODUCER_CONNECTION,
277
// "NamedDataSourceManager.getInitialContext() fetching "
278
// + initial context with no environment parameters.");
279
context = new InitialContext JavaDoc();
280         }
281
282         // Return the context that we made
283
return context;
284     }
285 }
286
Popular Tags