KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > jdbc > JDBCUserDatabase


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.jdbc;
21
22 import java.io.File JavaDoc;
23 import java.sql.ResultSet JavaDoc;
24 import java.sql.SQLException JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Vector JavaDoc;
29 import java.util.regex.Matcher JavaDoc;
30 import java.util.regex.Pattern JavaDoc;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34
35 import com.sslexplorer.boot.ContextHolder;
36 import com.sslexplorer.core.CoreServlet;
37 import com.sslexplorer.core.CoreUtil;
38 import com.sslexplorer.core.UserDatabaseManager;
39 import com.sslexplorer.policyframework.Principal;
40 import com.sslexplorer.realms.Realm;
41 import com.sslexplorer.security.AccountLockedException;
42 import com.sslexplorer.security.DefaultUser;
43 import com.sslexplorer.security.DefaultUserDatabase;
44 import com.sslexplorer.security.InvalidLoginCredentialsException;
45 import com.sslexplorer.security.Role;
46 import com.sslexplorer.security.User;
47 import com.sslexplorer.security.UserDatabaseException;
48 import com.sslexplorer.security.UserNotFoundException;
49
50 /**
51  * @author lee
52  *
53  * To change the template for this generated type comment go to Window -
54  * Preferences - Java - Code Generation - Code and Comments
55  */

