001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.service.impl;
016    
017    import com.liferay.portal.DuplicateOrganizationException;
018    import com.liferay.portal.OrganizationNameException;
019    import com.liferay.portal.OrganizationParentException;
020    import com.liferay.portal.OrganizationTypeException;
021    import com.liferay.portal.RequiredOrganizationException;
022    import com.liferay.portal.kernel.cache.ThreadLocalCachable;
023    import com.liferay.portal.kernel.configuration.Filter;
024    import com.liferay.portal.kernel.dao.orm.QueryUtil;
025    import com.liferay.portal.kernel.exception.PortalException;
026    import com.liferay.portal.kernel.exception.SystemException;
027    import com.liferay.portal.kernel.search.Hits;
028    import com.liferay.portal.kernel.search.Indexer;
029    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
030    import com.liferay.portal.kernel.search.SearchContext;
031    import com.liferay.portal.kernel.search.Sort;
032    import com.liferay.portal.kernel.util.ArrayUtil;
033    import com.liferay.portal.kernel.util.GetterUtil;
034    import com.liferay.portal.kernel.util.OrderByComparator;
035    import com.liferay.portal.kernel.util.PropsKeys;
036    import com.liferay.portal.kernel.util.StringPool;
037    import com.liferay.portal.kernel.util.Validator;
038    import com.liferay.portal.model.Company;
039    import com.liferay.portal.model.Group;
040    import com.liferay.portal.model.LayoutSet;
041    import com.liferay.portal.model.ListTypeConstants;
042    import com.liferay.portal.model.Organization;
043    import com.liferay.portal.model.OrganizationConstants;
044    import com.liferay.portal.model.ResourceConstants;
045    import com.liferay.portal.model.Role;
046    import com.liferay.portal.model.RoleConstants;
047    import com.liferay.portal.model.User;
048    import com.liferay.portal.model.impl.OrganizationImpl;
049    import com.liferay.portal.security.permission.PermissionCacheUtil;
050    import com.liferay.portal.service.ServiceContext;
051    import com.liferay.portal.service.base.OrganizationLocalServiceBaseImpl;
052    import com.liferay.portal.util.PropsUtil;
053    import com.liferay.portal.util.PropsValues;
054    import com.liferay.portal.util.comparator.OrganizationNameComparator;
055    import com.liferay.portlet.enterpriseadmin.util.EnterpriseAdminUtil;
056    import com.liferay.portlet.expando.model.ExpandoBridge;
057    
058    import java.io.Serializable;
059    
060    import java.util.ArrayList;
061    import java.util.HashMap;
062    import java.util.Iterator;
063    import java.util.LinkedHashMap;
064    import java.util.List;
065    import java.util.Map;
066    
067    /**
068     * @author Brian Wing Shun Chan
069     * @author Jorge Ferrer
070     * @author Julio Camarero
071     * @author Hugo Huijser
072     */
073    public class OrganizationLocalServiceImpl
074            extends OrganizationLocalServiceBaseImpl {
075    
076            public void addGroupOrganizations(long groupId, long[] organizationIds)
077                    throws PortalException, SystemException {
078    
079                    groupPersistence.addOrganizations(groupId, organizationIds);
080    
081                    Indexer indexer = IndexerRegistryUtil.getIndexer(Organization.class);
082    
083                    indexer.reindex(organizationIds);
084    
085                    PermissionCacheUtil.clearCache();
086            }
087    
088            public Organization addOrganization(
089                            long userId, long parentOrganizationId, String name,
090                            String type, boolean recursable, long regionId, long countryId,
091                            int statusId, String comments, ServiceContext serviceContext)
092                    throws PortalException, SystemException {
093    
094                    // Organization
095    
096                    User user = userPersistence.findByPrimaryKey(userId);
097                    parentOrganizationId = getParentOrganizationId(
098                            user.getCompanyId(), parentOrganizationId);
099                    recursable = true;
100    
101                    validate(
102                            user.getCompanyId(), parentOrganizationId, name, type, countryId,
103                            statusId);
104    
105                    long organizationId = counterLocalService.increment();
106    
107                    Organization organization = organizationPersistence.create(
108                            organizationId);
109    
110                    organization.setCompanyId(user.getCompanyId());
111                    organization.setParentOrganizationId(parentOrganizationId);
112                    organization.setName(name);
113                    organization.setType(type);
114                    organization.setRecursable(recursable);
115                    organization.setRegionId(regionId);
116                    organization.setCountryId(countryId);
117                    organization.setStatusId(statusId);
118                    organization.setComments(comments);
119    
120                    organizationPersistence.update(organization, false);
121    
122                    // Group
123    
124                    Group group = groupLocalService.addGroup(
125                            userId, Organization.class.getName(), organizationId, null, null, 0,
126                            null, true, null);
127    
128                    if (PropsValues.ORGANIZATIONS_ASSIGNMENT_AUTO) {
129    
130                            // Role
131    
132                            Role role = roleLocalService.getRole(
133                                    organization.getCompanyId(), RoleConstants.ORGANIZATION_OWNER);
134    
135                            userGroupRoleLocalService.addUserGroupRoles(
136                                    userId, group.getGroupId(), new long[] {role.getRoleId()});
137    
138                            // User
139    
140                            userPersistence.addOrganization(userId, organizationId);
141                    }
142    
143                    // Resources
144    
145                    addOrganizationResources(userId, organization);
146    
147                    // Asset
148    
149                    if (serviceContext != null) {
150                            updateAsset(
151                                    userId, organization, serviceContext.getAssetCategoryIds(),
152                                    serviceContext.getAssetTagNames());
153                    }
154    
155                    // Expando
156    
157                    ExpandoBridge expandoBridge = organization.getExpandoBridge();
158    
159                    expandoBridge.setAttributes(serviceContext);
160    
161                    // Indexer
162    
163                    Indexer indexer = IndexerRegistryUtil.getIndexer(Organization.class);
164    
165                    indexer.reindex(organization);
166    
167                    return organization;
168            }
169    
170            public void addOrganizationResources(long userId, Organization organization)
171                    throws PortalException, SystemException {
172    
173                    String name = Organization.class.getName();
174    
175                    resourceLocalService.addResources(
176                            organization.getCompanyId(), 0, userId, name,
177                            organization.getOrganizationId(), false, false, false);
178            }
179    
180            public void addPasswordPolicyOrganizations(
181                            long passwordPolicyId, long[] organizationIds)
182                    throws SystemException {
183    
184                    passwordPolicyRelLocalService.addPasswordPolicyRels(
185                            passwordPolicyId, Organization.class.getName(), organizationIds);
186            }
187    
188            public void deleteLogo(long organizationId)
189                    throws PortalException, SystemException {
190    
191                    Organization organization = getOrganization(organizationId);
192    
193                    Group group = organization.getGroup();
194    
195                    LayoutSet publicLayoutSet =     layoutSetLocalService.getLayoutSet(
196                            group.getGroupId(), false);
197    
198                    if (publicLayoutSet.isLogo()) {
199                            long logoId = publicLayoutSet.getLogoId();
200    
201                            publicLayoutSet.setLogo(false);
202                            publicLayoutSet.setLogoId(0);
203    
204                            layoutSetPersistence.update(publicLayoutSet, false);
205    
206                            imageLocalService.deleteImage(logoId);
207                    }
208    
209                    LayoutSet privateLayoutSet = layoutSetLocalService.getLayoutSet(
210                            group.getGroupId(), true);
211    
212                    if (privateLayoutSet.isLogo()) {
213                            long logoId = privateLayoutSet.getLogoId();
214    
215                            privateLayoutSet.setLogo(false);
216                            privateLayoutSet.setLogoId(0);
217    
218                            layoutSetPersistence.update(publicLayoutSet, false);
219    
220                            if (imageLocalService.getImage(logoId) != null) {
221                                    imageLocalService.deleteImage(logoId);
222                            }
223                    }
224            }
225    
226            public void deleteOrganization(long organizationId)
227                    throws PortalException, SystemException {
228    
229                    Organization organization = organizationPersistence.findByPrimaryKey(
230                            organizationId);
231    
232                    if ((userLocalService.getOrganizationUsersCount(
233                                    organization.getOrganizationId(), true) > 0) ||
234                            (organizationPersistence.countByC_P(
235                                    organization.getCompanyId(),
236                                    organization.getOrganizationId()) > 0)) {
237    
238                            throw new RequiredOrganizationException();
239                    }
240    
241                    // Indexer
242    
243                    Indexer indexer = IndexerRegistryUtil.getIndexer(Organization.class);
244    
245                    indexer.delete(organization);
246    
247                    // Asset
248    
249                    assetEntryLocalService.deleteEntry(
250                            Organization.class.getName(), organization.getOrganizationId());
251    
252                    // Addresses
253    
254                    addressLocalService.deleteAddresses(
255                            organization.getCompanyId(), Organization.class.getName(),
256                            organization.getOrganizationId());
257    
258                    // Email addresses
259    
260                    emailAddressLocalService.deleteEmailAddresses(
261                            organization.getCompanyId(), Organization.class.getName(),
262                            organization.getOrganizationId());
263    
264                    // Expando
265    
266                    expandoValueLocalService.deleteValues(
267                            Organization.class.getName(), organization.getOrganizationId());
268    
269                    // Password policy relation
270    
271                    passwordPolicyRelLocalService.deletePasswordPolicyRel(
272                            Organization.class.getName(), organization.getOrganizationId());
273    
274                    // Phone
275    
276                    phoneLocalService.deletePhones(
277                            organization.getCompanyId(), Organization.class.getName(),
278                            organization.getOrganizationId());
279    
280                    // Website
281    
282                    websiteLocalService.deleteWebsites(
283                            organization.getCompanyId(), Organization.class.getName(),
284                            organization.getOrganizationId());
285    
286                    // Group
287    
288                    Group group = organization.getGroup();
289    
290                    groupLocalService.deleteGroup(group.getGroupId());
291    
292                    // Resources
293    
294                    String name = Organization.class.getName();
295    
296                    resourceLocalService.deleteResource(
297                            organization.getCompanyId(), name,
298                            ResourceConstants.SCOPE_INDIVIDUAL,
299                            organization.getOrganizationId());
300    
301                    // Organization
302    
303                    organizationPersistence.remove(organization);
304    
305                    // Permission cache
306    
307                    PermissionCacheUtil.clearCache();
308            }
309    
310            public List<Organization> getGroupOrganizations(long groupId)
311                    throws SystemException {
312    
313                    return groupPersistence.getOrganizations(groupId);
314            }
315    
316            public Organization getOrganization(long organizationId)
317                    throws PortalException, SystemException {
318    
319                    return organizationPersistence.findByPrimaryKey(organizationId);
320            }
321    
322            public Organization getOrganization(long companyId, String name)
323                    throws PortalException, SystemException {
324    
325                    return organizationPersistence.findByC_N(companyId, name);
326            }
327    
328            public long getOrganizationId(long companyId, String name)
329                    throws SystemException {
330    
331                    Organization organization = organizationPersistence.fetchByC_N(
332                            companyId, name);
333    
334                    if (organization != null) {
335                            return organization.getOrganizationId();
336                    }
337                    else {
338                            return 0;
339                    }
340            }
341    
342            public List<Organization> getOrganizations(long[] organizationIds)
343                    throws PortalException, SystemException {
344    
345                    List<Organization> organizations = new ArrayList<Organization>(
346                            organizationIds.length);
347    
348                    for (long organizationId : organizationIds) {
349                            Organization organization = getOrganization(organizationId);
350    
351                            organizations.add(organization);
352                    }
353    
354                    return organizations;
355            }
356    
357            public List<Organization> getParentOrganizations(long organizationId)
358                    throws PortalException, SystemException {
359    
360                    if (organizationId ==
361                                    OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID) {
362    
363                            return new ArrayList<Organization>();
364                    }
365    
366                    Organization organization =
367                            organizationPersistence.findByPrimaryKey(organizationId);
368    
369                    return getParentOrganizations(organization, true);
370            }
371    
372            public List<Organization> getSuborganizations(
373                            List<Organization> organizations)
374                    throws SystemException {
375    
376                    List<Organization> allSuborganizations = new ArrayList<Organization>();
377    
378                    for (int i = 0; i < organizations.size(); i++) {
379                            Organization organization = organizations.get(i);
380    
381                            List<Organization> suborganizations =
382                                    organizationPersistence.findByC_P(
383                                            organization.getCompanyId(),
384                                            organization.getOrganizationId());
385    
386                            addSuborganizations(allSuborganizations, suborganizations);
387                    }
388    
389                    return allSuborganizations;
390            }
391    
392            public List<Organization> getSubsetOrganizations(
393                    List<Organization> allOrganizations,
394                    List<Organization> availableOrganizations) {
395    
396                    List<Organization> subsetOrganizations = new ArrayList<Organization>();
397    
398                    Iterator<Organization> itr = allOrganizations.iterator();
399    
400                    while (itr.hasNext()) {
401                            Organization organization = itr.next();
402    
403                            if (availableOrganizations.contains(organization)) {
404                                    subsetOrganizations.add(organization);
405                            }
406                    }
407    
408                    return subsetOrganizations;
409            }
410    
411            public List<Organization> getUserOrganizations(long userId)
412                    throws PortalException, SystemException {
413    
414                    return getUserOrganizations(userId, false);
415            }
416    
417            public List<Organization> getUserOrganizations(
418                            long userId, boolean inheritUserGroups)
419                    throws PortalException, SystemException {
420    
421                    return getUserOrganizations(
422                            userId, inheritUserGroups, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
423            }
424    
425            public List<Organization> getUserOrganizations(
426                            long userId, boolean inheritUserGroups, int start, int end)
427                    throws PortalException, SystemException {
428    
429                    if (inheritUserGroups &&
430                            PropsValues.ORGANIZATIONS_USER_GROUP_MEMBERSHIP_ENABLED) {
431    
432                            User user = userPersistence.findByPrimaryKey(userId);
433    
434                            LinkedHashMap<String, Object> organizationParams =
435                                    new LinkedHashMap<String, Object>();
436    
437                            organizationParams.put("usersOrgs", new Long(userId));
438    
439                            return search(
440                                    user.getCompanyId(),
441                                    OrganizationConstants.ANY_PARENT_ORGANIZATION_ID, null, null,
442                                    null, null, organizationParams, start, end);
443                    }
444                    else {
445                            return userPersistence.getOrganizations(userId, start, end);
446                    }
447            }
448    
449            public List<Organization> getUserOrganizations(
450                            long userId, int start, int end)
451                    throws PortalException, SystemException {
452    
453                    return getUserOrganizations(userId, false, start, end);
454            }
455    
456            @ThreadLocalCachable
457            public int getUserOrganizationsCount(long userId) throws SystemException {
458                    return userPersistence.getOrganizationsSize(userId);
459            }
460    
461            public boolean hasGroupOrganization(long groupId, long organizationId)
462                    throws SystemException {
463    
464                    return groupPersistence.containsOrganization(groupId, organizationId);
465            }
466    
467            public boolean hasPasswordPolicyOrganization(
468                            long passwordPolicyId, long organizationId)
469                    throws SystemException {
470    
471                    return passwordPolicyRelLocalService.hasPasswordPolicyRel(
472                            passwordPolicyId, Organization.class.getName(), organizationId);
473            }
474    
475            public boolean hasUserOrganization(long userId, long organizationId)
476                    throws SystemException {
477    
478                    return userPersistence.containsOrganization(userId, organizationId);
479            }
480    
481            public boolean hasUserOrganization(
482                            long userId, long organizationId, boolean inheritSuborganizations,
483                            boolean inheritUserGroups, boolean includeSpecifiedOrganization)
484                    throws PortalException, SystemException {
485    
486                    if (!inheritSuborganizations && !inheritUserGroups) {
487                            return userPersistence.containsOrganization(userId, organizationId);
488                    }
489    
490                    if (inheritSuborganizations) {
491                            LinkedHashMap<String, Object> params =
492                                    new LinkedHashMap<String, Object>();
493    
494                            Long[][] leftAndRightOrganizationIds =
495                                    EnterpriseAdminUtil.getLeftAndRightOrganizationIds(
496                                            organizationId);
497    
498                            if (!includeSpecifiedOrganization) {
499                                    leftAndRightOrganizationIds[0][0] =
500                                            leftAndRightOrganizationIds[0][0].longValue() + 1;
501                            }
502    
503                            params.put("usersOrgsTree", leftAndRightOrganizationIds);
504    
505                            if (userFinder.countByUser(userId, params) > 0) {
506                                    return true;
507                            }
508                    }
509    
510                    if (inheritUserGroups) {
511                            if (organizationFinder.countByO_U(organizationId, userId) > 0) {
512                                    return true;
513                            }
514                    }
515    
516                    return false;
517            }
518    
519            public void rebuildTree(long companyId, boolean force)
520                    throws SystemException {
521    
522                    organizationPersistence.rebuildTree(companyId, force);
523            }
524    
525            public Hits search(
526                            long companyId, long parentOrganizationId, String keywords,
527                            LinkedHashMap<String, Object> params, int start, int end, Sort sort)
528                    throws SystemException {
529    
530                    String name = null;
531                    String type = null;
532                    String street = null;
533                    String city = null;
534                    String zip = null;
535                    String region = null;
536                    String country = null;
537                    boolean andOperator = false;
538    
539                    if (Validator.isNotNull(keywords)) {
540                            name = keywords;
541                            type = keywords;
542                            street = keywords;
543                            city = keywords;
544                            zip = keywords;
545                            region = keywords;
546                            country = keywords;
547                    }
548                    else {
549                            andOperator = true;
550                    }
551    
552                    return search(
553                            companyId, parentOrganizationId, name, type, street, city, zip,
554                            region, country, params, andOperator, start, end, sort);
555            }
556    
557            public List<Organization> search(
558                            long companyId, long parentOrganizationId, String keywords,
559                            String type, Long regionId, Long countryId,
560                            LinkedHashMap<String, Object> params,
561                            int start, int end)
562                    throws SystemException {
563    
564                    return search(
565                            companyId, parentOrganizationId, keywords, type, regionId,
566                            countryId, params, start, end,
567                            new OrganizationNameComparator(true));
568            }
569    
570            public List<Organization> search(
571                            long companyId, long parentOrganizationId, String keywords,
572                            String type, Long regionId, Long countryId,
573                            LinkedHashMap<String, Object> params,
574                            int start, int end, OrderByComparator obc)
575                    throws SystemException {
576    
577                    String parentOrganizationIdComparator = StringPool.EQUAL;
578    
579                    if (parentOrganizationId ==
580                                    OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
581    
582                            parentOrganizationIdComparator = StringPool.NOT_EQUAL;
583                    }
584    
585                    return organizationFinder.findByKeywords(
586                            companyId, parentOrganizationId, parentOrganizationIdComparator,
587                            keywords, type, regionId, countryId, params, start, end,
588                            obc);
589            }
590    
591            public List<Organization> search(
592                            long companyId, long parentOrganizationId, String name, String type,
593                            String street, String city, String zip,
594                            Long regionId, Long countryId,
595                            LinkedHashMap<String, Object> params, boolean andOperator,
596                            int start, int end)
597                    throws SystemException {
598    
599                    return search(
600                            companyId, parentOrganizationId, name, type, street, city, zip,
601                            regionId, countryId, params, andOperator, start, end,
602                            new OrganizationNameComparator(true));
603            }
604    
605            public List<Organization> search(
606                            long companyId, long parentOrganizationId, String name, String type,
607                            String street, String city, String zip,
608                            Long regionId, Long countryId, LinkedHashMap<String, Object> params,
609                            boolean andOperator, int start, int end, OrderByComparator obc)
610                    throws SystemException {
611    
612                    String parentOrganizationIdComparator = StringPool.EQUAL;
613    
614                    if (parentOrganizationId ==
615                                    OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
616    
617                            parentOrganizationIdComparator = StringPool.NOT_EQUAL;
618                    }
619    
620                    return organizationFinder.findByC_PO_N_T_S_C_Z_R_C(
621                            companyId, parentOrganizationId, parentOrganizationIdComparator,
622                            name, type, street, city, zip, regionId, countryId, params,
623                            andOperator, start, end, obc);
624            }
625    
626            public Hits search(
627                            long companyId, long parentOrganizationId, String name, String type,
628                            String street, String city, String zip, String region,
629                            String country, LinkedHashMap<String, Object> params,
630                            boolean andSearch, int start, int end, Sort sort)
631                    throws SystemException {
632    
633                    try {
634                            Map<String, Serializable> attributes =
635                                    new HashMap<String, Serializable>();
636    
637                            attributes.put("city", city);
638                            attributes.put("country", country);
639                            attributes.put("name", name);
640                            attributes.put("params", params);
641    
642                            if (parentOrganizationId > 0) {
643                                    attributes.put(
644                                            "parentOrganizationId",
645                                            String.valueOf(parentOrganizationId));
646                            }
647    
648                            attributes.put("region", region);
649                            attributes.put("street", street);
650                            attributes.put("type", type);
651                            attributes.put("zip", zip);
652    
653                            SearchContext searchContext = new SearchContext();
654    
655                            searchContext.setAndSearch(andSearch);
656                            searchContext.setAttributes(attributes);
657                            searchContext.setCompanyId(companyId);
658                            searchContext.setEnd(end);
659                            searchContext.setSorts(new Sort[] {sort});
660                            searchContext.setStart(start);
661    
662                            Indexer indexer = IndexerRegistryUtil.getIndexer(
663                                    Organization.class);
664    
665                            return indexer.search(searchContext);
666                    }
667                    catch (Exception e) {
668                            throw new SystemException(e);
669                    }
670            }
671    
672            public int searchCount(
673                            long companyId, long parentOrganizationId, String keywords,
674                            String type, Long regionId, Long countryId,
675                            LinkedHashMap<String, Object> params)
676                    throws SystemException {
677    
678                    String parentOrganizationIdComparator = StringPool.EQUAL;
679    
680                    if (parentOrganizationId ==
681                                    OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
682    
683                            parentOrganizationIdComparator = StringPool.NOT_EQUAL;
684                    }
685    
686                    return organizationFinder.countByKeywords(
687                            companyId, parentOrganizationId, parentOrganizationIdComparator,
688                            keywords, type, regionId, countryId, params);
689            }
690    
691            public int searchCount(
692                            long companyId, long parentOrganizationId, String name, String type,
693                            String street, String city, String zip,
694                            Long regionId, Long countryId, LinkedHashMap<String, Object> params,
695                            boolean andOperator)
696                    throws SystemException {
697    
698                    String parentOrganizationIdComparator = StringPool.EQUAL;
699    
700                    if (parentOrganizationId ==
701                                    OrganizationConstants.ANY_PARENT_ORGANIZATION_ID) {
702    
703                            parentOrganizationIdComparator = StringPool.NOT_EQUAL;
704                    }
705    
706                    return organizationFinder.countByC_PO_N_T_S_C_Z_R_C(
707                            companyId, parentOrganizationId, parentOrganizationIdComparator,
708                            name, type, street, city, zip, regionId, countryId, params,
709                            andOperator);
710            }
711    
712            public void setGroupOrganizations(long groupId, long[] organizationIds)
713                    throws PortalException, SystemException {
714    
715                    groupPersistence.setOrganizations(groupId, organizationIds);
716    
717                    Indexer indexer = IndexerRegistryUtil.getIndexer(Organization.class);
718    
719                    indexer.reindex(organizationIds);
720    
721                    PermissionCacheUtil.clearCache();
722            }
723    
724            public void unsetGroupOrganizations(long groupId, long[] organizationIds)
725                    throws PortalException, SystemException {
726    
727                    groupPersistence.removeOrganizations(groupId, organizationIds);
728    
729                    Indexer indexer = IndexerRegistryUtil.getIndexer(Organization.class);
730    
731                    indexer.reindex(organizationIds);
732    
733                    PermissionCacheUtil.clearCache();
734            }
735    
736            public void unsetPasswordPolicyOrganizations(
737                            long passwordPolicyId, long[] organizationIds)
738                    throws SystemException {
739    
740                    passwordPolicyRelLocalService.deletePasswordPolicyRels(
741                            passwordPolicyId, Organization.class.getName(), organizationIds);
742            }
743    
744            public void updateAsset(
745                            long userId, Organization organization, long[] assetCategoryIds,
746                            String[] assetTagNames)
747                    throws PortalException, SystemException {
748    
749                    User user = userPersistence.findByPrimaryKey(userId);
750    
751                    Company company = companyPersistence.findByPrimaryKey(
752                            user.getCompanyId());
753    
754                    Group companyGroup = company.getGroup();
755    
756                    assetEntryLocalService.updateEntry(
757                            userId, companyGroup.getGroupId(), Organization.class.getName(),
758                            organization.getOrganizationId(), null, assetCategoryIds,
759                            assetTagNames, false, null, null, null, null, null,
760                            organization.getName(), StringPool.BLANK, null, null, 0, 0, null,
761                            false);
762            }
763    
764            public Organization updateOrganization(
765                            long companyId, long organizationId, long parentOrganizationId,
766                            String name, String type, boolean recursable, long regionId,
767                            long countryId, int statusId, String comments,
768                            ServiceContext serviceContext)
769                    throws PortalException, SystemException {
770    
771                    // Organization
772    
773                    parentOrganizationId = getParentOrganizationId(
774                            companyId, parentOrganizationId);
775                    recursable = true;
776    
777                    validate(
778                            companyId, organizationId, parentOrganizationId, name, type,
779                            countryId, statusId);
780    
781                    Organization organization = organizationPersistence.findByPrimaryKey(
782                            organizationId);
783    
784                    organization.setParentOrganizationId(parentOrganizationId);
785                    organization.setName(name);
786                    organization.setType(type);
787                    organization.setRecursable(recursable);
788                    organization.setRegionId(regionId);
789                    organization.setCountryId(countryId);
790                    organization.setStatusId(statusId);
791                    organization.setComments(comments);
792    
793                    organizationPersistence.update(organization, false);
794    
795                    // Asset
796    
797                    if (serviceContext != null) {
798                            updateAsset(
799                                    serviceContext.getUserId(), organization,
800                                    serviceContext.getAssetCategoryIds(),
801                                    serviceContext.getAssetTagNames());
802                    }
803    
804                    // Expando
805    
806                    ExpandoBridge expandoBridge = organization.getExpandoBridge();
807    
808                    expandoBridge.setAttributes(serviceContext);
809    
810                    // Indexer
811    
812                    Indexer indexer = IndexerRegistryUtil.getIndexer(Organization.class);
813    
814                    indexer.reindex(organization);
815    
816                    return organization;
817            }
818    
819            protected void addSuborganizations(
820                            List<Organization> allSuborganizations,
821                            List<Organization> organizations)
822                    throws SystemException {
823    
824                    for (Organization organization : organizations) {
825                            if (!allSuborganizations.contains(organization)) {
826                                    allSuborganizations.add(organization);
827    
828                                    List<Organization> suborganizations =
829                                            organizationPersistence.findByC_P(
830                                                    organization.getCompanyId(),
831                                                    organization.getOrganizationId());
832    
833                                    addSuborganizations(allSuborganizations, suborganizations);
834                            }
835                    }
836            }
837    
838            protected long getParentOrganizationId(
839                            long companyId, long parentOrganizationId)
840                    throws SystemException {
841    
842                    if (parentOrganizationId !=
843                                    OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID) {
844    
845                            // Ensure parent organization exists and belongs to the proper
846                            // company
847    
848                            Organization parentOrganization =
849                                    organizationPersistence.fetchByPrimaryKey(parentOrganizationId);
850    
851                            if ((parentOrganization == null) ||
852                                    (companyId != parentOrganization.getCompanyId())) {
853    
854                                    parentOrganizationId =
855                                            OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID;
856                            }
857                    }
858    
859                    return parentOrganizationId;
860            }
861    
862            protected List<Organization> getParentOrganizations(
863                            Organization organization, boolean lastOrganization)
864                    throws PortalException, SystemException {
865    
866                    List<Organization> organizations = new ArrayList<Organization>();
867    
868                    if (!lastOrganization) {
869                            organizations.add(organization);
870                    }
871    
872                    long parentOrganizationId = organization.getParentOrganizationId();
873    
874                    if (parentOrganizationId ==
875                                    OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID) {
876    
877                            return organizations;
878                    }
879    
880                    Organization parentOrganization =
881                            organizationPersistence.findByPrimaryKey(parentOrganizationId);
882    
883                    List<Organization> parentOrganizatons = getParentOrganizations(
884                            parentOrganization, false);
885    
886                    organizations.addAll(parentOrganizatons);
887    
888                    return organizations;
889            }
890    
891            protected boolean isParentOrganization(
892                            long parentOrganizationId, long organizationId)
893                    throws PortalException, SystemException {
894    
895                    // Return true if parentOrganizationId is among the parent organizatons
896                    // of organizationId
897    
898                    Organization parentOrganization =
899                            organizationPersistence.findByPrimaryKey(
900                                    parentOrganizationId);
901    
902                    List<Organization> parentOrganizations = getParentOrganizations(
903                            organizationId);
904    
905                    if (parentOrganizations.contains(parentOrganization)) {
906                            return true;
907                    }
908                    else {
909                            return false;
910                    }
911            }
912    
913            protected void validate(
914                            long companyId, long organizationId, long parentOrganizationId,
915                            String name, String type, long countryId, int statusId)
916                    throws PortalException, SystemException {
917    
918                    if (!ArrayUtil.contains(PropsValues.ORGANIZATIONS_TYPES, type)) {
919                            throw new OrganizationTypeException(
920                                    "Invalid organization type " + type);
921                    }
922    
923                    if ((parentOrganizationId ==
924                                    OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID)) {
925    
926                            if (!OrganizationImpl.isRootable(type)) {
927                                    throw new OrganizationParentException(
928                                            "Organization of type " + type + " cannot be a root");
929                            }
930                    }
931                    else {
932                            Organization parentOrganization =
933                                    organizationPersistence.fetchByPrimaryKey(
934                                            parentOrganizationId);
935    
936                            if (parentOrganization == null) {
937                                    throw new OrganizationParentException(
938                                            "Organization " + parentOrganizationId + " doesn't exist");
939                            }
940    
941                            String[] childrenTypes = OrganizationImpl.getChildrenTypes(
942                                    parentOrganization.getType());
943    
944                            if (childrenTypes.length == 0) {
945                                    throw new OrganizationParentException(
946                                            "Organization of type " + type + " cannot have children");
947                            }
948    
949                            if ((companyId != parentOrganization.getCompanyId()) ||
950                                    (parentOrganizationId == organizationId)) {
951    
952                                    throw new OrganizationParentException();
953                            }
954    
955                            if (!ArrayUtil.contains(childrenTypes, type)) {
956                                    throw new OrganizationParentException(
957                                            "Type " + type + " not allowed as child of " +
958                                                    parentOrganization.getType());
959                            }
960                    }
961    
962                    if ((organizationId > 0) &&
963                            (parentOrganizationId !=
964                                    OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID)) {
965    
966                            // Prevent circular organizational references
967    
968                            if (isParentOrganization(organizationId, parentOrganizationId)) {
969                                    throw new OrganizationParentException();
970                            }
971                    }
972    
973                    if (Validator.isNull(name)) {
974                            throw new OrganizationNameException();
975                    }
976                    else {
977                            Organization organization = organizationPersistence.fetchByC_N(
978                                    companyId, name);
979    
980                            if ((organization != null) &&
981                                    (organization.getName().equalsIgnoreCase(name))) {
982    
983                                    if ((organizationId <= 0) ||
984                                            (organization.getOrganizationId() != organizationId)) {
985    
986                                            throw new DuplicateOrganizationException();
987                                    }
988                            }
989                    }
990    
991                    boolean countryRequired = GetterUtil.getBoolean(
992                            PropsUtil.get(
993                                    PropsKeys.ORGANIZATIONS_COUNTRY_REQUIRED, new Filter(type)));
994    
995                    if (countryRequired || (countryId > 0)) {
996                            countryPersistence.findByPrimaryKey(countryId);
997                    }
998    
999                    listTypeService.validate(
1000                            statusId, ListTypeConstants.ORGANIZATION_STATUS);
1001            }
1002    
1003            protected void validate(
1004                            long companyId, long parentOrganizationId, String name, String type,
1005                            long countryId, int statusId)
1006                    throws PortalException, SystemException {
1007    
1008                    validate(
1009                            companyId, 0, parentOrganizationId, name, type, countryId,
1010                            statusId);
1011            }
1012    
1013    }