KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > security > realm > factory > JResourceMemory


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2004 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or 1any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * Initial developer: Florent BENOIT
22  * --------------------------------------------------------------------------
23  * $Id: JResourceMemory.java,v 1.6 2004/09/17 22:33:32 ehardesty Exp $
24  * --------------------------------------------------------------------------
25  */

26
27 package org.objectweb.jonas.security.realm.factory;
28
29 import java.security.NoSuchAlgorithmException JavaDoc;
30 import java.util.Enumeration JavaDoc;
31 import java.util.Hashtable JavaDoc;
32 import java.util.ArrayList JavaDoc;
33
34 import javax.naming.BinaryRefAddr JavaDoc;
35 import javax.naming.NamingException JavaDoc;
36 import javax.naming.Reference JavaDoc;
37 import javax.naming.StringRefAddr JavaDoc;
38
39 import org.objectweb.util.monolog.api.BasicLevel;
40 import org.objectweb.jonas.common.JNDIUtils;
41 import org.objectweb.jonas.jmx.JonasObjectName;
42 import org.objectweb.jonas.security.realm.lib.XML;
43 import org.objectweb.jonas.security.realm.principals.User;
44 import org.objectweb.jonas.security.realm.principals.Group;
45 import org.objectweb.jonas.security.realm.principals.Role;
46 import org.objectweb.jonas.security.realm.lib.HashHelper;
47
48 /**
49  * This class extends the JResource class for the Memory implementation.
50  * @author Florent Benoit
51  */

