KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > methodhead > reg > User


1 /*
2  * Copyright (C) 2006 Methodhead Software LLC. All rights reserved.
3  *
4  * This file is part of TransferCM.
5  *
6  * TransferCM is free software; you can redistribute it and/or modify it under the
7  * terms of the GNU General Public License as published by the Free Software
8  * Foundation; either version 2 of the License, or (at your option) any later
9  * version.
10  *
11  * TransferCM is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * TransferCM; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
18  * Fifth Floor, Boston, MA 02110-1301 USA
19  */

20
21 package com.methodhead.reg;
22
23 import com.methodhead.persistable.Persistable;
24 import com.methodhead.persistable.Key;
25 import com.methodhead.aikp.AutoIntKeyPersistable;
26 import com.methodhead.aikp.IntKey;
27 import com.methodhead.sitecontext.SiteContext;
28 import com.methodhead.auth.AuthUser;
29 import com.methodhead.util.MhfStringUtils;
30
31 import org.apache.commons.beanutils.DynaClass;
32 import org.apache.commons.beanutils.DynaProperty;
33 import org.apache.commons.beanutils.BasicDynaClass;
34 import java.util.ArrayList JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.sql.ResultSet JavaDoc;
38 import java.sql.SQLException JavaDoc;
39 import com.methodhead.persistable.ConnectionSingleton;
40 import org.apache.commons.lang.exception.ExceptionUtils;
41 import java.security.MessageDigest JavaDoc;
42 import java.security.NoSuchAlgorithmException JavaDoc;
43 import org.apache.log4j.Logger;
44 import org.apache.commons.lang.exception.ExceptionUtils;
45
46 /**
47  * A User. The following fields are defined:
48  * <ul>
49  * <li><tt>int id = 0</tt></li>
50  * <li><tt>String password = ""</tt></li>
51  * <li><tt>int contact_id = 0</tt></li>
52  * </ul>
53  */

