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