KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exolab > jms > authentication > UserManager


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "Exolab" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of Exoffice Technologies. For written permission,
18  * please contact info@exolab.org.
19  *
20  * 4. Products derived from this Software may not be called "Exolab"
21  * nor may "Exolab" appear in their names without prior written
22  * permission of Exoffice Technologies. Exolab is a registered
23  * trademark of Exoffice Technologies.
24  *
25  * 5. Due credit should be given to the Exolab Project
26  * (http://www.exolab.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2003-2004 (C) Exoffice Technologies Inc. All Rights Reserved.
42  *
43  * $Id: UserManager.java,v 1.1 2004/11/26 01:50:39 tanderson Exp $
44  */

45 package org.exolab.jms.authentication;
46
47 import java.sql.Connection JavaDoc;
48 import java.util.Enumeration JavaDoc;
49 import java.util.HashMap JavaDoc;
50 import java.util.Iterator JavaDoc;
51
52 import javax.transaction.TransactionManager JavaDoc;
53
54 import org.apache.commons.logging.Log;
55 import org.apache.commons.logging.LogFactory;
56
57 import org.exolab.jms.service.ServiceException;
58 import org.exolab.jms.config.Configuration;
59 import org.exolab.jms.config.ConfigurationManager;
60 import org.exolab.jms.config.SecurityConfiguration;
61 import org.exolab.jms.persistence.DatabaseService;
62 import org.exolab.jms.persistence.PersistenceAdapter;
63 import org.exolab.jms.persistence.SQLHelper;
64
65
66 /**
67  * The user manager is responsible for creating and managing users.
68  *
69  * @version $Revision: 1.1 $ $Date: 2004/11/26 01:50:39 $
70  * @author <a HREF="mailto:knut@lerpold.no">Knut Lerpold</a>
71  */

72 public class UserManager {
73
74     /**
75      * A list of all users are maintained
76      * in this data structure.
77      */

78     private HashMap JavaDoc _userCache = new HashMap JavaDoc();
79
80     /**
81      * The logger
82      */

83     private static final Log _log = LogFactory.getLog(UserManager.class);
84
85
86     /**
87      * Construct a new <code>UserManager</code>
88      *
89      * @throws ServiceException if the service cannot be initialised
90      */

91     protected UserManager() throws ServiceException {
92         init();
93     }
94
95     /**
96      * Create a new user
97      *
98      * @param user the userobject containing username and password
99      * @return <code>true</code> if the user is created
100      * otherwise <code>false</code>
101      */

102     public synchronized boolean createUser(User user) {
103         boolean success = false;
104         PersistenceAdapter adapter = DatabaseService.getAdapter();
105
106         if (_userCache.get(user.getUsername()) == null) {
107             Connection JavaDoc connection = null;
108             try {
109                 connection = DatabaseService.getConnection();
110                 adapter.addUser(connection, user);
111                 addToUserCache(user);
112                 connection.commit();
113                 success = true;
114             } catch (Exception JavaDoc exception) {
115                 _log.error("Failed to create user", exception);
116                 SQLHelper.rollback(connection);
117             } finally {
118                 SQLHelper.close(connection);
119             }
120         }
121
122         return success;
123     }
124
125     /**
126      * Update user.
127      * Only possible update is password.
128      *
129      * @param user the userobject containing the username
130      * @return <code>true</code> if password is updated
131      * otherwise <code>false</code>
132      */

133     public synchronized boolean updateUser(User user) {
134         boolean success = false;
135         PersistenceAdapter adapter = DatabaseService.getAdapter();
136
137         if (_userCache.get(user.getUsername()) != null) {
138             Connection JavaDoc connection = null;
139             try {
140                 connection = DatabaseService.getConnection();
141                 adapter.updateUser(connection, user);
142                 connection.commit();
143                 addToUserCache(user);
144                 success = true;
145             } catch (Exception JavaDoc exception) {
146                 _log.error("Failed to update user", exception);
147                 SQLHelper.rollback(connection);
148             } finally {
149                 SQLHelper.close(connection);
150             }
151         }
152
153         return success;
154     }
155
156     /**
157      * Delete a users
158      *
159      * @param user the userobject containing the username
160      * @return <code>true</code> if the is removed
161      * otherwise <code>false</code>
162      */

163     public synchronized boolean deleteUser(User user) {
164         boolean success = false;
165         PersistenceAdapter adapter = DatabaseService.getAdapter();
166
167         if (_userCache.get(user.getUsername()) != null) {
168             Connection JavaDoc connection = null;
169             try {
170                 connection = DatabaseService.getConnection();
171                 adapter.removeUser(connection, user);
172                 removeFromUserCache(user);
173                 success = true;
174                 connection.commit();
175             } catch (Exception JavaDoc exception) {
176                 _log.error("Failed to remove user", exception);
177                 SQLHelper.rollback(connection);
178             } finally {
179                 SQLHelper.close(connection);
180             }
181         }
182         return success;
183     }
184
185     /**
186      * Return a user
187      *
188      * @param user the userobject containing the username
189      * @return a User
190      */

191     public synchronized User getUser(User user) {
192         return (User) _userCache.get(user.getUsername());
193     }
194
195     /**
196      * Return a list of user names currently supported by the user
197      * manager. This includes all types of users.
198      *
199      * @return an enumeration of the user names
200      */

201     public Iterator JavaDoc userNames() {
202         return _userCache.keySet().iterator();
203     }
204
205     /**
206      * Destroy this manager. This is brutal and final
207      */

208     public synchronized void destroy() {
209         _userCache.clear();
210         _userCache = null;
211     }
212
213     /**
214      * Determines if a user's name and password are valid
215      *
216      * @param username the user's name
217      * @param password the user's password
218      * @return <code>true</code> if the name and password are valid,
219      * otherwise <code>false</code>
220      */

221     public synchronized boolean validateUser(String JavaDoc username,
222                                              String JavaDoc password) {
223         boolean result = false;
224
225         SecurityConfiguration config =
226             ConfigurationManager.getConfig().getSecurityConfiguration();
227         if (!config.getSecurityEnabled()) {
228             // security disabled
229
result = true;
230         }
231
232         User user = (User) _userCache.get(username);
233         if (user != null && user.getPassword().equals(password)) {
234             result = true;
235         }
236
237         return result;
238     }
239
240     /**
241      * Initialise user manager.
242      *
243      * @throws ServiceException if the user manager cannot be initialised
244      */

245     protected void init() throws ServiceException {
246         Connection JavaDoc connection = null;
247         TransactionManager JavaDoc tm = null;
248         try {
249             connection = DatabaseService.getConnection();
250
251             Enumeration JavaDoc iter =
252                 DatabaseService.getAdapter().getAllUsers(connection);
253             connection.commit();
254
255             while (iter.hasMoreElements()) {
256                 // add each user to the cache
257
User user = (User) iter.nextElement();
258                 addToUserCache(user);
259             }
260         } catch (Exception JavaDoc exception) {
261             SQLHelper.rollback(connection);
262             _log.error("Failed to initialise UserManager", exception);
263             throw new ServiceException(exception);
264         } finally {
265             SQLHelper.close(connection);
266         }
267
268         registerConfiguredUsers();
269     }
270
271     /**
272      * Add the specified entry to the user cache, if it doesn't
273      * already exist.
274      *
275      * @param user - user to add
276      */

277     protected void addToUserCache(User user) {
278         if (!_userCache.containsKey(user.getUsername())) {
279             _userCache.put(user.getUsername(), user);
280         }
281     }
282
283     /**
284      * Remove the specified user from the cache
285      *
286      * @param user the user to remove
287      */

288     protected void removeFromUserCache(User user) {
289         _userCache.remove(user.getUsername());
290     }
291
292     /**
293      * Registers users specified in the configuration
294      */

295     protected void registerConfiguredUsers() {
296         Configuration config = ConfigurationManager.getConfig();
297         if (config.getUsers() != null) {
298             org.exolab.jms.config.User[] users = config.getUsers().getUser();
299             for (int i = 0; i < users.length; ++i) {
300                 User user = new User(users[i].getName(),
301                     users[i].getPassword());
302                 createUser(user);
303             }
304         }
305     }
306
307 }
308
Popular Tags