KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmanage > core > auth > UserManager


1 /**
2  * Copyright 2004-2005 jManage.org
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.jmanage.core.auth;
17
18 import org.jdom.Document;
19 import org.jdom.JDOMException;
20 import org.jdom.Element;
21 import org.jdom.output.XMLOutputter;
22 import org.jdom.input.SAXBuilder;
23 import org.jmanage.core.crypto.Crypto;
24 import org.jmanage.core.util.Loggers;
25
26 import java.io.File JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.util.*;
29 import java.util.logging.Logger JavaDoc;
30
31 /**
32  *
33  * Date : Jun 27, 2004 10:43:03 PM
34  * @author Shashank
35  */

36 public class UserManager implements AuthConstants{
37
38     private static final Logger JavaDoc logger = Loggers.getLogger(UserManager.class);
39
40     /* create instance of UserManager */
41     private static UserManager userManager =
42             new UserManager(new File JavaDoc(USER_CONFIG_FILE_NAME));
43
44     /* user map */
45     private Map users = null;
46
47     /**
48      * Cache user information.
49      *
50      * @param userConfigFile
51      */

52     private UserManager(File JavaDoc userConfigFile){
53         try{
54             Document userConfig = new SAXBuilder().build(userConfigFile);
55             users = loadUsers(userConfig);
56         }catch(JDOMException jdEx){
57             logger.info("Error reading user info "+USER_CONFIG_FILE_NAME);
58             jdEx.printStackTrace();
59         }
60     }
61
62
63     /**
64      * Get the only instance of UserManager
65      *
66      * @return
67      */

68     public static UserManager getInstance(){
69         return userManager;
70     }
71
72     /**
73      * Load all users from the configuration file.
74      *
75      * @param userConfig
76      * @return
77      */

78     private Map loadUsers(Document userConfig){
79         Map userData = Collections.synchronizedMap(new HashMap(1));
80         List users =
81                 userConfig.getRootElement().getChildren();
82         Iterator userIterator = users.iterator();
83
84         while(userIterator.hasNext()){
85             Element user = (Element)userIterator.next();
86             List roles = user.getChildren(ROLE);
87             Iterator roleIterator = roles.iterator();
88             List userRoles = new ArrayList();
89             while(roleIterator.hasNext()){
90                 Element role = (Element)roleIterator.next();
91                 userRoles.add(new Role(role.getTextTrim()));
92             }
93             /* no need to hash password, as it is stored in hash form in
94                 the database */

95             userData.put(user.getAttributeValue(NAME),
96                     new User(user.getAttributeValue(NAME),
97                             user.getAttributeValue(PASSWORD),
98                             userRoles, user.getAttributeValue(STATUS),
99                             Integer.parseInt(user.getAttributeValue(LOCK_COUNT))));
100         }
101         return userData;
102     }
103
104     /**
105      * Return instance of User with specified username and passowrd if exists.
106      *
107      * @param username
108      * @param password
109      * @return
110      */

111     public User verifyUsernamePassword(String JavaDoc username, char[] password){
112         User user = (User)users.get(username);
113         if(user != null){
114             final String JavaDoc hashedPassword = Crypto.hash(password);
115             user = hashedPassword.equals(user.getPassword()) &&
116                     User.STATUS_ACTIVE.equals(user.getStatus()) ? user : null;
117         }
118         return user;
119     }
120
121     /**
122      * Overloaded for use in User management functionality.
123      *
124      * @param username
125      * @return
126      */

127     public User getUser(String JavaDoc username){
128         return users.containsKey(username) ? (User)users.get(username) : null;
129     }
130
131     /**
132      * Retrieve all configured users of the application.
133      *
134      * @return
135      */

136     public Map getAllUsers(){
137         return users;
138     }
139
140     /**
141      * Add a new user to the list.
142      *
143      * @param user
144      */

145     public void addUser(User user){
146         users.put(user.getName(), user);
147         saveUser();
148     }
149
150     /**
151      * Update the selected user information.
152      *
153      * @param user
154      */

155     public void updateUser(User user){
156         users.remove(user.getName());
157         users.put(user.getName(), user);
158         saveUser();
159     }
160
161     /**
162      * Remove the selected user from the list.
163      *
164      * @param username
165      */

166     public void deleteUser(String JavaDoc username){
167         if(users.containsKey(username)){
168             users.remove(username);
169             saveUser();
170         }
171     }
172
173     /**
174      * Update current user's password.
175      *
176      * @param password
177      */

178     public void updatePassword(String JavaDoc username, String JavaDoc password){
179         User user=(User)users.get(username);
180         user.setPassword(Crypto.hash(password));
181         saveUser();
182     }
183
184     /**
185      * Save the changes to "jmanage-users.xml"
186      */

187     private void saveUser(){
188         try {
189             Document doc = new Document();
190             Element rootElement = new Element(AuthConstants.JM_USERS);
191             for(Iterator it=users.values().iterator(); it.hasNext();){
192                 User user = (User)it.next();
193                 /* create a user element */
194                 Element userElement = new Element(AuthConstants.USER);
195                 userElement.setAttribute(AuthConstants.NAME, user.getUsername());
196                 userElement.setAttribute(AuthConstants.PASSWORD, user.getPassword());
197                 assert user.getStatus() != null &&
198                         (user.getStatus().equals(User.STATUS_ACTIVE) || user.getStatus().equals(User.STATUS_LOCKED));
199                 userElement.setAttribute(AuthConstants.STATUS,
200                         user.getStatus() != null ? user.getStatus() : User.STATUS_ACTIVE);
201                 userElement.setAttribute(AuthConstants.LOCK_COUNT,
202                         String.valueOf(user.getStatus() != null ? user.getLockCount() : 0));
203                 /* add roles */
204                 for(Iterator iterator = user.getRoles().iterator(); iterator.hasNext();){
205                     Role role = (Role)iterator.next();
206                     Element roleElement = new Element(AuthConstants.ROLE);
207                     roleElement.setText(role.getName());
208                     userElement.addContent(roleElement);
209                 }
210                 rootElement.addContent(userElement);
211             }
212             doc.setRootElement(rootElement);
213             /* write to the disc */
214             XMLOutputter writer = new XMLOutputter();
215             writer.output(doc, new FileOutputStream JavaDoc(AuthConstants.USER_CONFIG_FILE_NAME));
216         } catch (Exception JavaDoc e) {
217             throw new RuntimeException JavaDoc(e);
218         }
219     }
220 }
Popular Tags