KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > eperson > EPerson


1 /*
2  * EPerson.java
3  *
4  * Version: $Revision: 1.33 $
5  *
6  * Date: $Date: 2006/11/22 17:41:52 $
7  *
8  * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
9  * Institute of Technology. All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions are
13  * met:
14  *
15  * - Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * - Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in the
20  * documentation and/or other materials provided with the distribution.
21  *
22  * - Neither the name of the Hewlett-Packard Company nor the name of the
23  * Massachusetts Institute of Technology nor the names of their
24  * contributors may be used to endorse or promote products derived from
25  * this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  */

40 package org.dspace.eperson;
41
42 import java.sql.SQLException JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.List JavaDoc;
45 import java.util.Vector JavaDoc;
46
47 import org.apache.log4j.Logger;
48 import org.dspace.authorize.AuthorizeException;
49 import org.dspace.authorize.AuthorizeManager;
50 import org.dspace.content.DSpaceObject;
51 import org.dspace.core.ConfigurationManager;
52 import org.dspace.core.Constants;
53 import org.dspace.core.Context;
54 import org.dspace.core.LogManager;
55 import org.dspace.core.Utils;
56 import org.dspace.history.HistoryManager;
57 import org.dspace.storage.rdbms.DatabaseManager;
58 import org.dspace.storage.rdbms.TableRow;
59 import org.dspace.storage.rdbms.TableRowIterator;
60
61 /**
62  * Class representing an e-person.
63  *
64  * @author David Stuve
65  * @version $Revision: 1.33 $
66  */