52 public class JResourceMemory extends JResource implements JResourceMemoryMBean {
53
54     /**
55      * Groups
56      */

57     private Hashtable JavaDoc groups = new Hashtable JavaDoc();
58
59     /**
60      * Roles
61      */

62     private Hashtable JavaDoc roles = new Hashtable JavaDoc();
63
64     /**
65      * Type of the factory
66      */

67     private static final String JavaDoc FACTORY_TYPE = "org.objectweb.jonas.security.realm.factory.JResourceMemory";
68
69     /**
70      * Name of the factory
71      */

72     private static final String JavaDoc FACTORY_NAME = "org.objectweb.jonas.security.realm.factory.JResourceMemoryFactory";
73
74     /**
75      * Constructor . Use the super constructor
76      * @throws Exception if super constructor fail
77      */

78     public JResourceMemory() throws Exception JavaDoc {
79         super();
80     }
81
82     /**
83      * Add a user to this resource.
84      * @param user the user which need to be added.
85      * @throws Exception if the user already exists
86      */

87     public void addUser(User user) throws Exception JavaDoc {
88
89         if (getUsers().get(user.getName()) != null) {
90             throw new Exception JavaDoc("User " + user.getName() + " already exists.");
91         }
92
93         // Add group if the group was not present
94
String JavaDoc[] userGroups = user.getArrayGroups();
95         String JavaDoc groupName = null;
96         for (int g = 0; g < userGroups.length; g++) {
97             groupName = userGroups[g];
98             if (!groups.containsKey(groupName)) {
99                 addGroup(new Group(groupName));
100             }
101         }
102
103         // Add role if the role was not present
104
String JavaDoc[] userRoles = user.getArrayRoles();
105         String JavaDoc roleName = null;
106         for (int g = 0; g < userRoles.length; g++) {
107             roleName = userRoles[g];
108             if (!roles.containsKey(roleName)) {
109                 addRole(new Role(roleName));
110             }
111         }
112
113         // Add user
114
getUsers().put(user.getName(), user);
115
116         //Add Mbean
117
String JavaDoc userName = user.getName();
118         try {
119             // register security service mbean
120
getMBeanServer().registerMBean(user, JonasObjectName.user(getName(), userName));
121         } catch (Exception JavaDoc e) {
122             getLogger().log(BasicLevel.ERROR, "Cannot register user '" + userName + "' in JMX server : " + e.getMessage());
123         }
124     }
125
126     /**
127      * Add a group to this resource.
128      * @param group the group which need to be added.
129      * @throws Exception if the group already exists
130      */

131     public void addGroup(Group group) throws Exception JavaDoc {
132
133         if (groups.get(group.getName()) != null) {
134             throw new Exception JavaDoc("Group " + group.getName() + " already exists.");
135         }
136
137         // Add role if the role was not present
138
String JavaDoc[] groupRoles = group.getArrayRoles();
139         String JavaDoc roleName = null;
140         for (int g = 0; g < groupRoles.length; g++) {
141             roleName = groupRoles[g];
142             if (!roles.containsKey(roleName)) {
143                 addRole(new Role(roleName));
144             }
145         }
146
147         // Add group
148
groups.put(group.getName(), group);
149
150         //Add Mbean
151
String JavaDoc groupName = group.getName();
152         try {
153             // register security service mbean
154
getMBeanServer().registerMBean(group, JonasObjectName.group(getName(), groupName));
155         } catch (Exception JavaDoc e) {
156             getLogger().log(BasicLevel.ERROR, "Cannot register group '" + groupName + "' in JMX server : " + e.getMessage());
157         }
158     }
159
160     /**
161      * Add a role to this resource.
162      * @param role the role which need to be added.
163      * @throws Exception if the role already exists
164      */

165     public void addRole(Role role) throws Exception JavaDoc {
166
167         if (roles.get(role.getName()) != null) {
168             throw new Exception JavaDoc("Role " + role.getName() + " already exists.");
169         }
170
171         // Add role
172
roles.put(role.getName(), role);
173
174         //Add Mbean
175
String JavaDoc roleName = role.getName();
176         try {
177             // register security service mbean
178
getMBeanServer().registerMBean(role, JonasObjectName.role(getName(), roleName));
179         } catch (Exception JavaDoc e) {
180             getLogger().log(BasicLevel.ERROR, "Cannot register role '" + roleName + "' in JMX server : " + e.getMessage());
181         }
182     }
183
184     /**
185      * Check if a user is found and return it
186      * @param name the wanted user name
187      * @return the user found or null
188      * @throws JResourceException if there is an error during the search
189      */

190     public User findUser(String JavaDoc name) throws JResourceException {
191         if (name == null) {
192             return null;
193         }
194         return ((User) getUsers().get(name));
195     }
196
197     /**
198      * Check if the given credential is the right credential for the given user
199      * @param user user to check its credentials
200      * @param credentials the given credentials
201      * @return true if the credential is valid for this user
202      */

203     public boolean isValidUser(User user, String JavaDoc credentials) {
204
205         boolean validated = false;
206
207         //Get algorithm and hashpassword
208
String JavaDoc pass = user.getHashPassword().getPassword();
209         String JavaDoc algo = user.getHashPassword().getAlgorithm();
210
211         // Crypt password ?
212
if (algo != null) {
213             try {
214                 validated = HashHelper.hashPassword(credentials, algo).equalsIgnoreCase(pass);
215             } catch (NoSuchAlgorithmException JavaDoc nsae) {
216                 getLogger().log(BasicLevel.ERROR, "Can't make a password with the algorithm " + algo + ". "
217                         + nsae.getMessage());
218             }
219         } else {
220             // clear
221
validated = credentials.equals(pass);
222         }
223         return validated;
224     }
225
226     /**
227      * Return all the groups
228      * @return the groups
229      */

230     public Hashtable JavaDoc getGroups() {
231         return groups;
232     }
233
234     /**
235      * Return all the roles
236      * @return the roles
237      */

238     public Hashtable JavaDoc getRoles() {
239         return roles;
240     }
241
242     /**
243      * Get all the roles (from the roles and from the groups) of the given user
244      * @param user the given user
245      * @return the array list of all the roles for a given user
246      * @throws JResourceException if it fails
247      */

248     public ArrayList JavaDoc getArrayListCombinedRoles(User user) throws JResourceException {
249         ArrayList JavaDoc allCombinedRoles = new ArrayList JavaDoc();
250
251         // Return empty array if user null
252
if (user == null) {
253             return allCombinedRoles;
254         }
255
256         // Add all user roles
257
String JavaDoc[] userRoles = user.getArrayRoles();
258         for (int r = 0; r < userRoles.length; r++) {
259             String JavaDoc roleName = userRoles[r];
260             if (!allCombinedRoles.contains(roleName)) {
261                 allCombinedRoles.add(roleName);
262             }
263         }
264
265         // Add roles of each group
266
String JavaDoc[] userGroups = user.getArrayGroups();
267         for (int g = 0; g < userGroups.length; g++) {
268             String JavaDoc groupName = userGroups[g];
269
270             // For each roles of the given group
271
Group group = (Group) groups.get(groupName);
272             if (group == null) {
273                 continue;
274             }
275
276             String JavaDoc[] groupRoles = group.getArrayRoles();
277             for (int gr = 0; gr < groupRoles.length; gr++) {
278                 String JavaDoc roleName = groupRoles[gr];
279                 if (!allCombinedRoles.contains(roleName)) {
280                     allCombinedRoles.add(roleName);
281                 }
282             }
283         }
284
285         return allCombinedRoles;
286     }
287
288     /**
289      * Set the groups
290      * @param groups the groups of this resource
291      */

292     public void setGroups(Hashtable JavaDoc groups) {
293         this.groups = groups;
294     }
295
296     /**
297      * Set the roles
298      * @param roles the roles of this resource
299      */

300     public void setRoles(Hashtable JavaDoc roles) {
301         this.roles = roles;
302     }
303
304     /**
305      * Add a user with a given principal and credential
306      * @param username the name of the user
307      * @param password password of the user
308      * @throws Exception if the user already exists
309      */

310     public void addUser(String JavaDoc username, String JavaDoc password) throws Exception JavaDoc {
311         addUser(new User(username, password));
312     }
313
314     /**
315      * Add a group with a given name
316      * @param groupname the name of the group
317      * @throws Exception if the group already exists
318      */

319     public void addGroup(String JavaDoc groupname) throws Exception JavaDoc {
320         addGroup(new Group(groupname));
321     }
322
323     /**
324      * Add a role with a given name
325      * @param rolename the name of the role
326      * @throws Exception if the role already exists
327      */

328     public void addRole(String JavaDoc rolename) throws Exception JavaDoc {
329         addRole(new Role(rolename));
330     }
331
332     /**
333      * Remove a user with a given principal
334      * @param username the name of the user
335      * @throws Exception if the user was not found
336      */

337     public void removeUser(String JavaDoc username) throws Exception JavaDoc {
338         if (getUsers().get(username) == null) {
339             throw new Exception JavaDoc("Can not remove user " + username + ". This user doesn't exist");
340         }
341         getUsers().remove(username);
342
343         // Remove Mbean
344
try {
345             // register security service mbean
346
getMBeanServer().unregisterMBean(JonasObjectName.user(getName(), username));
347         } catch (Exception JavaDoc e) {
348             getLogger().log(BasicLevel.ERROR, "Cannot unregister user '" + username + "' in JMX server : " + e.getMessage());
349         }
350
351     }
352
353     /**
354      * Remove a group with a given name
355      * @param groupname the name of the group
356      * @throws Exception if the group was not found
357      */

358     public void removeGroup(String JavaDoc groupname) throws Exception JavaDoc {
359         if (groups.get(groupname) == null) {
360             throw new Exception JavaDoc("Can not remove group " + groupname + ". This group doesn't exist");
361         }
362         groups.remove(groupname);
363         // Remove Mbean
364
try {
365             // register security service mbean
366
getMBeanServer().unregisterMBean(JonasObjectName.group(getName(), groupname));
367         } catch (Exception JavaDoc e) {
368             getLogger().log(BasicLevel.ERROR, "Cannot unregister group '" + groupname + "' in JMX server : "
369                     + e.getMessage());
370         }
371     }
372
373     /**
374      * Remove a role with a given name
375      * @param rolename the name of the role
376      * @throws Exception if the role was not found
377      */

378     public void removeRole(String JavaDoc rolename) throws Exception JavaDoc {
379         if (roles.get(rolename) == null) {
380             throw new Exception JavaDoc("Can not remove role " + rolename + ". This role doesn't exist");
381         }
382         roles.remove(rolename);
383
384         // Remove Mbean
385
try {
386             // register security service mbean
387
getMBeanServer().unregisterMBean(JonasObjectName.role(getName(), rolename));
388         } catch (Exception JavaDoc e) {
389             getLogger().log(BasicLevel.ERROR, "Cannot unregister role '" + rolename + "' in JMX server : " + e.getMessage());
390         }
391     }
392
393     /**
394      * String representation of the MemoryRealm
395      * @return the xml representation of the MemoryRealm
396      */

397     public String JavaDoc toXML() {
398         StringBuffer JavaDoc xml = new StringBuffer JavaDoc(" <memoryrealm name=\"");
399         xml.append(getName());
400         xml.append("\">\n");
401
402         // Roles
403
xml.append(" <roles>\n");
404         XML.xmlHashtable(xml, getRoles(), " ");
405         xml.append(" </roles>\n");
406
407         // Groups
408
xml.append(" <groups>\n");
409         XML.xmlHashtable(xml, getGroups(), " ");
410         xml.append(" </groups>\n");
411
412         // Users
413
xml.append(" <users>\n");
414         XML.xmlHashtable(xml, getUsers(), " ");
415         xml.append(" </users>\n");
416
417         xml.append(" </memoryrealm>");
418         return xml.toString();
419     }
420
421     /**
422      * The string representation of this realm is the XML
423      * @return XML representation
424      */

425     public String JavaDoc toString() {
426         return this.toXML();
427     }
428
429     /**
430      * Retrieves the Reference of the object. The Reference contains the factory
431      * used to create this object and the optional parameters used to configure
432      * the factory.
433      * @return the non-null Reference of the object.
434      * @throws NamingException if a naming exception was encountered while
435      * retrieving the reference.
436      */

437     public Reference JavaDoc getReference() throws NamingException JavaDoc {
438
439         // Build the reference to the factory FACTORY_TYPE
440
Reference JavaDoc reference = new Reference JavaDoc(FACTORY_TYPE, FACTORY_NAME, null);
441
442         // Add name
443
reference.add(new StringRefAddr JavaDoc("name", getName()));
444
445         // Add users
446
byte[] bytes = JNDIUtils.getBytesFromObject(getUsers(), getLogger());
447         if (bytes != null) {
448             reference.add(new BinaryRefAddr JavaDoc("users", bytes));
449         }
450
451         // Add groups
452
bytes = JNDIUtils.getBytesFromObject(groups, getLogger());
453         if (bytes != null) {
454             reference.add(new BinaryRefAddr JavaDoc("groups", bytes));
455         }
456
457         // Add roles
458
bytes = JNDIUtils.getBytesFromObject(roles, getLogger());
459         if (bytes != null) {
460             reference.add(new BinaryRefAddr JavaDoc("roles", bytes));
461         }
462
463         return reference;
464
465     }
466
467     /**
468      * Get the roles
469      * @return the array of the roles
470      */

471     public String JavaDoc[] listRoles() {
472         String JavaDoc[] s = new String JavaDoc[roles.size()];
473         int i = 0;
474         for (Enumeration JavaDoc e = roles.keys(); e.hasMoreElements(); i++) {
475             s[i] = (String JavaDoc) e.nextElement();
476         }
477         return s;
478     }
479
480     /**
481      * Get the groups
482      * @return the array of the groups
483      */

484     public String JavaDoc[] listGroups() {
485         String JavaDoc[] s = new String JavaDoc[groups.size()];
486         int i = 0;
487         for (Enumeration JavaDoc e = groups.keys(); e.hasMoreElements(); i++) {
488             s[i] = (String JavaDoc) e.nextElement();
489         }
490         return s;
491     }
492
493     /**
494      * Remove all the Mbeans used by this resource
495      * @throws JResourceException if the MBeans can not be removed
496      */

497     public void removeMBeans() throws JResourceException {
498
499         boolean error = false;
500         // Remove users MBeans
501
for (Enumeration JavaDoc e = getUsers().elements(); e.hasMoreElements();) {
502             User u = (User) e.nextElement();
503             try {
504                 // unregister user mbean
505
getMBeanServer().unregisterMBean(JonasObjectName.user(getName(), u.getName()));
506             } catch (Exception JavaDoc ex) {
507                 error = true;
508                 getLogger().log(BasicLevel.ERROR, "Cannot unregister mbean user '" + u.getName() + "' in JMX server : "
509                         + ex.getMessage());
510             }
511         }
512
513         // Remove roles MBeans
514
for (Enumeration JavaDoc e = roles.elements(); e.hasMoreElements();) {
515             Role r = (Role) e.nextElement();
516             try {
517                 // unregister role mbean
518
getMBeanServer().unregisterMBean(JonasObjectName.role(getName(), r.getName()));
519             } catch (Exception JavaDoc ex) {
520                 error = true;
521                 getLogger().log(BasicLevel.ERROR, "Cannot unregister mbean role '" + r.getName() + "' in JMX server : "
522                         + ex.getMessage());
523             }
524         }
525
526         // Remove groups MBeans
527
for (Enumeration JavaDoc e = groups.elements(); e.hasMoreElements();) {
528             Group g = (Group) e.nextElement();
529             try {
530                 // unregister group mbean
531
getMBeanServer().unregisterMBean(JonasObjectName.group(getName(), g.getName()));
532             } catch (Exception JavaDoc ex) {
533                 error = true;
534                 getLogger().log(BasicLevel.ERROR, "Cannot unregister mbean group '" + g.getName() + "' in JMX server : "
535                         + ex.getMessage());
536             }
537         }
538
539         if (error) {
540             throw new JResourceException(
541                     "There was errors during the remove of the MBeans of this resource. See the traces.");
542         }
543
544     }
545
546 }
Popular Tags