56 public class JDBCUserDatabase extends DefaultUserDatabase {
57
58     static Log log = LogFactory.getLog(JDBCUserDatabase.class);
59
60     // JDBCConnection con;
61
JDBCDatabaseEngine db;
62
63     HashMap JavaDoc permissionModules = new HashMap JavaDoc();
64
65     /**
66      * Constant for the database type.
67      */

68     public static final String JavaDoc DATABASE_TYPE = "builtIn";
69
70     /**
71      * Constructor
72      */

73     public JDBCUserDatabase() {
74         super("JDBC", true, true);
75     }
76
77     /*
78      * (non-Javadoc)
79      *
80      * @see com.sslexplorer.core.Database#open(com.sslexplorer.core.CoreServlet)
81      */

82     public void open(CoreServlet controllingServlet, Realm realm) throws Exception JavaDoc {
83         super.open(controllingServlet, realm);
84         String JavaDoc dbName = System.getProperty("sslexplorer.userDatabase.jdbc.dbName", "explorer_configuration");
85         controllingServlet.addDatabase(dbName, ContextHolder.getContext().getDBDirectory());
86         File JavaDoc upgradeDir = new File JavaDoc("install/upgrade");
87         String JavaDoc jdbcUser = System.getProperty("sslexplorer.jdbc.username", "sa");
88         String JavaDoc jdbcPassword = System.getProperty("sslexplorer.jdbc.password", "");
89         String JavaDoc vendorDB = System.getProperty("sslexplorer.jdbc.vendorClass", "com.sslexplorer.jdbc.hsqldb.HSQLDBDatabaseEngine");
90         if (log.isInfoEnabled()) {
91             log.info("User database is being opened...");
92             log.info("JDBC vendor class implementation is " + vendorDB);
93         }
94         db = (JDBCDatabaseEngine) Class.forName(vendorDB).newInstance();
95         db.init("userDatabase", dbName, jdbcUser, jdbcPassword, null);
96         DBUpgrader upgrader = new DBUpgrader(ContextHolder.getContext().getVersion(), db, ContextHolder.getContext()
97                         .getDBDirectory(), upgradeDir);
98         upgrader.upgrade();
99         open = true;
100     }
101
102     /* (non-Javadoc)
103      * @see com.sslexplorer.security.UserDatabase#logon(java.lang.String, java.lang.String)
104      */

105     public User logon(String JavaDoc username, String JavaDoc password)
106             throws UserDatabaseException, InvalidLoginCredentialsException,
107             AccountLockedException {
108         JDBCPreparedStatement ps = null;
109         try {
110             ps = db.getStatement("logon.user");
111             ps.setString(1, username);
112             ps.setString(2, password);
113             ps.setInt(3, realm.getResourceId());
114             ResultSet JavaDoc results = ps.executeQuery();
115             try {
116                 while (results.next()) {
117                     try {
118                         DefaultUser user = new DefaultUser(results.getString("username"), results.getString("email"), results
119                                         .getString("fullname"), results.getDate("last_password_change"),
120                                         UserDatabaseManager.getInstance().getRealm(results.getInt("realm_ID")));
121                         addRoles(user);
122                         return user;
123                     } catch (Exception JavaDoc e) {
124                         throw new UserDatabaseException("Failed to get user realm.");
125                     }
126                 }
127             } finally {
128                 results.close();
129             }
130         } catch (UserDatabaseException ude) {
131             throw ude;
132         } catch (SQLException JavaDoc ex) {
133             throw new UserDatabaseException("Failed to execute SQL query", ex);
134         } catch (ClassNotFoundException JavaDoc ex) {
135             throw new UserDatabaseException("Failed to execute SQL query", ex);
136         } finally {
137             try {
138                 if (ps != null) {
139                     ps.releasePreparedStatement();
140                 }
141             } catch (SQLException JavaDoc e) {
142             }
143         }
144         throw new InvalidLoginCredentialsException();
145     }
146
147     /*
148      * (non-Javadoc)
149      *
150      * @see com.sshtools.enterprise.admin.UserDatabase#logout(com.sshtools.enterprise.admin.User)
151      */

152     public void logout(User user) {
153         // Nothing needed to logout of the db.
154
}
155
156     public User[] listAllUsers(String JavaDoc filter) throws Exception JavaDoc {
157         // Get the allowed roles from the database
158
JDBCPreparedStatement ps = db.getStatement("select.users");
159         String JavaDoc wildCard = "^" + CoreUtil.replaceAllTokens(filter, "*", ".*")
160                 + "$";
161         Pattern JavaDoc p = Pattern.compile(wildCard, Pattern.CASE_INSENSITIVE);
162         try {
163             ResultSet JavaDoc results = ps.executeQuery();
164             try {
165                 Vector JavaDoc<User> tmp = new Vector JavaDoc<User>();
166                 while (results.next()) {
167                     String JavaDoc username = results.getString("username");
168                     Matcher JavaDoc matcher = p.matcher(username);
169                     Realm usersRealm = UserDatabaseManager.getInstance().getRealm(results.getInt("realm_ID"));
170                     if (matcher.matches() && usersRealm.equals(realm)) {
171                         DefaultUser u = new DefaultUser(results
172                                 .getString("username"), results
173                                 .getString("email"), results
174                                 .getString("fullname"), results
175                                 .getDate("last_password_change"), usersRealm);
176                         addRoles(u);
177                         tmp.add(u);
178                     }
179                 }
180                 DefaultUser[] users = new DefaultUser[tmp.size()];
181                 tmp.copyInto(users);
182                 return users;
183             } finally {
184                 results.close();
185             }
186         } finally {
187             ps.releasePreparedStatement();
188         }
189     }
190
191     /* (non-Javadoc)
192      * @see com.sslexplorer.security.UserDatabase#getAccount(java.lang.String)
193      */

194     public User getAccount(String JavaDoc username) throws UserNotFoundException, Exception JavaDoc {
195         // Get the allowed roles from the database
196
JDBCPreparedStatement ps = db.getStatement("select.user");
197         try {
198             ps.setString(1, username);
199             ResultSet JavaDoc results = ps.executeQuery();
200             try {
201                 while (results.next()) {
202                     Realm usersRealm = UserDatabaseManager.getInstance().getRealm(results.getInt("realm_ID"));
203                     if (usersRealm.equals(realm)){
204                         DefaultUser u = new DefaultUser(results
205                                 .getString("username"), results.getString("email"),
206                                 results.getString("fullname"), results
207                                     .getDate("last_password_change"), usersRealm);
208                         addRoles(u);
209                         return u;
210                     }
211                 }
212                 throw new UserNotFoundException("No user exists with username " + username + " in realm " + realm.getResourceDisplayName());
213             } finally {
214                 results.close();
215             }
216         } finally {
217             ps.releasePreparedStatement();
218         }
219     }
220
221     /* (non-Javadoc)
222      * @see com.sslexplorer.security.DefaultUserDatabase#createAccount(java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.sslexplorer.security.Role[])
223      */

224     public User createAccount(String JavaDoc username, String JavaDoc password, String JavaDoc email,
225             String JavaDoc fullname, Role[] roles)
226             throws Exception JavaDoc {
227         JDBCPreparedStatement ps = db.getStatement("create.account");
228         try {
229             ps.setString(1, username);
230             ps.setString(2, email);
231             ps.setString(3, password);
232             ps.setString(4, fullname);
233             ps.setInt(5, realm.getResourceId());
234             ps.execute();
235             for (int i = 0; roles != null && i < roles.length; i++) {
236                 JDBCPreparedStatement ps2 = db.getStatement("assign.role");
237                 try {
238                     ps2.setString(1, username);
239                     ps2.setString(2, roles[i].getPrincipalName());
240                     ps2.setInt(3, realm.getResourceId());
241                     ps2.execute();
242                 } finally {
243                     ps2.releasePreparedStatement();
244                 }
245             }
246         } finally {
247             ps.releasePreparedStatement();
248         }
249         return getAccount(username);
250     }
251
252     /* (non-Javadoc)
253      * @see com.sslexplorer.security.DefaultUserDatabase#getUsersInRole(com.sslexplorer.security.Role)
254      */

255     public User[] getUsersInRole(Role role) throws Exception JavaDoc {
256         return CoreUtil.getUsersInRole(role, this);
257     }
258
259     /*
260      * (non-Javadoc)
261      *
262      * @see com.sshtools.enterprise.admin.UserDatabase#updateAccount(com.sshtools.enterprise.admin.User,
263      * java.lang.String, java.lang.String, java.lang.String)
264      */

265     public void updateAccount(User user, String JavaDoc email, String JavaDoc fullname,
266             Role[] roles) throws Exception JavaDoc {
267         JDBCPreparedStatement ps = db.getStatement("update.account");
268         try {
269             ps.setString(1, email);
270             ps.setString(2, fullname);
271             ps.setString(3, user.getPrincipalName());
272             ps.execute();
273         } finally {
274             ps.releasePreparedStatement();
275         }
276         ps = db.getStatement("delete.roles");
277         try {
278             ps.setString(1, user.getPrincipalName());
279             ps.setInt(2, user.getRealm().getResourceId());
280             ps.execute();
281         } finally {
282             ps.releasePreparedStatement();
283         }
284         ps = db.getStatement("assign.role");
285         try {
286             for (int i = 0; roles != null && i < roles.length; i++) {
287                 ps.setString(1, user.getPrincipalName());
288                 ps.setString(2, roles[i].getPrincipalName());
289                 ps.setInt(3, user.getRealm().getResourceId());
290                 ps.execute();
291                 ps.reset();
292             }
293         } finally {
294             ps.releasePreparedStatement();
295         }
296     }
297
298     /* (non-Javadoc)
299      * @see com.sslexplorer.security.DefaultUserDatabase#deleteAccount(com.sslexplorer.security.User)
300      */

301     public void deleteAccount(User user) throws Exception JavaDoc, UserNotFoundException {
302         this.getAccount(user.getPrincipalName());
303         JDBCPreparedStatement ps = db.getStatement("delete.account");
304         try {
305             ps.setString(1, user.getPrincipalName());
306             ps.setInt(2, user.getRealm().getResourceId());
307             ps.execute();
308         } finally {
309             ps.releasePreparedStatement();
310         }
311         ps = db.getStatement("delete.account.roles");
312         try {
313             ps.setString(1, user.getPrincipalName());
314             ps.setInt(2, user.getRealm().getResourceId());
315             ps.execute();
316         } finally {
317             ps.releasePreparedStatement();
318         }
319     }
320
321     /* (non-Javadoc)
322      * @see com.sslexplorer.security.UserDatabase#checkPassword(java.lang.String, java.lang.String)
323      */

324     public boolean checkPassword(String JavaDoc username, String JavaDoc password)
325             throws UserDatabaseException, InvalidLoginCredentialsException {
326         try {
327             JDBCPreparedStatement ps = db.getStatement("logon.user");
328             try {
329                 ps.setString(1, username);
330                 ps.setString(2, password);
331                 ps.setInt(3, realm.getResourceId());
332                 ResultSet JavaDoc results = ps.executeQuery();
333                 try {
334                     return results.next();
335                 } finally {
336                     results.close();
337                 }
338             } finally {
339                 ps.releasePreparedStatement();
340             }
341         } catch (Exception JavaDoc ex) {
342             throw new UserDatabaseException("Failed to execute SQL query", ex);
343         }
344     }
345
346     /* (non-Javadoc)
347      * @see com.sslexplorer.security.DefaultUserDatabase#changePassword(java.lang.String, java.lang.String, java.lang.String, boolean)
348      */

349     public void changePassword(String JavaDoc username, String JavaDoc oldPassword,
350             String JavaDoc password, boolean forcePasswordChangeAtLogon)
351             throws UserDatabaseException, InvalidLoginCredentialsException {
352         JDBCPreparedStatement ps = null;
353         try {
354             if (forcePasswordChangeAtLogon) {
355                 ps = db.getStatement("change.password.force");
356                 ps.setString(1, password);
357                 ps.setString(2, username);
358                 ps.setInt(3, realm.getResourceId());
359             } else {
360                 ps = db.getStatement("change.password");
361                 ps.setString(1, password);
362                 ps.setString(2, username);
363                 ps.setInt(3, realm.getResourceId());
364             }
365             ps.execute();
366         } catch (Exception JavaDoc e) {
367             throw new UserDatabaseException(
368                     "Failed to change password for user " + username + " in realm " + realm + ".");
369         } finally {
370             if (ps != null) {
371                 try {
372                     ps.releasePreparedStatement();
373                 } catch (SQLException JavaDoc e) {
374                 }
375             }
376         }
377     }
378
379     /* (non-Javadoc)
380      * @see com.sslexplorer.security.DefaultUserDatabase#setPassword(java.lang.String, java.lang.String, boolean, com.sslexplorer.security.User, java.lang.String)
381      */

382     public void setPassword(String JavaDoc username, String JavaDoc password,
383             boolean forcePasswordChangeAtLogon, User adminUser,
384             String JavaDoc adminPassword) throws UserDatabaseException,
385             InvalidLoginCredentialsException {
386         changePassword(username, "", password, forcePasswordChangeAtLogon);
387     }
388
389     /* (non-Javadoc)
390      * @see com.sslexplorer.security.UserDatabase#listAvailablePrincipals()
391      */

392     public Principal[] listAvailablePrincipals() throws Exception JavaDoc {
393         return listAllUsers(null);
394     }
395
396     /* (non-Javadoc)
397      * @see com.sslexplorer.security.UserDatabase#getRole(java.lang.String)
398      */

399     public Role getRole(String JavaDoc rolename) throws Exception JavaDoc {
400         JDBCPreparedStatement ps = db.getStatement("select.role");
401         try {
402             ps.setString(1, rolename);
403             ps.setInt(2, realm.getResourceId());
404             ResultSet JavaDoc results = ps.executeQuery();
405             try {
406                 if (results.next()) {
407                     JDBCRole r = new JDBCRole(results.getString("rolename"), realm);
408                     return r;
409                 }
410             } finally {
411                 results.close();
412             }
413         } finally {
414             ps.releasePreparedStatement();
415         }
416         throw new Exception JavaDoc("No role exists with rolename " + rolename);
417     }
418
419     /* (non-Javadoc)
420      * @see com.sslexplorer.security.UserDatabase#listAllRoles(java.lang.String)
421      */

422     public Role[] listAllRoles(String JavaDoc filter) throws Exception JavaDoc {
423         String JavaDoc wildCard = "^" + CoreUtil.replaceAllTokens(filter, "*", ".*")
424                 + "$";
425         Pattern JavaDoc p = Pattern.compile(wildCard, Pattern.CASE_INSENSITIVE);
426         JDBCPreparedStatement ps = db.getStatement("select.roles");
427         try {
428             ResultSet JavaDoc results = ps.executeQuery();
429             try {
430                 Vector JavaDoc<Role> tmp = new Vector JavaDoc<Role>();
431                 while (results.next()) {
432                     String JavaDoc rolename = results.getString("rolename");
433                     Realm usersRealm = UserDatabaseManager.getInstance().getRealm(results.getInt("realm_ID"));
434                     Matcher JavaDoc matcher = p.matcher(rolename);
435                     if (matcher.matches() && usersRealm.equals(realm)) {
436                         JDBCRole r = new JDBCRole(rolename, realm);
437                         tmp.add(r);
438                     }
439                 }
440                 JDBCRole[] roles = new JDBCRole[tmp.size()];
441                 tmp.copyInto(roles);
442                 return roles;
443             } finally {
444                 results.close();
445             }
446         } finally {
447             ps.releasePreparedStatement();
448         }
449     }
450
451     /* (non-Javadoc)
452      * @see com.sslexplorer.security.DefaultUserDatabase#createRole(java.lang.String)
453      */

454     public Role createRole(String JavaDoc rolename) throws Exception JavaDoc {
455         JDBCPreparedStatement ps = db.getStatement("create.role");
456         try {
457             ps.setString(1, rolename);
458             ps.setInt(2, realm.getResourceId());
459             ps.execute();
460         } finally {
461             ps.releasePreparedStatement();
462         }
463         return getRole(rolename);
464     }
465
466     /* (non-Javadoc)
467      * @see com.sslexplorer.security.DefaultUserDatabase#deleteRole(java.lang.String)
468      */

469     public void deleteRole(String JavaDoc rolename) throws Exception JavaDoc {
470         JDBCPreparedStatement ps = db.getStatement("delete.role.1");
471         try {
472             ps.setString(1, rolename);
473             ps.setInt(2, realm.getResourceId());
474             ps.execute();
475         } finally {
476             ps.releasePreparedStatement();
477         }
478         ps = db.getStatement("delete.role.2");
479         try {
480             ps.setString(1, rolename);
481             ps.setInt(2, realm.getResourceId());
482             ps.execute();
483         } finally {
484             ps.releasePreparedStatement();
485         }
486     }
487
488     /**
489      * @param u
490      * @throws UserDatabaseException
491      */

492     private void addRoles(DefaultUser u) throws UserDatabaseException {
493         JDBCPreparedStatement ps = null;
494         try {
495             ps = db.getStatement("select.user.roles");
496             ps.setString(1, u.getPrincipalName());
497             ps.setInt(2, u.getRealm().getResourceId());
498             ResultSet JavaDoc r2 = ps.executeQuery();
499             List JavaDoc<Role> roles = new ArrayList JavaDoc<Role>();
500             try {
501                 while (r2.next()) {
502                     Role r = getRole(r2.getString("rolename"));
503                     roles.add(r);
504                 }
505             } finally {
506                 r2.close();
507             }
508             Role[] r = new Role[roles.size()];
509             roles.toArray(r);
510             u.setRoles(r);
511         } catch (Exception JavaDoc e) {
512             throw new UserDatabaseException("Failed to add roles to user.", e);
513         } finally {
514             if (ps != null) {
515                 try {
516                     ps.releasePreparedStatement();
517                 } catch (SQLException JavaDoc e) {
518                 }
519             }
520         }
521     }
522 }
523
Popular Tags