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