54 public class User
55 extends
56   AutoIntKeyPersistable
57 implements
58   AuthUser,
59   Comparable JavaDoc {
60
61   private static DynaClass dynaClass_ = null;
62   private static DynaClass roleDynaClass_ = null;
63   private static DynaClass siteContextDynaClass_ = null;
64
65   static {
66     //
67
// user
68
//
69
DynaProperty[] dynaProperties =
70       new DynaProperty[] {
71         new DynaProperty( "id", Integer JavaDoc.class ),
72         new DynaProperty( "password", String JavaDoc.class ),
73         new DynaProperty( "contact_id", Integer JavaDoc.class )
74       };
75
76     dynaClass_ =
77       new BasicDynaClass(
78         "reg_user", User.class, dynaProperties );
79
80     //
81
// role
82
//
83
dynaProperties =
84       new DynaProperty[] {
85         new DynaProperty( "user_id", Integer JavaDoc.class ),
86         new DynaProperty( "sitecontext_id", Integer JavaDoc.class ),
87         new DynaProperty( "name", String JavaDoc.class )
88       };
89
90     roleDynaClass_ =
91       new BasicDynaClass(
92         "reg_role", Persistable.class, dynaProperties );
93   }
94
95   // constructors /////////////////////////////////////////////////////////////
96

97   public User() {
98     super( dynaClass_ );
99     init();
100   }
101
102   public User( DynaClass dynaClass ) {
103     super( dynaClass );
104     init();
105   }
106
107   // constants ////////////////////////////////////////////////////////////////
108

109   // classes //////////////////////////////////////////////////////////////////
110

111   // methods //////////////////////////////////////////////////////////////////
112

113   public int compareTo(
114     Object JavaDoc o ) {
115
116     if ( o == null ) {
117       throw new NullPointerException JavaDoc();
118     }
119
120     User user = ( User )o;
121
122     return this.getContact().getFullName().compareTo( user.getContact().getFullName() );
123   }
124
125   protected void init() {
126     setInt( "id", 0 );
127     setString( "password", "" );
128     setInt( "contact_id", 0 );
129   }
130
131   public String JavaDoc toString() {
132     if ( "".equals( getContact().getString( "email" ) ) )
133       return "User (no email address)";
134     else
135       return getContact().getString( "email" );
136   }
137
138   /**
139    * Extends default behaviour to handle password encryption if
140    * passwordEncrypted flag is set.
141    */

142   public void set(
143     String JavaDoc name,
144     Object JavaDoc value ) {
145
146     if ( !loading_ ) {
147       if ( "password".equals( name ) ) {
148         if ( getPasswordEncrypted() ) {
149           super.set( "password", encryptPassword( ( String JavaDoc )value ) );
150           return;
151         }
152       }
153     }
154
155     super.set( name, value );
156   }
157
158   public boolean authenticate(
159     String JavaDoc password ) {
160
161     if ( getPasswordEncrypted() ) {
162
163       return getString( "password" ).equals( encryptPassword( password ) );
164     }
165     else {
166       return getString( "password" ).equals( password );
167     }
168   }
169
170   public String JavaDoc getLogin() {
171     return getContact().getString( "email" );
172   }
173
174   public String JavaDoc getPublicSecret() {
175     return encryptPassword( getString( "password" ) );
176   }
177
178   public boolean loadForLogin(
179     String JavaDoc login ) {
180
181     ResultSet JavaDoc rs = null;
182     try {
183       String JavaDoc sql =
184         "SELECT " +
185         " reg_user.id AS id " +
186         "FROM " +
187         " reg_user " +
188         "LEFT JOIN " +
189         " reg_contact ON " +
190         " reg_user.contact_id = reg_contact.id " +
191         "WHERE " +
192         " reg_contact.email=" + getSqlLiteral( login );
193
194       rs = ConnectionSingleton.runQuery( sql );
195
196       if ( rs == null ) {
197         throw new SQLException JavaDoc( "Null result set." );
198       }
199
200       if ( !rs.next() ) {
201         return false;
202       }
203
204       load( new IntKey( rs.getInt( "id" ) ) );
205       return true;
206     }
207     catch ( SQLException JavaDoc e ) {
208       String JavaDoc msg = "Doing something. " + ExceptionUtils.getStackTrace( e );
209       logger_.error( msg );
210       throw new RuntimeException JavaDoc( msg );
211     }
212     finally {
213       ConnectionSingleton.close( rs );
214     }
215   }
216
217   /**
218    * Returns true if this user has the role <tt>name</tt> for the site
219    * <tt>siteContext</tt>.
220    */

221   public boolean hasRole(
222     SiteContext siteContext,
223     String JavaDoc name ) {
224
225     for ( Iterator JavaDoc iter = roles_.iterator(); iter.hasNext(); ) {
226       Role role = ( Role )iter.next();
227
228       if ( role.getSiteContext().equals( siteContext ) &&
229            role.getName().equals( name ) )
230         return true;
231     }
232
233     return false;
234   }
235
236   private SiteContext getSiteContext(
237     int id ) {
238
239     SiteContext siteContext = new SiteContext();
240     siteContext.load( new IntKey( id ) );
241     return siteContext;
242   }
243
244   private void saveRoles() {
245     Persistable p = new Persistable( roleDynaClass_ );
246     p.setInt( "user_id", getInt( "id" ) );
247
248     for ( Iterator JavaDoc iter = roles_.iterator(); iter.hasNext(); ) {
249       Role role = ( Role )iter.next();
250       p.setString( "name", role.getName() );
251       p.setInt( "sitecontext_id", role.getSiteContext().getInt( "id" ) );
252       p.saveNew();
253     }
254   }
255
256   private void loadRoles() {
257     List JavaDoc l =
258       Persistable.loadAll( roleDynaClass_, "user_id=" + getInt( "id" ), null );
259
260
261     roles_.clear();
262     for ( Iterator JavaDoc iter = l.iterator(); iter.hasNext(); ) {
263       Persistable p = ( Persistable )iter.next();
264
265       Role role = new Role();
266       role.setSiteContext( getSiteContext( p.getInt( "sitecontext_id" ) ) );
267       role.setName( p.getString( "name" ) );
268
269       roles_.add( role );
270     }
271   }
272
273   private void deleteRoles() {
274     Persistable p = new Persistable( roleDynaClass_ );
275     p.deleteAll( roleDynaClass_, "user_id=" + getInt( "id" ) );
276   }
277
278   public void saveNew() {
279     contact_.saveNew();
280     setInt( "contact_id", contact_.getInt( "id" ) );
281     super.saveNew();
282     saveRoles();
283   }
284
285   public void load(
286     Key key ) {
287
288     loading_ = true;
289     super.load( key );
290     contact_.load( new IntKey( getInt( "contact_id" ) ) );
291     loadRoles();
292     loading_ = false;
293   }
294
295   public void save() {
296     deleteRoles();
297     saveRoles();
298
299     super.save();
300     contact_.save();
301   }
302
303   public void delete() {
304     deleteRoles();
305     super.delete();
306     contact_.delete();
307   }
308
309   /**
310    * Returns a list of all {@link com.methodhead.reg.User User}s associated
311    * with <tt>siteContext</tt>.
312    */

313   public List JavaDoc loadAllForSiteContext(
314     SiteContext siteContext ) {
315
316     ResultSet JavaDoc rs = null;
317
318     List JavaDoc list = new ArrayList JavaDoc();
319
320     try {
321       rs = ConnectionSingleton.runQuery(
322         "SELECT DISTINCT user_id FROM reg_role WHERE sitecontext_id=" +
323         siteContext.getInt( "id" ) );
324
325       while ( rs.next() ) {
326         User user = new User();
327         user.load( new IntKey( rs.getInt( "user_id" ) ) );
328         list.add( user );
329       }
330
331       ConnectionSingleton.close( rs );
332     }
333     catch ( SQLException JavaDoc e ) {
334       ConnectionSingleton.close( rs );
335       throw new RuntimeException JavaDoc(
336         "Unexpected SQLException while loading all users for site context " +
337         siteContext + ":\n" + ExceptionUtils.getStackTrace( e ) );
338     }
339
340     return list;
341   }
342
343   /**
344    * Encrypts <tt>password</tt> by MD5 hashing it and Base64 encoding the
345    * result.
346    */

347   protected String JavaDoc encryptPassword(
348     String JavaDoc password ) {
349
350     return MhfStringUtils.hashAndEncode( password );
351   }
352
353   // properties ///////////////////////////////////////////////////////////////
354

355   /**
356    * Returns a list of {@link Role Role}s for the user.
357    */

358   public List JavaDoc getRoles() {
359     return roles_;
360   }
361
362   public Contact getContact() {
363     return contact_;
364   }
365
366   public boolean getPasswordEncrypted() {
367     return passwordEncrypted_;
368   }
369
370   /**
371    * Sets the password encrypted flag. When this flag is set, passwords are
372    * hashed with MD5 and Base64 encoded before being saved in the database or
373    * used in {@link #authenticate authenticate()}.
374    */

375   public void setPasswordEncrypted(
376     boolean passwordEncrypted ) {
377     passwordEncrypted_ = passwordEncrypted;
378   }
379
380   // attributes ///////////////////////////////////////////////////////////////
381

382   private List JavaDoc roles_ = new ArrayList JavaDoc();
383   private Contact contact_ = new Contact();
384   private boolean passwordEncrypted_ = false;
385   private boolean loading_ = false;
386
387   private static Logger logger_ = Logger.getLogger( User.class );
388 }
389
Popular Tags