KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > repository > commonimpl > user > UserImpl


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
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.outerj.daisy.repository.commonimpl.user;
17
18 import java.util.Date JavaDoc;
19 import java.util.GregorianCalendar JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.Map JavaDoc;
23
24 import org.outerj.daisy.repository.user.Role;
25 import org.outerj.daisy.repository.user.Roles;
26 import org.outerj.daisy.repository.user.User;
27 import org.outerj.daisy.repository.commonimpl.AuthenticatedUser;
28 import org.outerj.daisy.repository.RepositoryException;
29 import org.outerx.daisy.x10.RoleDocument;
30 import org.outerx.daisy.x10.RolesDocument;
31 import org.outerx.daisy.x10.UserDocument;
32 import org.outerx.daisy.x10.PublicUserInfoDocument;
33
34 public class UserImpl implements User {
35     private UserManagementStrategy userManagementStrategy;
36     /**
37      * the userId as it is known in the <b>data store</b>.
38      *
39      * <p>Not to be confused with <b>login</b>!
40      *
41      * <p>Initialize on -1 until the save method is called.
42      * As soon as the User is persisted, this id
43      * can be updated with the actual value. This allows
44      * a user of this class to distinguish between
45      * persisted and not yet persisted User objects.
46      *
47      * <p>After the UserManagementStrategy has been invoked
48      * in order to persist the User, this
49      * UserManagementStrategy itself calls a method of the
50      * Object that was used to invoke the UserManagementStrategy
51      * in the first place.
52      *
53      */

54     private long userId=-1;
55     private String JavaDoc login;
56     private RoleImpl defaultRole;
57     private String JavaDoc email;
58     private String JavaDoc firstName;
59     private String JavaDoc lastName;
60     private String JavaDoc passWord;
61     private boolean updateableByUser = false;
62     private Date JavaDoc lastModified;
63     private long lastModifier;
64     private AuthenticatedUser requestingUser;
65     private Map JavaDoc roles = new HashMap JavaDoc();
66     private long updateCount = 0;
67     private boolean confirmed = true;
68     private String JavaDoc confirmKey;
69     private boolean roleChanges=false;
70     private IntimateAccess intimateAccess = new IntimateAccess();
71     private boolean readOnly = false;
72     private String JavaDoc authenticationScheme = "daisy";
73     private static final String JavaDoc READ_ONLY_MESSAGE = "This User object is read-only.";
74
75     /**
76      * creates a new User
77      * @param userManagementStrategy the storage manipulation strategy to use
78      * @param login the login name of the new User
79      * @param requestingUser the authenticated, administrative user that requested this UserImpl object
80      */

81     public UserImpl(UserManagementStrategy userManagementStrategy, String JavaDoc login, AuthenticatedUser requestingUser) {
82         this.userManagementStrategy = userManagementStrategy;
83         this.login = login;
84         this.requestingUser = requestingUser;
85     }
86
87     public void setDefaultRole(Role role) {
88         if (readOnly)
89             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
90
91         if (role == null) {
92             this.defaultRole = null;
93         } else {
94             preRoleAddChecks(role);
95             addToRole(role);
96             this.defaultRole = (RoleImpl)role;
97         }
98     }
99
100     private void preRoleAddChecks(Role role) {
101         if (role == null)
102             throw new IllegalArgumentException JavaDoc("Role object cannot be null.");
103
104         if (!(role instanceof RoleImpl))
105             throw new IllegalArgumentException JavaDoc("Unsupported Role object supplied.");
106
107         if (((RoleImpl)role).getIntimateAccess(userManagementStrategy) == null)
108             throw new IllegalArgumentException JavaDoc("Role object is not loaded from the same Repository as this User object.");
109
110         if (role.getId() == -1)
111             throw new IllegalArgumentException JavaDoc("Only roles which have already been created in the repository can be added to a User.");
112     }
113
114     public Role getDefaultRole() {
115         return defaultRole;
116     }
117
118     public Roles getAllRoles() {
119         return getRolesFromMap();
120     }
121
122     public long[] getAllRoleIds() {
123         long[] ids = new long[roles.size()];
124         Iterator JavaDoc rolesIt = roles.values().iterator();
125         int i = 0;
126         while (rolesIt.hasNext()) {
127             ids[i++] = ((Role)rolesIt.next()).getId();
128         }
129         return ids;
130     }
131
132     public void setPassword(String JavaDoc s) {
133         if (readOnly)
134             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
135
136         passWord = s;
137     }
138
139     public void setEmail(String JavaDoc emailAddress) {
140         if (readOnly)
141             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
142
143         email = emailAddress;
144     }
145
146     public String JavaDoc getEmail() {
147         return email;
148     }
149
150     public long getId() {
151         return userId;
152     }
153
154     /**
155      * persists the state of this object to the data store
156      */

157
158     public void save() throws RepositoryException {
159         if (readOnly)
160             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
161
162         userManagementStrategy.store(this);
163     }
164
165     public UserDocument getXml() {
166         UserDocument userDocument = UserDocument.Factory.newInstance();
167         UserDocument.User userXml = userDocument.addNewUser();
168
169         if (defaultRole != null) {
170             RoleDocument.Role defaultRoleXml = defaultRole.getXml().getRole();
171             userXml.setRole(defaultRoleXml);
172         }
173
174         if (email != null)
175             userXml.setEmail(email);
176         if (firstName != null)
177             userXml.setFirstName(firstName);
178         if (lastName != null)
179             userXml.setLastName(lastName);
180         userXml.setLogin(login);
181         if (passWord != null)
182             userXml.setPassword(passWord);
183         userXml.setUpdateCount(updateCount);
184         userXml.setUpdateableByUser(updateableByUser);
185         userXml.setConfirmed(confirmed);
186         if (confirmKey != null)
187             userXml.setConfirmKey(confirmKey);
188         userXml.setAuthenticationScheme(authenticationScheme);
189
190         Roles r = getRolesFromMap();
191         RolesDocument.Roles rolesXml = r.getXml().getRoles();
192         userXml.setRoles(rolesXml);
193         
194         if (userId!=-1) {
195             GregorianCalendar JavaDoc lastModifiedCalendar = new GregorianCalendar JavaDoc();
196             lastModifiedCalendar.setTime(lastModified);
197             
198             userXml.setLastModified(lastModifiedCalendar);
199             userXml.setLastModifier(lastModifier);
200             
201             userXml.setId(userId);
202         }
203         return userDocument;
204     }
205
206     private Roles getRolesFromMap() {
207         Role[] rolesArray = (Role[])roles.values().toArray(new Role[roles.size()]);
208         Roles r = new RolesImpl(rolesArray);
209         return r;
210     }
211
212     public void addToRole(Role role) {
213         if (readOnly)
214             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
215
216         preRoleAddChecks(role);
217
218         if (!roles.containsKey(new Long JavaDoc(role.getId()))) {
219             roleChanges = true;
220             roles.put(new Long JavaDoc(role.getId()), role);
221         }
222     }
223
224     public void removeFromRole(Role role) {
225         if (readOnly)
226             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
227
228         roleChanges = true;
229         roles.remove(new Long JavaDoc(role.getId()));
230     }
231
232     public String JavaDoc getLogin() {
233         return login;
234     }
235
236     public void setFirstName(String JavaDoc firstName) {
237         if (readOnly)
238             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
239
240         this.firstName = firstName;
241     }
242
243     public void setLastName(String JavaDoc lastName) {
244         if (readOnly)
245             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
246
247         this.lastName = lastName;
248     }
249
250     public String JavaDoc getFirstName() {
251         return firstName;
252     }
253
254     public String JavaDoc getLastName() {
255         return lastName;
256     }
257
258     public String JavaDoc getDisplayName() {
259         String JavaDoc name = null;
260         if (firstName == null && lastName == null) {
261             name = login;
262         } else if (firstName != null && lastName != null) {
263             name = firstName + " " + lastName;
264         } else if (lastName != null) {
265             name = lastName;
266         } else {
267             name = firstName;
268         }
269         return name;
270     }
271
272     /**
273      * Disables all operations that can modify the state of this object.
274      */

275     public void makeReadOnly() {
276         this.readOnly = true;
277
278         // also make associated roles read-only
279
if (defaultRole != null)
280             defaultRole.makeReadOnly();
281         Iterator JavaDoc roleIt = roles.values().iterator();
282         while (roleIt.hasNext()) {
283             ((RoleImpl)roleIt.next()).makeReadOnly();
284         }
285     }
286
287     public IntimateAccess getIntimateAccess(UserManagementStrategy strategy) {
288         if (readOnly)
289             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
290
291         if (this.userManagementStrategy == strategy)
292             return intimateAccess;
293         else
294             return null;
295     }
296     
297     public Date JavaDoc getLastModified() {
298         if (lastModified != null)
299             return (Date JavaDoc)lastModified.clone();
300         else
301             return lastModified;
302     }
303
304     public long getLastModifier() {
305         return lastModifier;
306     }
307
308     /**
309      * <p>Checks if a supplied password is valid.
310      *
311      * <p>Currently the rules for validity are:
312      * <ol>
313      * <li>Must be different from null
314      * <li>Must have a length of at least 1 character
315      * </ol>
316      * @param password the password to check for validity
317      * @return true if valid, false if not valid
318      */

319     public static boolean isValidPassword(String JavaDoc password) {
320         boolean isValid = false;
321         if (password!=null){
322             if (password.length()>=1) isValid=true;
323         }
324         return isValid;
325     }
326
327     public void clearRoles() {
328         if (readOnly)
329             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
330
331         this.roles.clear();
332         this.roleChanges = true;
333         this.defaultRole = null;
334     }
335
336     public void setLogin(String JavaDoc loginName) {
337         if (readOnly)
338             throw new RuntimeException JavaDoc(READ_ONLY_MESSAGE);
339
340         this.login = loginName;
341     }
342
343     public long getUpdateCount() {
344         return updateCount;
345     }
346
347     public boolean hasRole(long roleId) {
348         return roles.containsKey(new Long JavaDoc(roleId));
349     }
350
351     public boolean isUpdateableByUser() {
352         return updateableByUser;
353     }
354
355     public void setUpdateableByUser(boolean updateableByUser) {
356         this.updateableByUser = updateableByUser;
357     }
358
359     public boolean isConfirmed() {
360         return confirmed;
361     }
362
363     public void setConfirmed(boolean confirmed) {
364         this.confirmed = confirmed;
365     }
366
367     public String JavaDoc getConfirmKey() {
368         return confirmKey;
369     }
370
371     public void setConfirmKey(String JavaDoc confirmKey) {
372         this.confirmKey = confirmKey;
373     }
374
375     public String JavaDoc getAuthenticationScheme() {
376         return authenticationScheme;
377     }
378
379     public void setAuthenticationScheme(String JavaDoc schemeName) {
380         if (schemeName == null)
381             throw new IllegalArgumentException JavaDoc("schemeName cannot be null.");
382         if (schemeName.length() < 1)
383             throw new IllegalArgumentException JavaDoc("schemeName cannot be an empty string.");
384
385         this.authenticationScheme = schemeName;
386     }
387
388     public PublicUserInfoDocument getPublicUserInfo() {
389         PublicUserInfoDocument publicInfoDocument = PublicUserInfoDocument.Factory.newInstance();
390         PublicUserInfoDocument.PublicUserInfo publicInfoXml = publicInfoDocument.addNewPublicUserInfo();
391         publicInfoXml.setId(getId());
392         publicInfoXml.setLogin(getLogin());
393         publicInfoXml.setDisplayName(getDisplayName());
394         return publicInfoDocument;
395     }
396
397     /**
398      * provides intimate access to the UserImpl.
399      */

400     public class IntimateAccess {
401         private IntimateAccess() {
402         }
403
404         public void setLastModified(Date JavaDoc lastModDate) {
405             lastModified = lastModDate;
406         }
407         public void setLastModifier(long lastMod) {
408             lastModifier = lastMod;
409         }
410
411         public AuthenticatedUser getCurrentUser() {
412             return requestingUser;
413         }
414
415         public void saved(long id, String JavaDoc firstName, String JavaDoc lastName, String JavaDoc email, Date JavaDoc lastModified, long lastModifier, long updateCount) {
416             userId = id;
417             UserImpl.this.firstName = firstName;
418             UserImpl.this.lastName = lastName;
419             UserImpl.this.email = email;
420             UserImpl.this.lastModified = lastModified;
421             UserImpl.this.lastModifier = lastModifier;
422             UserImpl.this.updateCount = updateCount;
423             roleChanges=false;
424         }
425
426         /**
427          * We <b>only</b> allow access to the supplied password value through Intimate Access!
428          * @return the password supplied by the user, meant to be stored in the data store immediately
429          */

430         public String JavaDoc getPassword() {
431             return passWord;
432         }
433
434         public void addToRole(Role r) {
435             roles.put(new Long JavaDoc(r.getId()), r);
436         }
437
438         /**
439          * marks if this user has role changes or not
440          */

441         public boolean hasRoleChanges() {
442             return roleChanges;
443         }
444     }
445 }
446
Popular Tags