KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ivata > groupware > business > addressbook > AddressBookImpl


1 /*
2  * Copyright (c) 2001 - 2005 ivata limited.
3  * All rights reserved.
4  * -----------------------------------------------------------------------------
5  * ivata groupware may be redistributed under the GNU General Public
6  * License as published by the Free Software Foundation;
7  * version 2 of the License.
8  *
9  * These programs are free software; you can redistribute them and/or
10  * modify them under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; version 2 of the License.
12  *
13  * These programs are distributed in the hope that they will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16  *
17  * See the GNU General Public License in the file LICENSE.txt for more
18  * details.
19  *
20  * If you would like a copy of the GNU General Public License write to
21  *
22  * Free Software Foundation, Inc.
23  * 59 Temple Place - Suite 330
24  * Boston, MA 02111-1307, USA.
25  *
26  *
27  * To arrange commercial support and licensing, contact ivata at
28  * http://www.ivata.com/contact.jsp
29  * -----------------------------------------------------------------------------
30  * $Log: AddressBookImpl.java,v $
31  * Revision 1.5 2005/04/29 02:48:14 colinmacleod
32  * Data bugfixes.
33  * Changed primary key back to Integer.
34  *
35  * Revision 1.4 2005/04/28 18:47:10 colinmacleod
36  * Fixed XHMTL, styles and resin compatibility.
37  * Added support for URL rewriting.
38  *
39  * Revision 1.3 2005/04/10 20:09:34 colinmacleod
40  * Added new themes.
41  * Changed id type to String.
42  * Changed i tag to em and b tag to strong.
43  * Improved PicoContainerFactory with NanoContainer scripts.
44  *
45  * Revision 1.2 2005/04/09 17:19:06 colinmacleod
46  * Changed copyright text to GPL v2 explicitly.
47  *
48  * Revision 1.1.1.1 2005/03/10 17:50:18 colinmacleod
49  * Restructured ivata op around Hibernate/PicoContainer.
50  * Renamed ivata groupware.
51  *
52  * Revision 1.7 2004/11/12 18:17:10 colinmacleod
53  * Ordered imports.
54  *
55  * Revision 1.6 2004/11/12 15:56:47 colinmacleod
56  * Removed dependencies on SSLEXT.
57  * Moved Persistence classes to ivata masks.
58  *
59  * Revision 1.5 2004/11/03 15:36:48 colinmacleod
60  * Changed relationship between person and address:
61  * each person for now has exactly one address.
62  *
63  * Revision 1.4 2004/07/18 22:30:25 colinmacleod
64  * Synchronized lists and collections.
65  *
66  * Revision 1.3 2004/07/18 21:59:13 colinmacleod
67  * Removed Person from User - now you need to use addressbook/persistence
68  * manager to find the person (makes the app run faster.)
69  *
70  * Revision 1.2 2004/07/13 19:41:13 colinmacleod
71  * Moved project to POJOs from EJBs.
72  * Applied PicoContainer to services layer (replacing session EJBs).
73  * Applied Hibernate to persistence layer (replacing entity EJBs).
74  *
75  * Revision 1.1 2004/03/26 21:34:35 colinmacleod
76  * Split off functionality into POJO.
77  * -----------------------------------------------------------------------------
78  */

79 package com.ivata.groupware.business.addressbook;
80
81 import java.util.ArrayList JavaDoc;
82 import java.util.Arrays JavaDoc;
83 import java.util.Collections JavaDoc;
84 import java.util.Iterator JavaDoc;
85 import java.util.List JavaDoc;
86 import java.util.Stack JavaDoc;
87 import java.util.Vector JavaDoc;
88
89 import javax.ejb.EJBException JavaDoc;
90
91 import com.ivata.groupware.admin.security.Security;
92 import com.ivata.groupware.admin.security.server.SecuritySession;
93 import com.ivata.groupware.admin.security.user.UserDO;
94 import com.ivata.groupware.admin.security.user.UserConstants;
95 import com.ivata.groupware.admin.setting.Settings;
96 import com.ivata.groupware.business.BusinessLogic;
97 import com.ivata.groupware.business.addressbook.address.AddressDO;
98 import com.ivata.groupware.business.addressbook.address.country.CountryDO;
99 import com.ivata.groupware.business.addressbook.person.PersonDO;
100 import com.ivata.groupware.business.addressbook.person.group.GroupConstants;
101 import com.ivata.groupware.business.addressbook.person.group.GroupDO;
102 import com.ivata.groupware.business.addressbook.person.group.right.RightConstants;
103 import com.ivata.groupware.business.addressbook.right.AddressBookRights;
104 import com.ivata.groupware.business.addressbook.telecomaddress.TelecomAddressConstants;
105 import com.ivata.groupware.business.addressbook.telecomaddress.TelecomAddressDO;
106 import com.ivata.groupware.container.persistence.QueryPersistenceManager;
107 import com.ivata.groupware.container.persistence.TimestampDOHandling;
108 import com.ivata.groupware.container.persistence.listener.RemovePersistenceListener;
109 import com.ivata.mask.Mask;
110 import com.ivata.mask.MaskFactory;
111 import com.ivata.mask.persistence.PersistenceException;
112 import com.ivata.mask.persistence.PersistenceSession;
113 import com.ivata.mask.util.StringHandling;
114 import com.ivata.mask.util.SystemException;
115 import com.ivata.mask.validation.ValidationError;
116 import com.ivata.mask.validation.ValidationErrors;
117 import com.ivata.mask.validation.ValidationException;
118 import com.ivata.mask.valueobject.ValueObject;
119
120 /**
121  * @author Colin MacLeod
122  * <a HREF='mailto:colin.macleod@ivata.com'>colin.macleod@ivata.com</a>
123  * @since Mar 22, 2004
124  * @version $Revision: 1.5 $
125  */

