KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jguard > ext > database > ConnectionFactory


1 /*
2 jGuard is a security framework based on top of jaas (java authentication and authorization security).
3 it is written for web applications, to resolve simply, access control problems.
4 version $Name$
5 http://sourceforge.net/projects/jguard/
6
7 Copyright (C) 2004 Charles GAY
8
9 This library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
13
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
23
24 jGuard project home page:
25 http://sourceforge.net/projects/jguard/
26
27 */

28
29 package net.sf.jguard.ext.database;
30
31 import java.sql.Connection JavaDoc;
32 import java.sql.DriverManager JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.util.Arrays JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.Hashtable JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.Map JavaDoc;
39 import java.util.logging.Level JavaDoc;
40 import java.util.logging.Logger JavaDoc;
41
42 import javax.naming.InitialContext JavaDoc;
43 import javax.naming.NamingException JavaDoc;
44 import javax.sql.DataSource JavaDoc;
45
46 import net.sf.jguard.core.CoreConstants;
47 import net.sf.jguard.ext.SecurityConstants;
48
49
50 /**
51  * Factory for Database Connection.
52  * @author <a HREF="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
53  * @version $Revision: 202 $
54  */

55 public final class ConnectionFactory {
56     /** Logger for this class */
57     private static final Logger JavaDoc logger = Logger.getLogger(ConnectionFactory.class.getName());
58
59     private Class JavaDoc clazz = null;
60     private String JavaDoc url = null;
61     private String JavaDoc login = null;
62     private String JavaDoc password = null;
63
64     /**
65      * key string which contains applicationName, and, if this application is "secured" (in a jGuard notion),
66      * "|" and the applicationPassword
67      */

68     private String JavaDoc key = null;
69     /**
70      * jndi <strong>true</strong> if the connection is reachable with the jndi abstraction,
71      * <strong>false</strong> if we should reach connection through the DriverManager
72      */

73     private boolean JNDI = false;
74     //Map which contains Datasources ans connection informations
75
//(when the connection is reach through the driverManager)
76
private Map JavaDoc connMap = new HashMap JavaDoc();
77     private DataSource JavaDoc datasource = null;
78
79     /**
80      * initialise connection settings for the specified webapp in the map (with the <strong>applicationName</strong> parameter).
81      * @param opts
82      */

83     public ConnectionFactory(Map JavaDoc opts){
84
85         logger.finest(" ConnectionFactoryOptions="+opts);
86
87         String JavaDoc applicationName= (String JavaDoc)opts.get(CoreConstants.APPLICATION_NAME);
88         String JavaDoc applicationPassword = (String JavaDoc)opts.get(SecurityConstants.APPLICATION_PASSWORD);
89         if((String JavaDoc)opts.get(SecurityConstants.SECURED)!=null &&((String JavaDoc)opts.get(SecurityConstants.SECURED)).equals("true")){
90          key = new StringBuffer JavaDoc(applicationName).append("|").append(applicationPassword).toString();
91         }else{
92             key = new String JavaDoc(applicationName);
93         }
94
95         String JavaDoc jndiRef = (String JavaDoc)opts.get("JNDI");
96         if (jndiRef!= null){
97
98            try {
99               Hashtable JavaDoc env = new Hashtable JavaDoc(opts);
100               InitialContext JavaDoc initCtx = new InitialContext JavaDoc(env);
101               Object JavaDoc object = (DataSource JavaDoc) initCtx.lookup(jndiRef);
102                if (object instanceof DataSource JavaDoc) {
103                 datasource= (DataSource JavaDoc) object;
104                 }else{
105                     throw new IllegalArgumentException JavaDoc(" JNDI lookup "+jndiRef+" must return an object of type javax.sql.DataSource ");
106                 }
107               connMap.put(key,datasource);
108               JNDI= true;
109            } catch (NamingException JavaDoc e) {
110                 if (logger.isLoggable(Level.FINEST)) {
111                     logger.finest("init() - datasource cannot be retrieved through JNDI "
112                     + e.getMessage());
113                 }
114            }catch(Throwable JavaDoc t){
115                System.out.println(t.getMessage());
116            }
117
118         }else{
119
120             String JavaDoc driver = (String JavaDoc)opts.get(SecurityConstants.DATABASE_DRIVER);
121             String JavaDoc url = (String JavaDoc)opts.get(SecurityConstants.DATABASE_DRIVER_URL);
122             String JavaDoc login = (String JavaDoc)opts.get(SecurityConstants.DATABASE_DRIVER_LOGIN);
123             String JavaDoc password = (String JavaDoc)opts.get(SecurityConstants.DATABASE_DRIVER_PASSWORD);
124             String JavaDoc value = driver+"|"+url+"|"+login+"|"+password;
125             connMap.put(key,value);
126         }
127
128     }
129
130     /**
131      * Returns a database connection, encapsulating the DAO details.
132      *
133      * @return java.sql.Connection obtained either from a pool or explicitly
134      */

135     public final Connection JavaDoc getConnection() {
136         Connection JavaDoc conn = null;
137
138         //jndi stuff
139
if(JNDI){
140           conn = getConnectionWithJNDI();
141         //driver manager stuff
142
}else{
143             conn = getConnectionWithDriver();
144         }
145         return conn;
146
147
148     }
149
150
151     /**
152      * Returns a database connection.this method is used to authenticate user through
153      * the Jdbc Driver.
154      * @param user user database connection
155      * @param password password database connection
156      * @return java.sql.Connection obtained either from a pool or explicitly
157      */

158     public final Connection JavaDoc getConnection(String JavaDoc user,String JavaDoc password) {
159
160             Connection JavaDoc conn = null;
161             try {
162                 if(url == null){
163                     logger.severe(" jdbc driver url is not defined ");
164                 }
165                 if(this.clazz == null){
166                     logger.severe(" jdbc driver class is not defined ");
167                 }
168                 conn = DriverManager.getConnection(this.url,user,password);
169             } catch (SQLException JavaDoc e) {
170                 logger.severe(" connection canot be established url="+url+" user="+user+" password="+password);
171             }
172             return conn;
173
174
175     }
176
177     /**
178      * get a connection grabbed through a Datasource reached by JNDI.
179      * @see javax.sql.DataSource
180      * @return Connection
181      */

182     private Connection JavaDoc getConnectionWithJNDI() {
183         Connection JavaDoc conn = null;
184           try {
185               conn = datasource.getConnection();
186           } catch (SQLException JavaDoc e) {
187                 if (logger.isLoggable(Level.SEVERE)) {
188                     logger.severe("getConnection() - connection through JNDI cannot be established "
189                     + e.getMessage());
190                 }
191           }
192         return conn;
193     }
194
195     /**
196      * get a connection grabbed through a Driver interface.
197      * @see java.sql.Driver
198      * @return Connection
199      */

200     private Connection JavaDoc getConnectionWithDriver() {
201         Connection JavaDoc conn = null;
202         try {
203             if(clazz==null && url==null && login==null && password==null){
204                 String JavaDoc value = (String JavaDoc)connMap.get(key);
205                 List JavaDoc strings = Arrays.asList(value.split("\\|"));
206                 conn = getConnection(strings);
207             }else{
208                 conn = DriverManager.getConnection(url,login,password);
209             }
210         }catch (ClassNotFoundException JavaDoc e) {
211                 logger.severe("getConnection() - ClassNotFoundException" + e.getMessage());
212                 logger.severe("getConnection(String, boolean)" + e);
213         }catch (SQLException JavaDoc e) {
214                     logger.severe("getConnection() - SQLException "+ e.getMessage());
215                     logger.severe("getConnection() - SQLException state="+ e.getSQLState());
216                     logger.severe("getConnection() - SQLException error code="+ e.getErrorCode());
217                     logger.severe("getConnection() - SQLException error next exception="+ e.getNextException());
218                     logger.log(Level.SEVERE, "getConnection(String, boolean)", e);
219         }
220         return conn;
221     }
222
223     private Connection JavaDoc getConnection(List JavaDoc strings) throws ClassNotFoundException JavaDoc, SQLException JavaDoc {
224         Connection JavaDoc conn;
225         String JavaDoc driver = (String JavaDoc)strings.get(0);
226         url = (String JavaDoc)strings.get(1);
227         login = (String JavaDoc)strings.get(2);
228
229         switch(strings.size()){
230            case 4:
231                //'regular' use case
232
password = (String JavaDoc)strings.get(3);
233                break;
234            case 3:
235                //'goofy' use case ;-)
236
//if the list lacks one element, we implied the
237
//password is empty
238
password ="";
239                break;
240            default:
241                throw new IllegalArgumentException JavaDoc(" wrong number of parameters to establish JDBC connection "+strings);
242         }
243
244
245
246         if (logger.isLoggable(Level.FINEST)) {
247             logger.finest("getConnection() - driver=" + driver);
248             logger.finest("getConnection() - url=" + url);
249             logger.finest("getConnection() - login=" + login);
250             logger.finest("getConnection() - password=" + password);
251         }
252
253
254         Class.forName(driver);
255         conn = DriverManager.getConnection(url,login,password);
256         return conn;
257     }
258
259
260
261
262 }
263
Popular Tags