1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   * 
13   */
14  
15  package com.liferay.portal.service.impl;
16  
17  import com.liferay.portal.DuplicateOrganizationException;
18  import com.liferay.portal.OrganizationNameException;
19  import com.liferay.portal.OrganizationParentException;
20  import com.liferay.portal.PortalException;
21  import com.liferay.portal.RequiredOrganizationException;
22  import com.liferay.portal.SystemException;
23  import com.liferay.portal.kernel.dao.orm.QueryUtil;
24  import com.liferay.portal.kernel.util.OrderByComparator;
25  import com.liferay.portal.kernel.util.StringPool;
26  import com.liferay.portal.kernel.util.Validator;
27  import com.liferay.portal.model.Group;
28  import com.liferay.portal.model.Location;
29  import com.liferay.portal.model.Organization;
30  import com.liferay.portal.model.OrganizationConstants;
31  import com.liferay.portal.model.ResourceConstants;
32  import com.liferay.portal.model.Role;
33  import com.liferay.portal.model.RoleConstants;
34  import com.liferay.portal.model.User;
35  import com.liferay.portal.model.impl.ListTypeImpl;
36  import com.liferay.portal.security.permission.PermissionCacheUtil;
37  import com.liferay.portal.service.base.OrganizationLocalServiceBaseImpl;
38  import com.liferay.portal.util.PropsValues;
39  import com.liferay.portal.util.comparator.OrganizationNameComparator;
40  
41  import java.rmi.RemoteException;
42  
43  import java.util.ArrayList;
44  import java.util.Iterator;
45  import java.util.LinkedHashMap;
46  import java.util.List;
47  
48  /**
49   * <a href="OrganizationLocalServiceImpl.java.html"><b><i>View Source</i></b>
50   * </a>
51   *
52   * @author Brian Wing Shun Chan
53   * @author Jorge Ferrer
54   */
55  public class OrganizationLocalServiceImpl
56      extends OrganizationLocalServiceBaseImpl {
57  
58      public void addGroupOrganizations(long groupId, long[] organizationIds)
59          throws SystemException {
60  
61          groupPersistence.addOrganizations(groupId, organizationIds);
62  
63          PermissionCacheUtil.clearCache();
64      }
65  
66      public Organization addOrganization(
67              long userId, long parentOrganizationId, String name,
68              int type, boolean recursable, long regionId, long countryId,
69              int statusId, String comments)
70          throws PortalException, SystemException {
71  
72          // Organization
73  
74          User user = userPersistence.findByPrimaryKey(userId);
75          parentOrganizationId = getParentOrganizationId(
76              user.getCompanyId(), parentOrganizationId);
77          recursable = true;
78  
79          validate(
80              user.getCompanyId(), parentOrganizationId, name, type, countryId,
81              statusId);
82  
83          long organizationId = counterLocalService.increment();
84  
85          Organization organization = organizationPersistence.create(
86              organizationId);
87  
88          organization.setCompanyId(user.getCompanyId());
89          organization.setParentOrganizationId(parentOrganizationId);
90          organization.setName(name);
91  
92          if (type == OrganizationConstants.TYPE_LOCATION) {
93              organization.setLocation(true);
94          }
95          else {
96              organization.setLocation(false);
97          }
98  
99          organization.setRecursable(recursable);
100         organization.setRegionId(regionId);
101         organization.setCountryId(countryId);
102         organization.setStatusId(statusId);
103         organization.setComments(comments);
104 
105         organizationPersistence.update(organization, false);
106 
107         // Group
108 
109         Group group = groupLocalService.addGroup(
110             userId, Organization.class.getName(), organizationId, null, null, 0,
111             null, true);
112 
113         // Role
114 
115         Role role = roleLocalService.getRole(
116             organization.getCompanyId(), RoleConstants.ORGANIZATION_OWNER);
117 
118         userGroupRoleLocalService.addUserGroupRoles(
119             userId, group.getGroupId(), new long[] {role.getRoleId()});
120 
121         // User
122 
123         userPersistence.addOrganization(userId, organizationId);
124 
125         // Resources
126 
127         addOrganizationResources(userId, organization);
128 
129         return organization;
130     }
131 
132     public void addOrganizationResources(long userId, Organization organization)
133         throws PortalException, SystemException {
134 
135         String name = Organization.class.getName();
136 
137         if (organization.isLocation()) {
138             name = Location.class.getName();
139         }
140 
141         resourceLocalService.addResources(
142             organization.getCompanyId(), 0, userId, name,
143             organization.getOrganizationId(), false, false, false);
144     }
145 
146     public void addPasswordPolicyOrganizations(
147             long passwordPolicyId, long[] organizationIds)
148         throws SystemException {
149 
150         passwordPolicyRelLocalService.addPasswordPolicyRels(
151             passwordPolicyId, Organization.class.getName(), organizationIds);
152     }
153 
154     public void deleteOrganization(long organizationId)
155         throws PortalException, SystemException {
156 
157         Organization organization = organizationPersistence.findByPrimaryKey(
158             organizationId);
159 
160         if ((userLocalService.getOrganizationUsersCount(
161                 organization.getOrganizationId(), true) > 0) ||
162             (organizationPersistence.countByC_P(
163                 organization.getCompanyId(),
164                 organization.getOrganizationId()) > 0)) {
165 
166             throw new RequiredOrganizationException();
167         }
168 
169         // Addresses
170 
171         addressLocalService.deleteAddresses(
172             organization.getCompanyId(), Organization.class.getName(),
173             organization.getOrganizationId());
174 
175         // Email addresses
176 
177         emailAddressLocalService.deleteEmailAddresses(
178             organization.getCompanyId(), Organization.class.getName(),
179             organization.getOrganizationId());
180 
181         // Password policy relation
182 
183         passwordPolicyRelLocalService.deletePasswordPolicyRel(
184             Organization.class.getName(), organization.getOrganizationId());
185 
186         // Phone
187 
188         phoneLocalService.deletePhones(
189             organization.getCompanyId(), Organization.class.getName(),
190             organization.getOrganizationId());
191 
192         // Website
193 
194         websiteLocalService.deleteWebsites(
195             organization.getCompanyId(), Organization.class.getName(),
196             organization.getOrganizationId());
197 
198         // Group
199 
200         Group group = organization.getGroup();
201 
202         groupLocalService.deleteGroup(group.getGroupId());
203 
204         // Resources
205 
206         String name = Organization.class.getName();
207 
208         if (organization.isLocation()) {
209             name = Location.class.getName();
210         }
211 
212         resourceLocalService.deleteResource(
213             organization.getCompanyId(), name,
214             ResourceConstants.SCOPE_INDIVIDUAL,
215             organization.getOrganizationId());
216 
217         // Organization
218 
219         organizationPersistence.remove(organization);
220 
221         // Permission cache
222 
223         PermissionCacheUtil.clearCache();
224     }
225 
226     public List<Organization> getGroupOrganizations(long groupId)
227         throws SystemException {
228 
229         return groupPersistence.getOrganizations(groupId);
230     }
231 
232     public Organization getOrganization(long organizationId)
233         throws PortalException, SystemException {
234 
235         return organizationPersistence.findByPrimaryKey(organizationId);
236     }
237 
238     public Organization getOrganization(long companyId, String name)
239         throws PortalException, SystemException {
240 
241         return organizationPersistence.findByC_N(companyId, name);
242     }
243 
244     public long getOrganizationId(long companyId, String name)
245         throws SystemException {
246 
247         Organization organization = organizationPersistence.fetchByC_N(
248             companyId, name);
249 
250         if (organization != null) {
251             return organization.getOrganizationId();
252         }
253         else {
254             return 0;
255         }
256     }
257 
258     public List<Organization> getOrganizations(long[] organizationIds)
259         throws PortalException, SystemException {
260 
261         List<Organization> organizations = new ArrayList<Organization>();
262 
263         for (int i = 0; i < organizationIds.length; i++) {
264             Organization organization = getOrganization(organizationIds[i]);
265 
266             organizations.add(organization);
267         }
268 
269         return organizations;
270     }
271 
272     public List<Organization> getParentOrganizations(long organizationId)
273         throws PortalException, SystemException {
274 
275         if (organizationId ==
276                 OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID) {
277 
278             return new ArrayList<Organization>();
279         }
280 
281         Organization organization =
282             organizationPersistence.findByPrimaryKey(organizationId);
283 
284         return getParentOrganizations(organization, true);
285     }
286 
287     public List<Organization> getSuborganizations(
288             List<Organization> organizations)
289         throws SystemException {
290 
291         List<Organization> allSuborganizations = new ArrayList<Organization>();
292 
293         for (int i = 0; i < organizations.size(); i++) {
294             Organization organization = organizations.get(i);
295 
296             List<Organization> suborganizations =
297                 organizationPersistence.findByC_P(
298                     organization.getCompanyId(),
299                     organization.getOrganizationId());
300 
301             addSuborganizations(allSuborganizations, suborganizations);
302         }
303 
304         return allSuborganizations;
305     }
306 
307     public List<Organization> getSubsetOrganizations(
308         List<Organization> allOrganizations,
309         List<Organization> availableOrganizations) {
310 
311         List<Organization> subsetOrganizations = new ArrayList<Organization>();
312 
313         Iterator<Organization> itr = allOrganizations.iterator();
314 
315         while (itr.hasNext()) {
316             Organization organization = itr.next();
317 
318             if (availableOrganizations.contains(organization)) {
319                 subsetOrganizations.add(organization);
320             }
321         }
322 
323         return subsetOrganizations;
324     }
325 
326     public List<Organization> getUserOrganizations(long userId)
327         throws PortalException, SystemException {
328 
329         return getUserOrganizations(userId, false);
330     }
331 
332     public List<Organization> getUserOrganizations(
333             long userId, boolean inheritUserGroups)
334         throws PortalException, SystemException {
335 
336         return getUserOrganizations(
337             userId, inheritUserGroups, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
338     }
339 
340     public List<Organization> getUserOrganizations(
341             long userId, int start, int end)
342         throws PortalException, SystemException {
343 
344         return getUserOrganizations(userId, false, start, end);
345     }
346 
347     public List<Organization> getUserOrganizations(
348             long userId, boolean inheritUserGroups, int start, int end)
349         throws PortalException, SystemException {
350 
351         if (inheritUserGroups &&
352             PropsValues.ORGANIZATIONS_USER_GROUP_MEMBERSHIP_ENABLED) {
353 
354             User user = userPersistence.findByPrimaryKey(userId);
355 
356             LinkedHashMap<String, Object> organizationParams =
357                 new LinkedHashMap<String, Object>();
358 
359             organizationParams.put("usersOrgs", new Long(userId));
360 
361             return search(
362                 user.getCompanyId(),
363                 OrganizationConstants.ANY_PARENT_ORGANIZATION_ID, null,
364                 OrganizationConstants.ANY_TYPE, null, null, organizationParams,
365                 start, end);
366         }
367         else {
368             return userPersistence.getOrganizations(userId, start, end);
369         }
370     }
371 
372     public int getUserOrganizationsCount(long userId) throws SystemException {
373         return userPersistence.getOrganizationsSize(userId);
374     }
375 
376     public boolean hasGroupOrganization(long groupId, long organizationId)
377         throws SystemException {
378 
379         return groupPersistence.containsOrganization(groupId, organizationId);
380     }
381 
382     public boolean hasUserOrganization(long userId, long organizationId)
383         throws SystemException {
384 
385         return userPersistence.containsOrganization(userId, organizationId);
386     }
387 
388     public boolean hasUserOrganization(
389             long userId, long organizationId, boolean inheritUserGroups)
390         throws PortalException, SystemException {
391 
392         if (inheritUserGroups) {
393             if (organizationFinder.countByO_U(organizationId, userId) > 0) {
394                 return true;
395             }
396             else {
397                 return false;
398             }
399         }
400         else {
401             return userPersistence.containsOrganization(userId, organizationId);
402         }
403     }
404 
405     public boolean hasPasswordPolicyOrganization(
406             long passwordPolicyId, long organizationId)
407         throws SystemException {
408 
409         return passwordPolicyRelLocalService.hasPasswordPolicyRel(
410             passwordPolicyId, Organization.class.getName(), organizationId);
411     }
412 
413     public void rebuildTree(long companyId, boolean force)
414         throws SystemException {
415 
416         organizationPersistence.rebuildTree(companyId, force);
417     }
418 
419     public List<Organization> search(
420             long companyId, long parentOrganizationId, String keywords,
421             int type, Long regionId, Long countryId,
422             LinkedHashMap<String, Object> params,
423             int start, int end)
424         throws SystemException {
425 
426         return search(
427             companyId, parentOrganizationId, keywords, type, regionId,
428             countryId, params, start, end,
429             new OrganizationNameComparator(true));
430     }
431 
432     public List<Organization> search(
433             long companyId, long parentOrganizationId, String keywords,
434             int type, Long regionId, Long countryId,
435             LinkedHashMap<String, Object> params,
436             int start, int end, OrderByComparator obc)
437         throws SystemException {
438 
439         String parentOrganizationIdComparator = StringPool.EQUAL;
440 
441         if (parentOrganizationId ==
442                 OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
443 
444             parentOrganizationIdComparator = StringPool.NOT_EQUAL;
445         }
446 
447         return organizationFinder.findByKeywords(
448             companyId, parentOrganizationId, parentOrganizationIdComparator,
449             keywords, type, regionId, countryId, params, start, end,
450             obc);
451     }
452 
453     public List<Organization> search(
454             long companyId, long parentOrganizationId, String name, int type,
455             String street, String city, String zip,
456             Long regionId, Long countryId,
457             LinkedHashMap<String, Object> params, boolean andOperator,
458             int start, int end)
459         throws SystemException {
460 
461         return search(
462             companyId, parentOrganizationId, name, type, street, city, zip,
463             regionId, countryId, params, andOperator, start, end,
464             new OrganizationNameComparator(true));
465     }
466 
467     public List<Organization> search(
468             long companyId, long parentOrganizationId, String name, int type,
469             String street, String city, String zip,
470             Long regionId, Long countryId, LinkedHashMap<String, Object> params,
471             boolean andOperator, int start, int end, OrderByComparator obc)
472         throws SystemException {
473 
474         String parentOrganizationIdComparator = StringPool.EQUAL;
475 
476         if (parentOrganizationId ==
477                 OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
478 
479             parentOrganizationIdComparator = StringPool.NOT_EQUAL;
480         }
481 
482         return organizationFinder.findByC_PO_N_T_S_C_Z_R_C(
483             companyId, parentOrganizationId, parentOrganizationIdComparator,
484             name, type, street, city, zip, regionId, countryId, params,
485             andOperator, start, end, obc);
486     }
487 
488     public int searchCount(
489             long companyId, long parentOrganizationId, String keywords,
490             int type, Long regionId, Long countryId,
491             LinkedHashMap<String, Object> params)
492         throws SystemException {
493 
494         String parentOrganizationIdComparator = StringPool.EQUAL;
495 
496         if (parentOrganizationId ==
497                 OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
498 
499             parentOrganizationIdComparator = StringPool.NOT_EQUAL;
500         }
501 
502         return organizationFinder.countByKeywords(
503             companyId, parentOrganizationId, parentOrganizationIdComparator,
504             keywords, type, regionId, countryId, params);
505     }
506 
507     public int searchCount(
508             long companyId, long parentOrganizationId, String name, int type,
509             String street, String city, String zip,
510             Long regionId, Long countryId, LinkedHashMap<String, Object> params,
511             boolean andOperator)
512         throws SystemException {
513 
514         String parentOrganizationIdComparator = StringPool.EQUAL;
515 
516         if (parentOrganizationId ==
517                 OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
518 
519             parentOrganizationIdComparator = StringPool.NOT_EQUAL;
520         }
521 
522         return organizationFinder.countByC_PO_N_T_S_C_Z_R_C(
523             companyId, parentOrganizationId, parentOrganizationIdComparator,
524             name, type, street, city, zip, regionId, countryId, params,
525             andOperator);
526     }
527 
528     public void setGroupOrganizations(long groupId, long[] organizationIds)
529         throws SystemException {
530 
531         groupPersistence.setOrganizations(groupId, organizationIds);
532 
533         PermissionCacheUtil.clearCache();
534     }
535 
536     public void unsetGroupOrganizations(long groupId, long[] organizationIds)
537         throws SystemException {
538 
539         groupPersistence.removeOrganizations(groupId, organizationIds);
540 
541         PermissionCacheUtil.clearCache();
542     }
543 
544     public void unsetPasswordPolicyOrganizations(
545             long passwordPolicyId, long[] organizationIds)
546         throws SystemException {
547 
548         passwordPolicyRelLocalService.deletePasswordPolicyRels(
549             passwordPolicyId, Organization.class.getName(), organizationIds);
550     }
551 
552     public Organization updateOrganization(
553             long companyId, long organizationId, long parentOrganizationId,
554             String name, int type, boolean recursable, long regionId,
555             long countryId, int statusId, String comments)
556         throws PortalException, SystemException {
557 
558         parentOrganizationId = getParentOrganizationId(
559             companyId, parentOrganizationId);
560         recursable = true;
561 
562         validate(
563             companyId, organizationId, parentOrganizationId, name, type,
564             countryId, statusId);
565 
566         Organization organization = organizationPersistence.findByPrimaryKey(
567             organizationId);
568 
569         organization.setParentOrganizationId(parentOrganizationId);
570         organization.setName(name);
571 
572         if (type == OrganizationConstants.TYPE_LOCATION) {
573             organization.setLocation(true);
574         }
575         else {
576             organization.setLocation(false);
577         }
578 
579         organization.setRecursable(recursable);
580         organization.setRegionId(regionId);
581         organization.setCountryId(countryId);
582         organization.setStatusId(statusId);
583         organization.setComments(comments);
584 
585         organizationPersistence.update(organization, false);
586 
587         return organization;
588     }
589 
590     protected void addSuborganizations(
591             List<Organization> allSuborganizations,
592             List<Organization> organizations)
593         throws SystemException {
594 
595         for (Organization organization : organizations) {
596             if (!allSuborganizations.contains(organization)) {
597                 allSuborganizations.add(organization);
598 
599                 List<Organization> suborganizations =
600                     organizationPersistence.findByC_P(
601                         organization.getCompanyId(),
602                         organization.getOrganizationId());
603 
604                 addSuborganizations(allSuborganizations, suborganizations);
605             }
606         }
607     }
608 
609     protected long getParentOrganizationId(
610             long companyId, long parentOrganizationId)
611         throws SystemException {
612 
613         if (parentOrganizationId !=
614                 OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID) {
615 
616             // Ensure parent organization exists and belongs to the proper
617             // company
618 
619             Organization parentOrganization =
620                 organizationPersistence.fetchByPrimaryKey(parentOrganizationId);
621 
622             if ((parentOrganization == null) ||
623                 (companyId != parentOrganization.getCompanyId())) {
624 
625                 parentOrganizationId =
626                     OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID;
627             }
628         }
629 
630         return parentOrganizationId;
631     }
632 
633     protected List<Organization> getParentOrganizations(
634             Organization organization, boolean lastOrganization)
635         throws PortalException, SystemException {
636 
637         List<Organization> organizations = new ArrayList<Organization>();
638 
639         if (!lastOrganization) {
640             organizations.add(organization);
641         }
642 
643         long parentOrganizationId = organization.getParentOrganizationId();
644 
645         if (parentOrganizationId ==
646                 OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID) {
647 
648             return organizations;
649         }
650 
651         Organization parentOrganization =
652             organizationPersistence.findByPrimaryKey(parentOrganizationId);
653 
654         List<Organization> parentOrganizatons = getParentOrganizations(
655             parentOrganization, false);
656 
657         organizations.addAll(parentOrganizatons);
658 
659         return organizations;
660     }
661 
662     protected boolean isParentOrganization(
663             long parentOrganizationId, long organizationId)
664         throws PortalException, SystemException {
665 
666         // Return true if parentOrganizationId is among the parent organizatons
667         // of organizationId
668 
669         Organization parentOrganization =
670             organizationPersistence.findByPrimaryKey(
671                 parentOrganizationId);
672 
673         List<Organization> parentOrganizations = getParentOrganizations(
674             organizationId);
675 
676         if (parentOrganizations.contains(parentOrganization)) {
677             return true;
678         }
679         else {
680             return false;
681         }
682     }
683 
684     protected void validate(
685             long companyId, long parentOrganizationId, String name, int type,
686             long countryId, int statusId)
687         throws PortalException, SystemException {
688 
689         validate(
690             companyId, 0, parentOrganizationId, name, type, countryId,
691             statusId);
692     }
693 
694     protected void validate(
695             long companyId, long organizationId, long parentOrganizationId,
696             String name, int type, long countryId, int statusId)
697         throws PortalException, SystemException {
698 
699         if ((type == OrganizationConstants.TYPE_LOCATION) ||
700             (parentOrganizationId !=
701                 OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID)) {
702 
703             Organization parentOrganization =
704                 organizationPersistence.fetchByPrimaryKey(parentOrganizationId);
705 
706             if ((parentOrganization == null) ||
707                 (companyId != parentOrganization.getCompanyId()) ||
708                 (parentOrganizationId == organizationId) ||
709                 (parentOrganization.isLocation())) {
710 
711                 throw new OrganizationParentException();
712             }
713         }
714 
715         if ((organizationId > 0) &&
716             (parentOrganizationId !=
717                 OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID)) {
718 
719             // Prevent circular organizational references
720 
721             if (isParentOrganization(organizationId, parentOrganizationId)) {
722                 throw new OrganizationParentException();
723             }
724         }
725 
726         if (Validator.isNull(name)) {
727             throw new OrganizationNameException();
728         }
729         else {
730             Organization organization = organizationPersistence.fetchByC_N(
731                 companyId, name);
732 
733             if ((organization != null) &&
734                 (organization.getName().equalsIgnoreCase(name))) {
735 
736                 if ((organizationId <= 0) ||
737                     (organization.getOrganizationId() != organizationId)) {
738 
739                     throw new DuplicateOrganizationException();
740                 }
741             }
742         }
743 
744         try {
745             if ((countryId > 0) || PropsValues.ORGANIZATIONS_COUNTRY_REQUIRED) {
746                 countryPersistence.findByPrimaryKey(countryId);
747             }
748 
749             listTypeService.validate(
750                 statusId, ListTypeImpl.ORGANIZATION_STATUS);
751         }
752         catch (RemoteException re) {
753             throw new SystemException(re);
754         }
755     }
756 
757 }