126 public class AddressBookImpl extends BusinessLogic implements AddressBook,
127         RemovePersistenceListener {
128
129     /**
130      * <p>This class is used to sort the countries returned.</p>
131      */

132     private class CountryComparator implements java.util.Comparator JavaDoc {
133
134         /**
135          * <p>Compare two objects (in this case, both are instances of
136          * {@link com.ivata.groupware.business.addressbook.address.country.CountryDO
137          * CountryDO}) and return which is the higher priority.</p>
138          *
139          * @param object1 first country to be compared.
140          * @param object2 second country to be compared
141          * @return a negative integer, zero, or a positive integer as the first
142          * argument is less than, equal to, or greater than the second.
143          */

144         public final int compare(final Object JavaDoc object1,
145             final Object JavaDoc object2) {
146             CountryDO country1 = (CountryDO) object1;
147             CountryDO country2 = (CountryDO) object2;
148             return new Integer JavaDoc(country1.getPriority()).compareTo(new Integer JavaDoc(country2.getPriority()));
149         }
150     }
151
152     /**
153      * <p>This class is used to sort the people returned.</p>
154      */

155     private class PersonComparator implements java.util.Comparator JavaDoc {
156
157         /**
158          * <p>Compare two objects (in this case, both are instances of
159          * {@link com.ivata.groupware.business.addressbook.person.PersonDO PersonDO}) and
160          * return which is the higher priority.</p>
161          *
162          * @param object1 First person to be compared.
163          * @param object2 Second person to be compared.
164          * @return a negative integer, zero, or a positive integer as the first
165          * argument is less than, equal to, or greater than the second.
166          */

167         public int compare(final Object JavaDoc object1,
168             final Object JavaDoc object2) {
169             PersonDO person1 = (PersonDO) object1;
170             PersonDO person2 = (PersonDO) object2;
171             String JavaDoc fileAs1 = person1.getFileAs();
172             String JavaDoc fileAs2 = person2.getFileAs();
173
174             // watch for null values. treat them as less than zero
175
if (fileAs1 == null) {
176                 return (fileAs2 == null) ? 0 : 1;
177             } else if (fileAs2 == null) {
178                 return 1;
179             } else {
180                 // add in the id in case the fileAs matches - it is no longer
181
// unique
182
fileAs1 += person1.getId();
183                 fileAs2 += person2.getId();
184                 return fileAs1.toLowerCase().compareTo(fileAs2.toLowerCase());
185             }
186         }
187     }
188     private MaskFactory maskFactory;
189
190     /**
191      * Persistence manger used to store/retrieve data objects.
192      */

193     private QueryPersistenceManager persistenceManager;
194     private AddressBookRights rights;
195     private Settings settings;
196     /**
197      * Construct a new address book.
198      *
199      * @param persistenceManager used to store objects in db.
200      */

201     public AddressBookImpl(final QueryPersistenceManager persistenceManager,
202             final MaskFactory maskFactoryParam,
203             final AddressBookRights rights,
204             final Settings settings) {
205         this.persistenceManager = persistenceManager;
206         this.maskFactory = maskFactoryParam;
207         persistenceManager.addRemoveListener(GroupDO.class, this);
208         this.rights = rights;
209         this.settings = settings;
210     }
211
212     /**
213      * @see com.ivata.groupware.business.addressbook.AddressBook#addAddressBook(String, com.ivata.groupware.business.addressbook.person.group.GroupDO)
214      */

215     public GroupDO addAddressBook(final SecuritySession securitySession,
216             final GroupDO groupDO)
217             throws SystemException {
218         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
219         try {
220             // before creating the group, check we have reasonable data
221
ValidationErrors errors = validate(securitySession, groupDO);
222             if (!errors.isEmpty()) {
223                 throw new ValidationException(errors);
224             }
225             GroupDO parent = (GroupDO) persistenceManager.findByPrimaryKey(
226                     persistenceSession,
227                     GroupDO.class, GroupConstants.ADDRESS_BOOK_PUBLIC);
228             groupDO.setParent(parent);
229
230             TimestampDOHandling.add(securitySession, groupDO);
231             persistenceManager.add(persistenceSession, groupDO);
232             return groupDO;
233         } catch (Exception JavaDoc e) {
234             persistenceSession.cancel();
235             throw new SystemException(e);
236         } finally {
237             persistenceSession.close();
238         }
239     }
240
241     /**
242      * @see com.ivata.groupware.business.addressbook.AddressBook#addGroup(String, com.ivata.groupware.business.addressbook.person.group.GroupDO)
243      */

244     public GroupDO addGroup(final SecuritySession securitySession,
245             final GroupDO groupDO)
246             throws SystemException {
247         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
248         try {
249             // before creating the group, check we have reasonable data
250
ValidationErrors errors = validate(securitySession, groupDO);
251             if (!errors.isEmpty()) {
252                 throw new ValidationException(errors);
253             }
254
255             TimestampDOHandling.add(securitySession, groupDO);
256             return (GroupDO) persistenceManager.add(persistenceSession, groupDO);
257         } catch (Exception JavaDoc e) {
258             persistenceSession.cancel();
259             throw new SystemException(e);
260         } finally {
261             persistenceSession.close();
262         }
263     }
264
265     /**
266      * @see com.ivata.groupware.business.addressbook.AddressBook#addPerson(String, com.ivata.groupware.business.addressbook.person.PersonDO)
267      */

268     public PersonDO addPerson(final SecuritySession securitySession,
269             final PersonDO person)
270             throws SystemException {
271         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
272         try {
273             // before creating the person, check we have reasonable data
274
ValidationErrors errors = validate(securitySession, person);
275             if (!errors.isEmpty()) {
276                 throw new ValidationException(errors);
277             }
278             TimestampDOHandling.add(securitySession, person);
279             if (person.getTelecomAddresses() != null) {
280                 Iterator JavaDoc telecomAddressIterator = person.getTelecomAddresses().iterator();
281                 while (telecomAddressIterator.hasNext()) {
282                     TelecomAddressDO telecomAddress = (TelecomAddressDO) telecomAddressIterator.next();
283                     // only new addressses allowed!
284
telecomAddress.setId(null);
285                     TimestampDOHandling.add(securitySession, telecomAddress);
286                 }
287             }
288             // not sure why I need to do this? should be automatic?
289
if (person.getAddress() != null) {
290                 person.getAddress().setPerson(person);
291             }
292             return (PersonDO) persistenceManager.add(persistenceSession,
293                     person);
294         } catch (Exception JavaDoc e) {
295             persistenceSession.cancel();
296             throw new SystemException(e);
297         } finally {
298             persistenceSession.close();
299         }
300     }
301
302     /**
303      * @see com.ivata.groupware.business.addressbook.AddressBook#addUserGroup(String, com.ivata.groupware.business.addressbook.person.group.GroupDO)
304      */

305     public GroupDO addUserGroup(final SecuritySession securitySession,
306             final GroupDO groupDO)
307             throws SystemException {
308         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
309         try {
310             // before creating the group, check we have reasonable data
311
ValidationErrors errors = validate(securitySession, groupDO);
312             if (!errors.isEmpty()) {
313                 throw new ValidationException(errors);
314             }
315
316             GroupDO parent = (GroupDO) persistenceManager.findByPrimaryKey(
317                     persistenceSession,
318                     GroupDO.class, GroupConstants.USER_GROUP);
319             groupDO.setParent(parent);
320
321             TimestampDOHandling.add(securitySession, groupDO);
322             return (GroupDO) persistenceManager.add(persistenceSession, groupDO);
323         } catch (Exception JavaDoc e) {
324             persistenceSession.cancel();
325             throw new SystemException(e);
326         } finally {
327             persistenceSession.close();
328         }
329     }
330
331     /**
332      * @see com.ivata.groupware.business.addressbook.AddressBook#amendGroup(String, com.ivata.groupware.business.addressbook.person.group.GroupDO)
333      */

334     public GroupDO amendGroup(final SecuritySession securitySession,
335             final GroupDO groupDO)
336             throws SystemException {
337         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
338         try {
339             // before changing the group, check we have reasonable data
340
ValidationErrors errors = validate(securitySession, groupDO);
341             if (!errors.isEmpty()) {
342                 throw new ValidationException(errors);
343             }
344
345             TimestampDOHandling.amend(securitySession, groupDO);
346             persistenceManager.amend(persistenceSession, groupDO);
347             return groupDO;
348         } catch (Exception JavaDoc e) {
349             persistenceSession.cancel();
350             throw new SystemException(e);
351         } finally {
352             persistenceSession.close();
353         }
354     }
355
356     /**
357      * @see com.ivata.groupware.business.addressbook.AddressBook#amendPerson(String, com.ivata.groupware.business.addressbook.person.PersonDO)
358      */

359     public PersonDO amendPerson(final SecuritySession securitySession,
360             final PersonDO person)
361             throws SystemException {
362         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
363         try {
364             // before creating the person, check we have reasonable data
365
ValidationErrors errors = validate(securitySession, person);
366             if (!errors.isEmpty()) {
367                 throw new ValidationException(errors);
368             }
369             TimestampDOHandling.amend(securitySession, person);
370             if (person.getTelecomAddresses() != null) {
371                 Iterator JavaDoc telecomAddressIterator = person.getTelecomAddresses().iterator();
372                 while (telecomAddressIterator.hasNext()) {
373                     TelecomAddressDO telecomAddress = (TelecomAddressDO) telecomAddressIterator.next();
374                     if (telecomAddress.getId() == null) {
375                         TimestampDOHandling.add(securitySession, telecomAddress);
376                     } else {
377                         TimestampDOHandling.amend(securitySession, telecomAddress);
378                     }
379                 }
380             }
381             // not sure why I need to do this? should be automatic, shurely?
382
if (person.getAddress() != null) {
383                 person.getAddress().setPerson(person);
384             }
385             // if the person is an employee but the country hasn't been set,
386
// remove the country object
387
if ((person.getEmployee() != null)
388                     && (person.getEmployee().getCountry() != null)
389                     && (person.getEmployee().getCountry().getId() == null)) {
390                 person.getEmployee().setCountry(null);
391             }
392             // if this person is a user, (s)he must be in the public address
393
// book
394
if ((person.getUser() != null)
395                     && !StringHandling.isNullOrEmpty(person.getUser()
396                             .getName())) {
397                 GroupDO addressBook = person.getGroup().getAddressBook();
398                 if (!GroupConstants.equals(
399                         addressBook.getId(),
400                         GroupConstants.ADDRESS_BOOK_DEFAULT)) {
401                     GroupDO defaultAddressBook = findGroupByPrimaryKey(
402                             securitySession,
403                             GroupConstants.ADDRESS_BOOK_DEFAULT);
404                     person.setGroup(defaultAddressBook);
405                 }
406             }
407             persistenceManager.amend(persistenceSession, person);
408
409             return person;
410         } catch (Exception JavaDoc e) {
411             persistenceSession.cancel();
412             throw new SystemException(e);
413         } finally {
414             persistenceSession.close();
415         }
416     }
417
418     /**
419      * @see com.ivata.groupware.business.addressbook.AddressBook#getAddressBookNames(String, Integer, boolean)
420      */

421     public List JavaDoc findAddressBooks(final SecuritySession securitySession,
422             final boolean includePersonal)
423             throws SystemException {
424         List JavaDoc addressBooks = new ArrayList JavaDoc();
425         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
426         try {
427             GroupDO addressBookParent = (GroupDO) persistenceManager
428                 .findByPrimaryKey(
429                         persistenceSession,
430                         GroupDO.class,
431                         GroupConstants.ADDRESS_BOOK_PUBLIC);
432             List JavaDoc children = persistenceManager.find(persistenceSession,
433                 "addressBookGroupsInGroup", new Object JavaDoc[]{addressBookParent.getId()});
434             addressBooks.addAll(children);
435
436             // find personal addressBook for that user
437
if (includePersonal) {
438                 GroupDO personalAddressBook = findPersonalAddressBook(securitySession);
439                 addressBooks.add(personalAddressBook);
440             }
441             return Collections.synchronizedList(addressBooks);
442         } catch (Exception JavaDoc e) {
443             persistenceSession.cancel();
444             throw new SystemException(e);
445         } finally {
446             persistenceSession.close();
447         }
448     }
449
450     /**
451      * @see com.ivata.groupware.business.addressbook.AddressBook#findAllCountries()
452      */

453     public List JavaDoc findAllCountries(final SecuritySession securitySession)
454             throws SystemException {
455         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
456         try {
457             return Collections.synchronizedList(persistenceManager.findAll(persistenceSession, CountryDO.class));
458         } catch (Exception JavaDoc e) {
459             persistenceSession.cancel();
460             throw new SystemException(e);
461         } finally {
462             persistenceSession.close();
463         }
464     }
465     /**
466      * <p>
467      * Recursive implementation to find all people in child groups.
468      * </p>
469      *
470      * @see com.ivata.groupware.business.addressbook.AddressBook#findCountryByCode(com.ivata.groupware.admin.security.server.SecuritySession, String)
471      */

472     private void findAllPeopleInGroup(final GroupDO group,
473             final String JavaDoc lowerCaseInitialLetter,
474             final List JavaDoc totalResults,
475             final Stack JavaDoc parentGroups) throws SystemException {
476         // go through the children first
477
PersistenceSession persistenceSession = persistenceManager.openSession();
478         parentGroups.push(group);
479
480         Mask groupMask = maskFactory.getMask(GroupDO.class);
481         try {
482             List JavaDoc children = persistenceManager.find(persistenceSession,
483                 "addressBookGroupsInGroup", new Object JavaDoc[]{group.getId()});
484             Iterator JavaDoc childIterator = children.iterator();
485             while(childIterator.hasNext()) {
486                 GroupDO child = (GroupDO) childIterator.next();
487                 if (parentGroups.contains(child)) {
488                     throw new ValidationException(
489                             new ValidationError(
490                                     "errors.addressbook.group.parent",
491                                     Arrays.asList(new Object JavaDoc[] {
492                                             group,
493                                             child
494                                     }))
495                             );
496                 }
497                 findAllPeopleInGroup(child, lowerCaseInitialLetter, totalResults,
498                         parentGroups);
499             }
500         } catch (Exception JavaDoc e) {
501             persistenceSession.cancel();
502             throw new SystemException(e);
503         } finally {
504             parentGroups.pop();
505             persistenceSession.close();
506         }
507
508         // iterate through all the people
509
// in this group and only add those which match the first letter
510
Iterator JavaDoc personIterator = group.getPeople().iterator();
511         while(personIterator.hasNext()) {
512             PersonDO person = (PersonDO) personIterator.next();
513             String JavaDoc fileAs = person.getFileAs();
514             if (StringHandling.isNullOrEmpty(fileAs)) {
515                 continue;
516             }
517             if ((lowerCaseInitialLetter != null)
518                             && !lowerCaseInitialLetter
519                                 .equals(fileAs.substring(0, 1).toLowerCase())) {
520                 continue;
521             }
522             totalResults.add(person);
523         }
524     }
525
526     /**
527      * <p>Find All People in a specific address book group.</p
528      *
529      * @see com.ivata.groupware.business.addressbook.AddressBook#findAllPeople(com.ivata.groupware.admin.security.server.SecuritySession, Integer, Integer, String)
530      */

531     public List JavaDoc findAllPeopleInGroup(final SecuritySession securitySession,
532             final GroupDO group,
533             final String JavaDoc initialLetterParam) throws SystemException {
534         boolean demoVersion = settings.getBooleanSetting(securitySession,
535                 "demoVersion", null).booleanValue();
536         List JavaDoc results = new Vector JavaDoc();
537         String JavaDoc initialLetterLowerCase = initialLetterParam;
538         if (initialLetterLowerCase != null) {
539             initialLetterLowerCase = initialLetterLowerCase.toLowerCase();
540         }
541         findAllPeopleInGroup(group, initialLetterLowerCase, results,
542                 new Stack JavaDoc());
543
544         // this filters out all the people which are in private address
545
// books - this should be removed when real user rights are used again
546
// this filtering stage also removes logically deleted people - that
547
// can probably stay in (depending on how the rights are implemented)
548
List JavaDoc filteredResults = new Vector JavaDoc();
549         Iterator JavaDoc peopleIterator = results.iterator();
550         while (peopleIterator.hasNext()) {
551             PersonDO person = (PersonDO) peopleIterator.next();
552             // don't show the administator in the demo
553
// TODO: this should really be handled via user rights
554
if (demoVersion && UserConstants
555                     .ADMINISTRATOR.equals(person.getId())) {
556                 continue;
557             }
558             if (person.isDeleted()) {
559                 continue;
560             }
561             if (!rights.canUser(securitySession, person.getGroup(),
562                                     RightConstants.ACCESS_VIEW)) {
563                 continue;
564             }
565             filteredResults.add(person);
566         }
567
568         return Collections.synchronizedList(filteredResults);
569     }
570
571     /**
572      * @see com.ivata.groupware.business.addressbook.AddressBook#findCountryByCode(String)
573      */

574     public CountryDO findCountryByCode(final SecuritySession securitySession,
575             final String JavaDoc countryCode)
576             throws SystemException {
577         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
578         try {
579             return (CountryDO) persistenceManager.findInstance(persistenceSession,
580                 "addressBookCountryByCode", new Object JavaDoc[] {countryCode});
581         } catch (Exception JavaDoc e) {
582             persistenceSession.cancel();
583             throw new SystemException(e);
584         } finally {
585             persistenceSession.close();
586         }
587     }
588
589     /**
590      * @see com.ivata.groupware.business.addressbook.AddressBook#findGroupByPrimaryKey(Integer)
591      */

592     public GroupDO findGroupByPrimaryKey(final SecuritySession securitySession,
593             final Integer JavaDoc id)
594             throws SystemException {
595         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
596         try {
597             return (GroupDO) persistenceManager.findByPrimaryKey(persistenceSession,
598                 GroupDO.class, id);
599         } catch (Exception JavaDoc e) {
600             persistenceSession.cancel();
601             throw new SystemException(e);
602         } finally {
603             persistenceSession.close();
604         }
605     }
606
607     /**
608      * <p>
609      * Find all groups which are siblings, identified by the parent group.
610      * </p>
611      * @see com.ivata.groupware.business.addressbook.AddressBook#findGroupByPrimaryKey(Integer)
612      */

613     public List JavaDoc findGroupsByParent(final SecuritySession securitySession,
614             final Integer JavaDoc parentId)
615             throws SystemException {
616         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
617         try {
618             return Collections.synchronizedList(persistenceManager.find(persistenceSession,
619                 "addressBookGroupsInGroup", new Object JavaDoc[]{parentId}));
620         } catch (Exception JavaDoc e) {
621             persistenceSession.cancel();
622             throw new SystemException(e);
623         } finally {
624             persistenceSession.close();
625         }
626     }
627
628     /**
629      * @see com.ivata.groupware.business.addressbook.AddressBook#findPersonalAddressBook(String)
630      */

631     public GroupDO findPersonalAddressBook(final SecuritySession securitySession)
632             throws SystemException {
633         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
634         try {
635             return (GroupDO) persistenceManager.findInstance(persistenceSession,
636                 "addressBookGroupsInGroupByName",
637                 new Object JavaDoc[] {GroupConstants.ADDRESS_BOOK_PRIVATE,
638                     securitySession.getUser().getName()});
639         } catch (Exception JavaDoc e) {
640             persistenceSession.cancel();
641             throw new SystemException(e);
642         } finally {
643             persistenceSession.close();
644         }
645     }
646
647     /**
648      * @see com.ivata.groupware.business.addressbook.AddressBook#findPersonByPrimaryKey(Integer)
649      */

650     public PersonDO findPersonByPrimaryKey(final SecuritySession securitySession,
651             final String JavaDoc id)
652             throws SystemException {
653         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
654         try {
655             return (PersonDO) persistenceManager.findByPrimaryKey(persistenceSession,
656                 PersonDO.class, id);
657         } catch (Exception JavaDoc e) {
658             persistenceSession.cancel();
659             throw new SystemException(e);
660         } finally {
661             persistenceSession.close();
662         }
663     }
664
665     /**
666      * <p>Find a person in the address book by their user name.</p>
667      *
668      * @param userName Name of the user to find.
669      * @return the person data object which matches this user name.
670      * @see com.ivata.groupware.business.addressbook.AddressBook#findPersonByUserName(com.ivata.groupware.admin.security.server.SecuritySession, String)
671      */

672     public PersonDO findPersonByUserName(final SecuritySession securitySession,
673             final String JavaDoc userName) throws SystemException {
674         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
675         try {
676             return (PersonDO) persistenceManager.findInstance(persistenceSession,
677                 "addressBookPersonByUserName", new Object JavaDoc [] {userName});
678         } catch (Exception JavaDoc e) {
679             persistenceSession.cancel();
680             throw new SystemException(e);
681         } finally {
682             persistenceSession.close();
683         }
684     }
685
686     /**
687      * @see com.ivata.groupware.business.addressbook.AddressBook#getUserGroupNames(String, Integer, boolean)
688      */

689     public List JavaDoc findUserGroups(final SecuritySession securitySession,
690             final boolean includeAdministrator)
691             throws SystemException {
692         List JavaDoc userGroups = new ArrayList JavaDoc();
693         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
694         try {
695             GroupDO userGroupParent = (GroupDO)
696                 persistenceManager.findByPrimaryKey(
697                         persistenceSession,
698                         GroupDO.class,
699                         GroupConstants.USER_GROUP);
700             List JavaDoc children = persistenceManager.find(persistenceSession,
701                 "addressBookGroupsInGroup", new Object JavaDoc[]{userGroupParent.getId()});
702             userGroups.addAll(children);
703
704             // if we should not include the administrator group, then excluded
705
if (!includeAdministrator) {
706                 Iterator JavaDoc iterator = userGroups.iterator();
707                 while(iterator.hasNext()) {
708                     GroupDO userGroup = (GroupDO) iterator.next();
709                     if (GroupConstants.equals(userGroup.getId(),
710                             GroupConstants.GROUP_ADMINISTRATOR)) {
711                         userGroups.remove(userGroup);
712                         break;
713                     }
714                 }
715             }
716             // add "everyone" GROUP to the list
717
userGroups.add(userGroupParent);
718             return Collections.synchronizedList(userGroups);
719         } catch (Exception JavaDoc e) {
720             persistenceSession.cancel();
721             throw new SystemException(e);
722         } finally {
723             persistenceSession.close();
724         }
725     }
726
727     /**
728      * Refer to {@link RemovePersistenceListener#onRemove}.
729      *
730      * @param session Refer to {@link RemovePersistenceListener#onRemove}.
731      * @param valueObject Refer to {@link RemovePersistenceListener#onRemove}.
732      * @throws PersistenceException
733      * Refer to {@link RemovePersistenceListener#onRemove}.
734      */

735     public void onRemove(final PersistenceSession persistenceSession,
736             final ValueObject valueObject) throws PersistenceException {
737         // only interested in deleting groups - at least for now!
738
if (!(valueObject instanceof GroupDO)) {
739             return;
740         }
741         GroupDO groupDO = (GroupDO) valueObject;
742
743         // relocate everything in this group to the parent
744
GroupDO parent = groupDO.getParent();
745
746         List JavaDoc children = persistenceManager.find(persistenceSession,
747             "addressBookGroupsInGroup", new Object JavaDoc[]{groupDO.getId()});
748
749         // if this is an addressbook group, see if the group has any members
750
if (GroupConstants.equals(groupDO.getParent().getId(),
751                     GroupConstants.ADDRESS_BOOK_PRIVATE)
752                 || GroupConstants.equals(groupDO.getParent().getId(),
753                         GroupConstants.ADDRESS_BOOK_PRIVATE)) {
754             assert (children.size() > 0);
755             assert (groupDO.getPeople().size() == 0);
756         }
757         // move all people and subgroups up a level
758
Iterator JavaDoc childIterator = children.iterator();
759         while (childIterator.hasNext()) {
760             GroupDO child = (GroupDO) childIterator.next();
761             child.setParent(parent);
762             persistenceManager.amend(persistenceSession, child);
763         }
764         Iterator JavaDoc personIterator = groupDO.getPeople().iterator();
765         while (personIterator.hasNext()) {
766             PersonDO person = (PersonDO) personIterator.next();
767             person.setGroup(parent);
768             persistenceManager.amend(persistenceSession, person);
769         }
770     }
771
772     /**
773      * @see com.ivata.groupware.business.addressbook.AddressBook#removeGroup(String, Integer)
774      */

775     public void removeGroup(final SecuritySession securitySession,
776             final Integer JavaDoc id)
777             throws SystemException {
778         // check we have an addressBookID and Id of group
779
assert (id != null);
780         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
781         try {
782             persistenceManager.remove(persistenceSession, GroupDO.class, id);
783         } catch (Exception JavaDoc e) {
784             persistenceSession.cancel();
785             throw new SystemException(e);
786         } finally {
787             persistenceSession.close();
788         }
789     }
790
791     /**
792      * @see com.ivata.groupware.business.addressbook.AddressBook#removePerson(String, Integer)
793      */

794     public void removePerson(final SecuritySession securitySession,
795             final Integer JavaDoc id)
796             throws SystemException {
797         // check we have an id
798
if (id == null) {
799             throw new EJBException JavaDoc("ERROR in AddressBookBean: cannot remove a person with a null id");
800         }
801         PersistenceSession persistenceSession =
802             persistenceManager.openSession(securitySession);
803         PersonDO person;
804         try {
805             person = (PersonDO)persistenceManager.findByPrimaryKey(
806                     persistenceSession, PersonDO.class, id);
807         } finally {
808             persistenceSession.close();
809         }
810         persistenceSession = persistenceManager.openSession(securitySession);
811         try {
812             // if this person has a user, only logically remove
813
if (person.getUser() == null) {
814                 persistenceManager.remove(persistenceSession, person);
815             } else {
816                 person.setDeleted(true);
817                 person.getUser().setDeleted(true);
818                 persistenceManager.amend(persistenceSession, person);
819             }
820         } catch (Exception JavaDoc e) {
821             persistenceSession.cancel();
822             throw new SystemException(e);
823         } finally {
824             persistenceSession.close();
825         }
826     }
827
828     /**
829      * Check the address data object is complete and represents a valid address.
830      *
831      * @param addressDO address to check.
832      * @return all errors found when validating this data object. If no errors
833      * are found, the returned instance is empty.
834      */

835     public ValidationErrors validate(final SecuritySession securitySession,
836             final AddressDO addressDO) {
837         ValidationErrors errors = new ValidationErrors();
838         Mask mask = maskFactory.getMask(AddressDO.class);
839
840         if ((addressDO.getCountry() == null)
841                 || StringHandling.isNullOrEmpty(addressDO.getCountry().getCode())) {
842             errors.add(new ValidationError(
843                     "person.address",
844                     AddressBook.BUNDLE_PATH,
845                     mask.getField("country"),
846                     "errors.required"));
847         }
848         if (StringHandling.isNullOrEmpty(addressDO.getStreetAddress())) {
849             errors.add(new ValidationError(
850                     "person.address",
851                     AddressBook.BUNDLE_PATH,
852                     mask.getField("streetAddress"),
853                     "errors.required"));
854         }
855         if (StringHandling.isNullOrEmpty(addressDO.getTown())) {
856             errors.add(new ValidationError(
857                     "person.address",
858                     AddressBook.BUNDLE_PATH,
859                     mask.getField("town"),
860                     "errors.required"));
861         }
862         return errors;
863     }
864
865     /**
866      * @see com.ivata.groupware.business.addressbook.AddressBook#validate(com.ivata.groupware.business.addressbook.person.group.GroupDO)
867      */

868     public ValidationErrors validate(final SecuritySession securitySession,
869             final GroupDO groupDO) {
870         ValidationErrors errors = new ValidationErrors();
871         Mask mask = maskFactory.getMask(GroupDO.class);
872
873         // name is mandatory
874
if (StringHandling.isNullOrEmpty(groupDO.getName())) {
875             errors.add(new ValidationError(
876                     "group",
877                     AddressBook.BUNDLE_PATH,
878                     mask.getField("name"),
879                     "errors.required"));
880         }
881         return errors;
882     }
883
884     /**
885      * Check the person data object is complete and represents a valid person.
886      *
887      * @param personDO person to check.
888      * @return all errors found when validating this data object. If no errors
889      * are found, the returned instance is empty.
890      */

891     public ValidationErrors validate(final SecuritySession securitySession,
892             final PersonDO personDO) {
893         ValidationErrors errors = new ValidationErrors();
894         Mask mask = maskFactory.getMask(PersonDO.class);
895         Mask userMask = maskFactory.getMask(UserDO.class);
896
897         if (StringHandling.isNullOrEmpty(personDO.getFileAs())) {
898             errors.add(new ValidationError(
899                     "personDetails",
900                     AddressBook.BUNDLE_PATH,
901                     mask.getField("fileAs"),
902                     "errors.required"));
903         }
904         if (StringHandling.isNullOrEmpty(personDO.getFirstNames())) {
905             errors.add(new ValidationError(
906                     "personDetails",
907                     AddressBook.BUNDLE_PATH,
908                     mask.getField("firstNames"),
909                     "errors.required"));
910         }
911         if (StringHandling.isNullOrEmpty(personDO.getLastName())) {
912             errors.add(new ValidationError(
913                     "personDetails",
914                     AddressBook.BUNDLE_PATH,
915                     mask.getField("lastName"),
916                     "errors.required"));
917
918         // contact has to belong to some group not root node of group tree !!!!
919
}
920         if (personDO.getGroup() == null) {
921             errors.add(new ValidationError(
922                     "personDetails",
923                     AddressBook.BUNDLE_PATH,
924                     mask.getField("addressBookName"),
925                     "errors.required"));
926         }
927         // if this is the default administrator, you can't stop that person
928
// being a user
929
if (UserConstants.ADMINISTRATOR.equals(personDO.getId())) {
930             if ((personDO.getUser() == null)
931                     || !personDO.getUser().isEnabled()
932                     || personDO.getUser().isDeleted()) {
933                 errors.add(new ValidationError(
934                         "user",
935                         Security.BUNDLE_PATH,
936                         userMask.getField("name"),
937                         "errors.addressBook.user.administrator"));
938
939             }
940         }
941
942
943         if (personDO.getUser() != null) {
944             if (personDO.getUser().getName() == null) {
945                 errors.add(new ValidationError(
946                         "user",
947                         Security.BUNDLE_PATH,
948                         userMask.getField("name"),
949                         "errors.required"));
950             }
951
952             // every user _must_ have at least one email address
953
// go thro' all the telecom addresses and look for an email address
954
boolean foundEmail = false;
955
956             for (Iterator JavaDoc i = personDO.getTelecomAddresses().iterator(); i.hasNext();) {
957                 int type = ((TelecomAddressDO) i.next()).getType();
958                 if (type == TelecomAddressConstants.TYPE_EMAIL) {
959                     foundEmail = true;
960                     break;
961                 }
962             }
963             if (!foundEmail) {
964                 errors.add(new ValidationError(
965                         "personDetails",
966                         AddressBook.BUNDLE_PATH,
967                         mask.getField("emailAddress"),
968                         "errors.required"));
969             }
970         }
971         // if any the mandatory address fields are there, see if they all are
972
if (personDO.getAddress() != null) {
973             ValidationErrors addressErrors = validate(securitySession,
974                     personDO.getAddress());
975             if (addressErrors != null) {
976                 errors.addAll(addressErrors);
977             }
978         }
979
980         return errors;
981     }
982 }
983
Popular Tags