67 public class EPerson extends DSpaceObject
68 {
69     /** The e-mail field (for sorting) */
70     public static final int EMAIL = 1;
71
72     /** The last name (for sorting) */
73     public static final int LASTNAME = 2;
74
75     /** The e-mail field (for sorting) */
76     public static final int ID = 3;
77
78     /** The netid field (for sorting) */
79     public static final int NETID = 4;
80
81     /** log4j logger */
82     private static Logger log = Logger.getLogger(EPerson.class);
83
84     /** Our context */
85     private Context myContext;
86
87     /** The row in the table representing this eperson */
88     private TableRow myRow;
89
90     /**
91      * Construct an EPerson
92      *
93      * @param context
94      * the context this object exists in
95      * @param row
96      * the corresponding row in the table
97      */

98     EPerson(Context context, TableRow row)
99     {
100         myContext = context;
101         myRow = row;
102
103         // Cache ourselves
104
context.cache(this, row.getIntColumn("eperson_id"));
105     }
106
107     /**
108      * Get an EPerson from the database.
109      *
110      * @param context
111      * DSpace context object
112      * @param id
113      * ID of the EPerson
114      *
115      * @return the EPerson format, or null if the ID is invalid.
116      */

117     public static EPerson find(Context context, int id) throws SQLException JavaDoc
118     {
119         // First check the cache
120
EPerson fromCache = (EPerson) context.fromCache(EPerson.class, id);
121
122         if (fromCache != null)
123         {
124             return fromCache;
125         }
126
127         TableRow row = DatabaseManager.find(context, "eperson", id);
128
129         if (row == null)
130         {
131             return null;
132         }
133         else
134         {
135             return new EPerson(context, row);
136         }
137     }
138
139     /**
140      * Find the eperson by their email address
141      *
142      * @return EPerson
143      */

144     public static EPerson findByEmail(Context context, String JavaDoc email)
145             throws SQLException JavaDoc, AuthorizeException
146     {
147         TableRow row = DatabaseManager.findByUnique(context, "eperson",
148                 "email", email);
149
150         if (row == null)
151         {
152             return null;
153         }
154         else
155         {
156             // First check the cache
157
EPerson fromCache = (EPerson) context.fromCache(EPerson.class, row
158                     .getIntColumn("eperson_id"));
159
160             if (fromCache != null)
161             {
162                 return fromCache;
163             }
164             else
165             {
166                 return new EPerson(context, row);
167             }
168         }
169     }
170
171     /**
172      * Find the eperson by their netid
173      *
174      * @param context
175      * DSpace context
176      * @param netid
177      * Network ID
178      *
179      * @return corresponding EPerson, or <code>null</code>
180      */

181     public static EPerson findByNetid(Context context, String JavaDoc netid)
182             throws SQLException JavaDoc
183     {
184         if (netid == null)
185             return null;
186
187         TableRow row = DatabaseManager.findByUnique(context, "eperson",
188                 "netid", netid);
189
190         if (row == null)
191         {
192             return null;
193         }
194         else
195         {
196             // First check the cache
197
EPerson fromCache = (EPerson) context.fromCache(EPerson.class, row
198                     .getIntColumn("eperson_id"));
199
200             if (fromCache != null)
201             {
202                 return fromCache;
203             }
204             else
205             {
206                 return new EPerson(context, row);
207             }
208         }
209     }
210
211     /**
212      * Find the epeople that match the search query across firstname, lastname or email
213      *
214      * @param context
215      * DSpace context
216      * @param query
217      * The search string
218      *
219      * @return array of EPerson objects
220      */

221     public static EPerson[] search(Context context, String JavaDoc query)
222             throws SQLException JavaDoc
223     {
224         return search(context, query, -1, -1);
225     }
226     
227     /**
228      * Find the epeople that match the search query across firstname, lastname or email.
229      * This method also allows offsets and limits for pagination purposes.
230      *
231      * @param context
232      * DSpace context
233      * @param query
234      * The search string
235      * @param offset
236      * Inclusive offset
237      * @param limit
238      * Maximum number of matches returned
239      *
240      * @return array of EPerson objects
241      */

242     public static EPerson[] search(Context context, String JavaDoc query, int offset, int limit)
243             throws SQLException JavaDoc
244     {
245         String JavaDoc params = "%"+query.toLowerCase()+"%";
246         String JavaDoc dbquery = "SELECT * FROM eperson WHERE eperson_id = ? OR " +
247             "firstname ILIKE ? OR lastname ILIKE ? OR email ILIKE ? ORDER BY lastname, firstname ASC ";
248         
249         if (offset >= 0 && limit >0) {
250             dbquery += "LIMIT " + limit + " OFFSET " + offset;
251         }
252         
253         // When checking against the eperson-id, make sure the query can be made into a number
254
Integer JavaDoc int_param;
255         try {
256             int_param = Integer.valueOf(query);
257         }
258         catch (NumberFormatException JavaDoc e) {
259             int_param = new Integer JavaDoc(-1);
260         }
261         
262         // Get all the epeople that match the query
263
TableRowIterator rows = DatabaseManager.query(context, dbquery, new Object JavaDoc[] {int_param,params,params,params});
264         
265         List JavaDoc epeopleRows = rows.toList();
266         EPerson[] epeople = new EPerson[epeopleRows.size()];
267         
268         for (int i = 0; i < epeopleRows.size(); i++)
269         {
270             TableRow row = (TableRow) epeopleRows.get(i);
271         
272             // First check the cache
273
EPerson fromCache = (EPerson) context.fromCache(EPerson.class, row
274                     .getIntColumn("eperson_id"));
275         
276             if (fromCache != null)
277             {
278                 epeople[i] = fromCache;
279             }
280             else
281             {
282                 epeople[i] = new EPerson(context, row);
283             }
284         }
285         
286         return epeople;
287     }
288
289     /**
290      * Returns the total number of epeople returned by a specific query, without the overhead
291      * of creating the EPerson objects to store the results.
292      *
293      * @param context
294      * DSpace context
295      * @param query
296      * The search string
297      *
298      * @return the number of epeople mathching the query
299      */

300     public static int searchResultCount(Context context, String JavaDoc query)
301         throws SQLException JavaDoc
302     {
303         String JavaDoc dbquery = "%"+query.toLowerCase()+"%";
304         Long JavaDoc count;
305         
306         // When checking against the eperson-id, make sure the query can be made into a number
307
Integer JavaDoc int_param;
308         try {
309             int_param = Integer.valueOf(query);
310         }
311         catch (NumberFormatException JavaDoc e) {
312             int_param = new Integer JavaDoc(-1);
313         }
314         
315         // Get all the epeople that match the query
316
TableRow row = DatabaseManager.querySingle(context,
317                 "SELECT count(*) as count FROM eperson WHERE eperson_id = ? OR " +
318                 "firstname ILIKE ? OR lastname ILIKE ? OR email ILIKE ?",
319                 new Object JavaDoc[] {int_param,dbquery,dbquery,dbquery});
320                 
321         // use getIntColumn for Oracle count data
322
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
323         {
324             count = new Long JavaDoc(row.getIntColumn("count"));
325         }
326         else //getLongColumn works for postgres
327
{
328             count = new Long JavaDoc(row.getLongColumn("count"));
329         }
330         
331         return count.intValue();
332     }
333     
334     
335     
336     /**
337      * Find all the epeople that match a particular query
338      * <ul>
339      * <li><code>ID</code></li>
340      * <li><code>LASTNAME</code></li>
341      * <li><code>EMAIL</code></li>
342      * <li><code>NETID</code></li>
343      * </ul>
344      *
345      * @return array of EPerson objects
346      */

347     public static EPerson[] findAll(Context context, int sortField)
348             throws SQLException JavaDoc
349     {
350         String JavaDoc s;
351
352         switch (sortField)
353         {
354         case ID:
355             s = "eperson_id";
356             break;
357
358         case EMAIL:
359             s = "email";
360             break;
361
362         case NETID:
363             s = "netid";
364             break;
365
366         default:
367             s = "lastname";
368         }
369
370         // NOTE: The use of 's' in the order by clause can not cause an sql
371
// injection because the string is derived from constant values above.
372
TableRowIterator rows = DatabaseManager.query(context,
373                 "SELECT * FROM eperson ORDER BY "+s);
374
375         List JavaDoc epeopleRows = rows.toList();
376
377         EPerson[] epeople = new EPerson[epeopleRows.size()];
378
379         for (int i = 0; i < epeopleRows.size(); i++)
380         {
381             TableRow row = (TableRow) epeopleRows.get(i);
382
383             // First check the cache
384
EPerson fromCache = (EPerson) context.fromCache(EPerson.class, row
385                     .getIntColumn("eperson_id"));
386
387             if (fromCache != null)
388             {
389                 epeople[i] = fromCache;
390             }
391             else
392             {
393                 epeople[i] = new EPerson(context, row);
394             }
395         }
396
397         return epeople;
398     }
399
400     /**
401      * Create a new eperson
402      *
403      * @param context
404      * DSpace context object
405      */

406     public static EPerson create(Context context) throws SQLException JavaDoc,
407             AuthorizeException
408     {
409         // authorized?
410
if (!AuthorizeManager.isAdmin(context))
411         {
412             throw new AuthorizeException(
413                     "You must be an admin to create an EPerson");
414         }
415
416         // Create a table row
417
TableRow row = DatabaseManager.create(context, "eperson");
418
419         EPerson e = new EPerson(context, row);
420
421         log.info(LogManager.getHeader(context, "create_eperson", "eperson_id="
422                 + e.getID()));
423
424         HistoryManager.saveHistory(context, e, HistoryManager.REMOVE, context
425                 .getCurrentUser(), context.getExtraLogInfo());
426
427         return e;
428     }
429
430     /**
431      * Delete an eperson
432      *
433      */

434     public void delete() throws SQLException JavaDoc, AuthorizeException,
435             EPersonDeletionException
436     {
437         // authorized?
438
if (!AuthorizeManager.isAdmin(myContext))
439         {
440             throw new AuthorizeException(
441                     "You must be an admin to delete an EPerson");
442         }
443
444         HistoryManager.saveHistory(myContext, this, HistoryManager.REMOVE,
445                 myContext.getCurrentUser(), myContext.getExtraLogInfo());
446
447         // check for presence of eperson in tables that
448
// have constraints on eperson_id
449
Vector JavaDoc constraintList = getDeleteConstraints();
450
451         // if eperson exists in tables that have constraints
452
// on eperson, throw an exception
453
if (constraintList.size() > 0)
454         {
455             throw new EPersonDeletionException(constraintList);
456         }
457
458         // Remove from cache
459
myContext.removeCached(this, getID());
460
461         // Remove any group memberships first
462
DatabaseManager.updateQuery(myContext,
463                 "DELETE FROM EPersonGroup2EPerson WHERE eperson_id= ? ",
464                 getID());
465
466         // Remove any subscriptions
467
DatabaseManager.updateQuery(myContext,
468                 "DELETE FROM subscription WHERE eperson_id= ? ",
469                 getID());
470
471         // Remove ourself
472
DatabaseManager.delete(myContext, myRow);
473
474         log.info(LogManager.getHeader(myContext, "delete_eperson",
475                 "eperson_id=" + getID()));
476     }
477
478     /**
479      * Get the e-person's internal identifier
480      *
481      * @return the internal identifier
482      */

483     public int getID()
484     {
485         return myRow.getIntColumn("eperson_id");
486     }
487
488     public String JavaDoc getHandle()
489     {
490         // No Handles for e-people
491
return null;
492     }
493
494     /**
495      * Get the e-person's email address
496      *
497      * @return their email address
498      */

499     public String JavaDoc getEmail()
500     {
501         return myRow.getStringColumn("email");
502     }
503
504     /**
505      * Set the EPerson's email
506      *
507      * @param s
508      * the new email
509      */

510     public void setEmail(String JavaDoc s)
511     {
512         if (s != null)
513         {
514             s = s.toLowerCase();
515         }
516
517         myRow.setColumn("email", s);
518     }
519
520     /**
521      * Get the e-person's netid
522      *
523      * @return their netid
524      */

525     public String JavaDoc getNetid()
526     {
527         return myRow.getStringColumn("netid");
528     }
529
530     /**
531      * Set the EPerson's netid
532      *
533      * @param s
534      * the new netid
535      */

536     public void setNetid(String JavaDoc s)
537     {
538         if (s != null)
539         {
540             s = s.toLowerCase();
541         }
542
543         myRow.setColumn("netid", s);
544     }
545
546     /**
547      * Get the e-person's full name, combining first and last name in a
548      * displayable string.
549      *
550      * @return their full name
551      */

552     public String JavaDoc getFullName()
553     {
554         String JavaDoc f = myRow.getStringColumn("firstname");
555         String JavaDoc l = myRow.getStringColumn("lastname");
556
557         if ((l == null) && (f == null))
558         {
559             return getEmail();
560         }
561         else if (f == null)
562         {
563             return l;
564         }
565         else
566         {
567             return (f + " " + l);
568         }
569     }
570
571     /**
572      * Get the eperson's first name.
573      *
574      * @return their first name
575      */

576     public String JavaDoc getFirstName()
577     {
578         return myRow.getStringColumn("firstname");
579     }
580
581     /**
582      * Set the eperson's first name
583      *
584      * @param firstname
585      * the person's first name
586      */

587     public void setFirstName(String JavaDoc firstname)
588     {
589         myRow.setColumn("firstname", firstname);
590     }
591
592     /**
593      * Get the eperson's last name.
594      *
595      * @return their last name
596      */

597     public String JavaDoc getLastName()
598     {
599         return myRow.getStringColumn("lastname");
600     }
601
602     /**
603      * Set the eperson's last name
604      *
605      * @param lastname
606      * the person's last name
607      */

608     public void setLastName(String JavaDoc lastname)
609     {
610         myRow.setColumn("lastname", lastname);
611     }
612
613     /**
614      * Indicate whether the user can log in
615      *
616      * @param login
617      * boolean yes/no
618      */

619     public void setCanLogIn(boolean login)
620     {
621         myRow.setColumn("can_log_in", login);
622     }
623
624     /**
625      * Can the user log in?
626      *
627      * @return boolean, yes/no
628      */

629     public boolean canLogIn()
630     {
631         return myRow.getBooleanColumn("can_log_in");
632     }
633
634     /**
635      * Set require cert yes/no
636      *
637      * @param isrequired
638      * boolean yes/no
639      */

640     public void setRequireCertificate(boolean isrequired)
641     {
642         myRow.setColumn("require_certificate", isrequired);
643     }
644
645     /**
646      * Get require certificate or not
647      *
648      * @return boolean, yes/no
649      */

650     public boolean getRequireCertificate()
651     {
652         return myRow.getBooleanColumn("require_certificate");
653     }
654
655     /**
656      * Indicate whether the user self-registered
657      *
658      * @param sr
659      * boolean yes/no
660      */

661     public void setSelfRegistered(boolean sr)
662     {
663         myRow.setColumn("self_registered", sr);
664     }
665
666     /**
667      * Can the user log in?
668      *
669      * @return boolean, yes/no
670      */

671     public boolean getSelfRegistered()
672     {
673         return myRow.getBooleanColumn("self_registered");
674     }
675
676     /**
677      * Get the value of a metadata field
678      *
679      * @param field
680      * the name of the metadata field to get
681      *
682      * @return the value of the metadata field
683      *
684      * @exception IllegalArgumentException
685      * if the requested metadata field doesn't exist
686      */

687     public String JavaDoc getMetadata(String JavaDoc field)
688     {
689         return myRow.getStringColumn(field);
690     }
691
692     /**
693      * Set a metadata value
694      *
695      * @param field
696      * the name of the metadata field to get
697      * @param value
698      * value to set the field to
699      *
700      * @exception IllegalArgumentException
701      * if the requested metadata field doesn't exist
702      */

703     public void setMetadata(String JavaDoc field, String JavaDoc value)
704     {
705         myRow.setColumn(field, value);
706     }
707
708     /**
709      * Set the EPerson's password
710      *
711      * @param s
712      * the new email
713      */

714     public void setPassword(String JavaDoc s)
715     {
716         // FIXME: encoding
717
String JavaDoc encoded = Utils.getMD5(s);
718
719         myRow.setColumn("password", encoded);
720     }
721
722     /**
723      * Check EPerson's password
724      *
725      * @param attempt
726      * the password attempt
727      * @return boolean successful/unsuccessful
728      */

729     public boolean checkPassword(String JavaDoc attempt)
730     {
731         String JavaDoc encoded = Utils.getMD5(attempt);
732
733         return (encoded.equals(myRow.getStringColumn("password")));
734     }
735
736     /**
737      * Update the EPerson
738      */

739     public void update() throws SQLException JavaDoc, AuthorizeException
740     {
741         // Check authorisation - if you're not the eperson
742
// see if the authorization system says you can
743
if (!myContext.ignoreAuthorization()
744                 && ((myContext.getCurrentUser() == null) || (getID() != myContext
745                         .getCurrentUser().getID())))
746         {
747             AuthorizeManager.authorizeAction(myContext, this, Constants.WRITE);
748         }
749
750         DatabaseManager.update(myContext, myRow);
751
752         log.info(LogManager.getHeader(myContext, "update_eperson",
753                 "eperson_id=" + getID()));
754
755         HistoryManager.saveHistory(myContext, this, HistoryManager.MODIFY,
756                 myContext.getCurrentUser(), myContext.getExtraLogInfo());
757     }
758
759     /**
760      * Return <code>true</code> if <code>other</code> is the same EPerson as
761      * this object, <code>false</code> otherwise
762      *
763      * @param other
764      * object to compare to
765      *
766      * @return <code>true</code> if object passed in represents the same
767      * eperson as this object
768      */

769     public boolean obsolete_equals(Object JavaDoc other)
770     {
771         if (!(other instanceof EPerson))
772         {
773             return false;
774         }
775
776         return (getID() == ((EPerson) other).getID());
777     }
778
779     /**
780      * return type found in Constants
781      */

782     public int getType()
783     {
784         return Constants.EPERSON;
785     }
786
787     /**
788      * Check for presence of EPerson in tables that have constraints on
789      * EPersons. Called by delete() to determine whether the eperson can
790      * actually be deleted.
791      *
792      * An EPerson cannot be deleted if it exists in the item, workflowitem, or
793      * tasklistitem tables.
794      *
795      * @return Vector of tables that contain a reference to the eperson.
796      */

797     public Vector JavaDoc getDeleteConstraints() throws SQLException JavaDoc
798     {
799         Vector JavaDoc tableList = new Vector JavaDoc();
800
801         // check for eperson in item table
802
TableRowIterator tri = DatabaseManager.query(myContext,
803                 "SELECT * from item where submitter_id= ? ",
804                 getID());
805
806         if (tri.hasNext())
807         {
808             tableList.add("item");
809         }
810
811         tri.close();
812         
813         // check for eperson in workflowitem table
814
tri = DatabaseManager.query(myContext,
815                 "SELECT * from workflowitem where owner= ? ",
816                 getID());
817
818         if (tri.hasNext())
819         {
820             tableList.add("workflowitem");
821         }
822
823         tri.close();
824         
825         // check for eperson in tasklistitem table
826
tri = DatabaseManager.query(myContext,
827                 "SELECT * from tasklistitem where eperson_id= ? ",
828                 getID());
829
830         if (tri.hasNext())
831         {
832             tableList.add("tasklistitem");
833         }
834
835         tri.close();
836         
837         // the list of tables can be used to construct an error message
838
// explaining to the user why the eperson cannot be deleted.
839
return tableList;
840     }
841
842     /**
843      * return an array of all of the groups that this EPerson is a member of
844      *
845      * @return Group []
846      * @throws SQLException
847      */

848     public Group[] getGroupMemberships() throws SQLException JavaDoc
849     {
850         // special groups
851
Group[] specialGroups = myContext.getSpecialGroups();
852
853         List JavaDoc groupList = new ArrayList JavaDoc();
854
855         for (int i = 0; i < specialGroups.length; i++)
856         {
857             groupList.add(specialGroups[i]);
858         }
859
860         // primary group IDs - returned as a set of Integers
861
Group[] myGroups = Group.allMemberGroups(myContext, this);
862
863         for (int i = 0; i < myGroups.length; i++)
864         {
865             groupList.add(myGroups[i]);
866         }
867
868         return (Group[]) groupList.toArray(new Group[0]);
869     }
870 }
871
Popular Tags