001    /**
002     * Copyright (c) 2000-present 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.LocaleException;
018    import com.liferay.portal.exception.AccountNameException;
019    import com.liferay.portal.exception.CompanyMxException;
020    import com.liferay.portal.exception.CompanyVirtualHostException;
021    import com.liferay.portal.exception.CompanyWebIdException;
022    import com.liferay.portal.exception.NoSuchVirtualHostException;
023    import com.liferay.portal.exception.RequiredCompanyException;
024    import com.liferay.portal.kernel.bean.BeanReference;
025    import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
026    import com.liferay.portal.kernel.dao.orm.DynamicQuery;
027    import com.liferay.portal.kernel.dao.orm.Property;
028    import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
029    import com.liferay.portal.kernel.exception.PortalException;
030    import com.liferay.portal.kernel.exception.SystemException;
031    import com.liferay.portal.kernel.instance.lifecycle.PortalInstanceLifecycleManager;
032    import com.liferay.portal.kernel.language.LanguageUtil;
033    import com.liferay.portal.kernel.log.Log;
034    import com.liferay.portal.kernel.log.LogFactoryUtil;
035    import com.liferay.portal.kernel.search.FacetedSearcher;
036    import com.liferay.portal.kernel.search.Hits;
037    import com.liferay.portal.kernel.search.Indexer;
038    import com.liferay.portal.kernel.search.SearchContext;
039    import com.liferay.portal.kernel.search.SearchEngineHelperUtil;
040    import com.liferay.portal.kernel.search.facet.AssetEntriesFacet;
041    import com.liferay.portal.kernel.search.facet.Facet;
042    import com.liferay.portal.kernel.search.facet.ScopeFacet;
043    import com.liferay.portal.kernel.security.auth.CompanyThreadLocal;
044    import com.liferay.portal.kernel.transaction.Isolation;
045    import com.liferay.portal.kernel.transaction.TransactionCommitCallbackUtil;
046    import com.liferay.portal.kernel.transaction.Transactional;
047    import com.liferay.portal.kernel.util.ArrayUtil;
048    import com.liferay.portal.kernel.util.Base64;
049    import com.liferay.portal.kernel.util.LocaleUtil;
050    import com.liferay.portal.kernel.util.PropsKeys;
051    import com.liferay.portal.kernel.util.StringPool;
052    import com.liferay.portal.kernel.util.StringUtil;
053    import com.liferay.portal.kernel.util.TimeZoneUtil;
054    import com.liferay.portal.kernel.util.UnicodeProperties;
055    import com.liferay.portal.kernel.util.Validator;
056    import com.liferay.portal.kernel.workflow.WorkflowConstants;
057    import com.liferay.portal.liveusers.LiveUsers;
058    import com.liferay.portal.model.Account;
059    import com.liferay.portal.model.Company;
060    import com.liferay.portal.model.CompanyConstants;
061    import com.liferay.portal.model.Contact;
062    import com.liferay.portal.model.ContactConstants;
063    import com.liferay.portal.model.Group;
064    import com.liferay.portal.model.GroupConstants;
065    import com.liferay.portal.model.LayoutPrototype;
066    import com.liferay.portal.model.LayoutSetPrototype;
067    import com.liferay.portal.model.Organization;
068    import com.liferay.portal.model.OrganizationConstants;
069    import com.liferay.portal.model.PasswordPolicy;
070    import com.liferay.portal.model.PortalPreferences;
071    import com.liferay.portal.model.Portlet;
072    import com.liferay.portal.model.Role;
073    import com.liferay.portal.model.RoleConstants;
074    import com.liferay.portal.model.User;
075    import com.liferay.portal.model.VirtualHost;
076    import com.liferay.portal.service.base.CompanyLocalServiceBaseImpl;
077    import com.liferay.portal.service.persistence.CompanyProvider;
078    import com.liferay.portal.service.persistence.CompanyProviderWrapper;
079    import com.liferay.portal.util.Portal;
080    import com.liferay.portal.util.PortalInstances;
081    import com.liferay.portal.util.PortalUtil;
082    import com.liferay.portal.util.PortletKeys;
083    import com.liferay.portal.util.PrefsPropsUtil;
084    import com.liferay.portal.util.PropsUtil;
085    import com.liferay.portal.util.PropsValues;
086    import com.liferay.registry.Registry;
087    import com.liferay.registry.RegistryUtil;
088    import com.liferay.registry.ServiceReference;
089    import com.liferay.registry.ServiceTracker;
090    import com.liferay.registry.ServiceTrackerCustomizer;
091    import com.liferay.util.Encryptor;
092    import com.liferay.util.EncryptorException;
093    
094    import java.io.File;
095    import java.io.IOException;
096    import java.io.InputStream;
097    
098    import java.util.ArrayList;
099    import java.util.Arrays;
100    import java.util.Date;
101    import java.util.HashSet;
102    import java.util.List;
103    import java.util.Locale;
104    import java.util.Map;
105    import java.util.Set;
106    import java.util.TimeZone;
107    import java.util.concurrent.Callable;
108    
109    import javax.portlet.PortletException;
110    import javax.portlet.PortletPreferences;
111    
112    /**
113     * Provides the local service for adding, checking, and updating companies. Each
114     * company refers to a separate portal instance.
115     *
116     * @author Brian Wing Shun Chan
117     * @author Julio Camarero
118     */
119    public class CompanyLocalServiceImpl extends CompanyLocalServiceBaseImpl {
120    
121            public CompanyLocalServiceImpl() {
122                    Registry registry = RegistryUtil.getRegistry();
123    
124                    _serviceTracker = registry.trackServices(
125                            PortalInstanceLifecycleManager.class,
126                            new PortalInstanceLifecycleManagerServiceTrackerCustomizer());
127    
128                    _serviceTracker.open();
129            }
130    
131            /**
132             * Adds a company.
133             *
134             * @param  webId the the company's web domain
135             * @param  virtualHostname the company's virtual host name
136             * @param  mx the company's mail domain
137             * @param  system whether the company is the very first company (i.e., the
138             *         super company)
139             * @param  maxUsers the max number of company users (optionally
140             *         <code>0</code>)
141             * @param  active whether the company is active
142             * @return the company
143             */
144            @Override
145            public Company addCompany(
146                            String webId, String virtualHostname, String mx, boolean system,
147                            int maxUsers, boolean active)
148                    throws PortalException {
149    
150                    // Company
151    
152                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
153    
154                    if (Validator.isNull(webId) ||
155                            webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID) ||
156                            (companyPersistence.fetchByWebId(webId) != null)) {
157    
158                            throw new CompanyWebIdException();
159                    }
160    
161                    validateVirtualHost(webId, virtualHostname);
162                    validateMx(mx);
163    
164                    Company company = checkCompany(webId, mx);
165    
166                    company = companyPersistence.fetchByPrimaryKey(company.getCompanyId());
167    
168                    company.setMx(mx);
169                    company.setSystem(system);
170                    company.setMaxUsers(maxUsers);
171                    company.setActive(active);
172    
173                    companyPersistence.update(company);
174    
175                    // Virtual host
176    
177                    company = updateVirtualHostname(
178                            company.getCompanyId(), virtualHostname);
179    
180                    return company;
181            }
182    
183            /**
184             * Returns the company with the web domain.
185             *
186             * The method sets mail domain to the web domain to the default name set in
187             * portal.properties
188             *
189             * @param  webId the company's web domain
190             * @return the company with the web domain
191             */
192            @Override
193            public Company checkCompany(String webId) throws PortalException {
194                    String mx = webId;
195    
196                    return companyLocalService.checkCompany(webId, mx);
197            }
198    
199            /**
200             * Returns the company with the web domain and mail domain. If no such
201             * company exits, the method will create a new company.
202             *
203             * The method goes through a series of checks to ensure that the company
204             * contains default users, groups, etc.
205             *
206             * @param  webId the company's web domain
207             * @param  mx the company's mail domain
208             * @return the company with the web domain and mail domain
209             */
210            @Override
211            @Transactional(
212                    isolation = Isolation.PORTAL,
213                    rollbackFor = {PortalException.class, SystemException.class}
214            )
215            public Company checkCompany(String webId, String mx)
216                    throws PortalException {
217    
218                    // Company
219    
220                    Date now = new Date();
221    
222                    Company company = companyPersistence.fetchByWebId(webId);
223    
224                    if (company == null) {
225                            long companyId = counterLocalService.increment();
226    
227                            company = companyPersistence.create(companyId);
228    
229                            try {
230                                    company.setKey(Base64.objectToString(Encryptor.generateKey()));
231                            }
232                            catch (EncryptorException ee) {
233                                    throw new SystemException(ee);
234                            }
235    
236                            company.setWebId(webId);
237                            company.setMx(mx);
238                            company.setActive(true);
239    
240                            companyPersistence.update(company);
241    
242                            // Account
243    
244                            String name = webId;
245    
246                            if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
247                                    name = PropsValues.COMPANY_DEFAULT_NAME;
248                            }
249    
250                            String legalName = null;
251                            String legalId = null;
252                            String legalType = null;
253                            String sicCode = null;
254                            String tickerSymbol = null;
255                            String industry = null;
256                            String type = null;
257                            String size = null;
258    
259                            updateAccount(
260                                    company, name, legalName, legalId, legalType, sicCode,
261                                    tickerSymbol, industry, type, size);
262    
263                            // Virtual host
264    
265                            if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
266                                    company = updateVirtualHostname(
267                                            companyId, _DEFAULT_VIRTUAL_HOST);
268                            }
269    
270                            // Demo settings
271    
272                            if (webId.equals("liferay.net")) {
273                                    company = companyPersistence.findByWebId(webId);
274    
275                                    updateVirtualHostname(companyId, "demo.liferay.net");
276    
277                                    updateSecurity(
278                                            companyId, CompanyConstants.AUTH_TYPE_EA, true, true, true,
279                                            true, false, true);
280    
281                                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
282                                            companyId);
283    
284                                    try {
285                                            preferences.setValue(
286                                                    PropsKeys.ADMIN_EMAIL_FROM_NAME, "Liferay Demo");
287                                            preferences.setValue(
288                                                    PropsKeys.ADMIN_EMAIL_FROM_ADDRESS, "test@liferay.net");
289    
290                                            preferences.store();
291                                    }
292                                    catch (IOException ioe) {
293                                            throw new SystemException(ioe);
294                                    }
295                                    catch (PortletException pe) {
296                                            throw new SystemException(pe);
297                                    }
298                            }
299                    }
300    
301                    CompanyProvider currentCompanyProvider =
302                            _companyProviderWrapper.getCompanyProvider();
303    
304                    try {
305                            final long companyId = company.getCompanyId();
306    
307                            _companyProviderWrapper.setCompanyProvider(
308                                    new CustomCompanyProvider(companyId));
309    
310                            // Key
311    
312                            checkCompanyKey(companyId);
313    
314                            // Default user
315    
316                            User defaultUser = userPersistence.fetchByC_DU(companyId, true);
317    
318                            if (defaultUser != null) {
319                                    if (!defaultUser.isAgreedToTermsOfUse()) {
320                                            defaultUser.setAgreedToTermsOfUse(true);
321    
322                                            userPersistence.update(defaultUser);
323                                    }
324                            }
325                            else {
326                                    long userId = counterLocalService.increment();
327    
328                                    defaultUser = userPersistence.create(userId);
329    
330                                    defaultUser.setCompanyId(companyId);
331                                    defaultUser.setDefaultUser(true);
332                                    defaultUser.setContactId(counterLocalService.increment());
333                                    defaultUser.setPassword("password");
334                                    defaultUser.setScreenName(
335                                            String.valueOf(defaultUser.getUserId()));
336                                    defaultUser.setEmailAddress("default@" + company.getMx());
337    
338                                    if (Validator.isNotNull(PropsValues.COMPANY_DEFAULT_LOCALE)) {
339                                            defaultUser.setLanguageId(
340                                                    PropsValues.COMPANY_DEFAULT_LOCALE);
341                                    }
342                                    else {
343                                            Locale locale = LocaleUtil.getDefault();
344    
345                                            defaultUser.setLanguageId(locale.toString());
346                                    }
347    
348                                    if (Validator.isNotNull(
349                                                    PropsValues.COMPANY_DEFAULT_TIME_ZONE)) {
350    
351                                            defaultUser.setTimeZoneId(
352                                                    PropsValues.COMPANY_DEFAULT_TIME_ZONE);
353                                    }
354                                    else {
355                                            TimeZone timeZone = TimeZoneUtil.getDefault();
356    
357                                            defaultUser.setTimeZoneId(timeZone.getID());
358                                    }
359    
360                                    String greeting = LanguageUtil.format(
361                                            defaultUser.getLocale(), "welcome", null, false);
362    
363                                    defaultUser.setGreeting(greeting + StringPool.EXCLAMATION);
364                                    defaultUser.setLoginDate(now);
365                                    defaultUser.setFailedLoginAttempts(0);
366                                    defaultUser.setAgreedToTermsOfUse(true);
367                                    defaultUser.setStatus(WorkflowConstants.STATUS_APPROVED);
368    
369                                    userPersistence.update(defaultUser);
370    
371                                    // Contact
372    
373                                    Contact defaultContact = contactPersistence.create(
374                                            defaultUser.getContactId());
375    
376                                    defaultContact.setCompanyId(defaultUser.getCompanyId());
377                                    defaultContact.setUserId(defaultUser.getUserId());
378                                    defaultContact.setUserName(StringPool.BLANK);
379                                    defaultContact.setClassName(User.class.getName());
380                                    defaultContact.setClassPK(defaultUser.getUserId());
381                                    defaultContact.setAccountId(company.getAccountId());
382                                    defaultContact.setParentContactId(
383                                            ContactConstants.DEFAULT_PARENT_CONTACT_ID);
384                                    defaultContact.setEmailAddress(defaultUser.getEmailAddress());
385                                    defaultContact.setFirstName(StringPool.BLANK);
386                                    defaultContact.setMiddleName(StringPool.BLANK);
387                                    defaultContact.setLastName(StringPool.BLANK);
388                                    defaultContact.setMale(true);
389                                    defaultContact.setBirthday(now);
390    
391                                    contactPersistence.update(defaultContact);
392                            }
393    
394                            // System roles
395    
396                            roleLocalService.checkSystemRoles(companyId);
397    
398                            // System groups
399    
400                            groupLocalService.checkSystemGroups(companyId);
401    
402                            // Company group
403    
404                            groupLocalService.checkCompanyGroup(companyId);
405    
406                            // Default password policy
407    
408                            passwordPolicyLocalService.checkDefaultPasswordPolicy(companyId);
409    
410                            // Default user must have the Guest role
411    
412                            Role guestRole = roleLocalService.getRole(
413                                    companyId, RoleConstants.GUEST);
414    
415                            roleLocalService.setUserRoles(
416                                    defaultUser.getUserId(), new long[] {guestRole.getRoleId()});
417    
418                            // Default admin
419    
420                            if (userPersistence.countByCompanyId(companyId) == 1) {
421                                    String emailAddress =
422                                            PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX + "@" + mx;
423    
424                                    userLocalService.addDefaultAdminUser(
425                                            companyId, PropsValues.DEFAULT_ADMIN_SCREEN_NAME,
426                                            emailAddress, defaultUser.getLocale(),
427                                            PropsValues.DEFAULT_ADMIN_FIRST_NAME,
428                                            PropsValues.DEFAULT_ADMIN_MIDDLE_NAME,
429                                            PropsValues.DEFAULT_ADMIN_LAST_NAME);
430                            }
431    
432                            // Portlets
433    
434                            portletLocalService.checkPortlets(companyId);
435    
436                            final Company finalCompany = company;
437    
438                            TransactionCommitCallbackUtil.registerCallback(
439                                    new Callable<Void>() {
440    
441                                            @Override
442                                            public Void call() throws Exception {
443                                                    registerCompany(finalCompany);
444    
445                                                    return null;
446                                            }
447    
448                                    });
449                    }
450                    finally {
451                            _companyProviderWrapper.setCompanyProvider(currentCompanyProvider);
452                    }
453    
454                    return company;
455            }
456    
457            /**
458             * Checks if the company has an encryption key. It will create a key if one
459             * does not exist.
460             *
461             * @param companyId the primary key of the company
462             */
463            @Override
464            public void checkCompanyKey(long companyId) throws PortalException {
465                    Company company = companyPersistence.findByPrimaryKey(companyId);
466    
467                    if (company.getKeyObj() != null) {
468                            return;
469                    }
470    
471                    try {
472                            company.setKey(Base64.objectToString(Encryptor.generateKey()));
473                    }
474                    catch (EncryptorException ee) {
475                            throw new SystemException(ee);
476                    }
477    
478                    companyPersistence.update(company);
479            }
480    
481            @Override
482            public Company deleteCompany(Company company) throws PortalException {
483                    return deleteCompany(company.getCompanyId());
484            }
485    
486            @Override
487            public Company deleteCompany(long companyId) throws PortalException {
488                    if (companyId == PortalInstances.getDefaultCompanyId()) {
489                            throw new RequiredCompanyException();
490                    }
491    
492                    Long currentCompanyId = CompanyThreadLocal.getCompanyId();
493                    boolean deleteInProcess = CompanyThreadLocal.isDeleteInProcess();
494    
495                    try {
496                            CompanyThreadLocal.setCompanyId(companyId);
497                            CompanyThreadLocal.setDeleteInProcess(true);
498    
499                            return doDeleteCompany(companyId);
500                    }
501                    finally {
502                            CompanyThreadLocal.setCompanyId(currentCompanyId);
503                            CompanyThreadLocal.setDeleteInProcess(deleteInProcess);
504                    }
505            }
506    
507            /**
508             * Deletes the company's logo.
509             *
510             * @param  companyId the primary key of the company
511             * @return the deleted logo's company
512             */
513            @Override
514            public Company deleteLogo(long companyId) throws PortalException {
515                    Company company = companyPersistence.findByPrimaryKey(companyId);
516    
517                    PortalUtil.updateImageId(company, false, null, "logoId", 0, 0, 0);
518    
519                    return company;
520            }
521    
522            /**
523             * Returns the company with the primary key.
524             *
525             * @param  companyId the primary key of the company
526             * @return the company with the primary key, <code>null</code> if a company
527             *         with the primary key could not be found
528             */
529            @Override
530            public Company fetchCompanyById(long companyId) {
531                    return companyPersistence.fetchByPrimaryKey(companyId);
532            }
533    
534            /**
535             * Returns the company with the virtual host name.
536             *
537             * @param  virtualHostname the virtual host name
538             * @return the company with the virtual host name, <code>null</code> if a
539             *         company with the virtual host could not be found
540             */
541            @Override
542            public Company fetchCompanyByVirtualHost(String virtualHostname) {
543                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
544    
545                    VirtualHost virtualHost = virtualHostPersistence.fetchByHostname(
546                            virtualHostname);
547    
548                    if ((virtualHost == null) || (virtualHost.getLayoutSetId() != 0)) {
549                            return null;
550                    }
551    
552                    return companyPersistence.fetchByPrimaryKey(virtualHost.getCompanyId());
553            }
554    
555            /**
556             * Returns all the companies.
557             *
558             * @return the companies
559             */
560            @Override
561            public List<Company> getCompanies() {
562                    return companyPersistence.findAll();
563            }
564    
565            /**
566             * Returns all the companies used by WSRP.
567             *
568             * @param  system whether the company is the very first company (i.e., the
569             *         super company)
570             * @return the companies used by WSRP
571             */
572            @Override
573            public List<Company> getCompanies(boolean system) {
574                    return companyPersistence.findBySystem(system);
575            }
576    
577            @Override
578            public List<Company> getCompanies(boolean system, int start, int end) {
579                    return companyPersistence.findBySystem(system, start, end);
580            }
581    
582            /**
583             * Returns the number of companies used by WSRP.
584             *
585             * @param  system whether the company is the very first company (i.e., the
586             *         super company)
587             * @return the number of companies used by WSRP
588             */
589            @Override
590            public int getCompaniesCount(boolean system) {
591                    return companyPersistence.countBySystem(system);
592            }
593    
594            /**
595             * Returns the company with the primary key.
596             *
597             * @param  companyId the primary key of the company
598             * @return the company with the primary key
599             */
600            @Override
601            public Company getCompanyById(long companyId) throws PortalException {
602                    return companyPersistence.findByPrimaryKey(companyId);
603            }
604    
605            /**
606             * Returns the company with the logo.
607             *
608             * @param  logoId the ID of the company's logo
609             * @return the company with the logo
610             */
611            @Override
612            public Company getCompanyByLogoId(long logoId) throws PortalException {
613                    return companyPersistence.findByLogoId(logoId);
614            }
615    
616            /**
617             * Returns the company with the mail domain.
618             *
619             * @param  mx the company's mail domain
620             * @return the company with the mail domain
621             */
622            @Override
623            public Company getCompanyByMx(String mx) throws PortalException {
624                    return companyPersistence.findByMx(mx);
625            }
626    
627            /**
628             * Returns the company with the virtual host name.
629             *
630             * @param  virtualHostname the company's virtual host name
631             * @return the company with the virtual host name
632             */
633            @Override
634            public Company getCompanyByVirtualHost(String virtualHostname)
635                    throws PortalException {
636    
637                    try {
638                            virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
639    
640                            VirtualHost virtualHost = virtualHostPersistence.findByHostname(
641                                    virtualHostname);
642    
643                            if (virtualHost.getLayoutSetId() != 0) {
644                                    throw new CompanyVirtualHostException(
645                                            "Virtual host is associated with layout set " +
646                                                    virtualHost.getLayoutSetId());
647                            }
648    
649                            return companyPersistence.findByPrimaryKey(
650                                    virtualHost.getCompanyId());
651                    }
652                    catch (NoSuchVirtualHostException nsvhe) {
653                            throw new CompanyVirtualHostException(nsvhe);
654                    }
655            }
656    
657            /**
658             * Returns the company with the web domain.
659             *
660             * @param  webId the company's web domain
661             * @return the company with the web domain
662             */
663            @Override
664            public Company getCompanyByWebId(String webId) throws PortalException {
665                    return companyPersistence.findByWebId(webId);
666            }
667    
668            /**
669             * Returns the user's company.
670             *
671             * @param  userId the primary key of the user
672             * @return Returns the first company if there is only one company or the
673             *         user's company if there are more than one company; <code>0</code>
674             *         otherwise
675             * @throws Exception if a user with the primary key could not be found
676             */
677            @Override
678            public long getCompanyIdByUserId(long userId) throws Exception {
679                    long[] companyIds = PortalInstances.getCompanyIds();
680    
681                    long companyId = 0;
682    
683                    if (companyIds.length == 1) {
684                            companyId = companyIds[0];
685                    }
686                    else if (companyIds.length > 1) {
687                            try {
688                                    User user = userPersistence.findByPrimaryKey(userId);
689    
690                                    companyId = user.getCompanyId();
691                            }
692                            catch (Exception e) {
693                                    if (_log.isWarnEnabled()) {
694                                            _log.warn(
695                                                    "Unable to get the company id for user " + userId, e);
696                                    }
697                            }
698                    }
699    
700                    return companyId;
701            }
702    
703            /**
704             * Removes the values that match the keys of the company's preferences.
705             *
706             * This method is called by {@link
707             * com.liferay.portlet.portalsettings.action.EditLDAPServerAction} remotely
708             * through {@link com.liferay.portal.service.CompanyService}.
709             *
710             * @param companyId the primary key of the company
711             * @param keys the company's preferences keys to be remove
712             */
713            @Override
714            public void removePreferences(long companyId, String[] keys) {
715                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
716                            companyId);
717    
718                    try {
719                            for (String key : keys) {
720                                    preferences.reset(key);
721                            }
722    
723                            preferences.store();
724                    }
725                    catch (Exception e) {
726                            throw new SystemException(e);
727                    }
728            }
729    
730            /**
731             * Returns an ordered range of all assets that match the keywords in the
732             * company.
733             *
734             * The method is called in {@link
735             * com.liferay.portal.search.PortalOpenSearchImpl} which is not longer used
736             * by the Search portlet.
737             *
738             * @param  companyId the primary key of the company
739             * @param  userId the primary key of the user
740             * @param  keywords the keywords (space separated),which may occur in assets
741             *         in the company (optionally <code>null</code>)
742             * @param  start the lower bound of the range of assets to return
743             * @param  end the upper bound of the range of assets to return (not
744             *         inclusive)
745             * @return the matching assets in the company
746             */
747            @Override
748            public Hits search(
749                    long companyId, long userId, String keywords, int start, int end) {
750    
751                    return search(companyId, userId, null, 0, null, keywords, start, end);
752            }
753    
754            /**
755             * Returns an ordered range of all assets that match the keywords in the
756             * portlet within the company.
757             *
758             * @param  companyId the primary key of the company
759             * @param  userId the primary key of the user
760             * @param  portletId the primary key of the portlet (optionally
761             *         <code>null</code>)
762             * @param  groupId the primary key of the group (optionally <code>0</code>)
763             * @param  type the mime type of assets to return(optionally
764             *         <code>null</code>)
765             * @param  keywords the keywords (space separated), which may occur in any
766             *         assets in the portlet (optionally <code>null</code>)
767             * @param  start the lower bound of the range of assets to return
768             * @param  end the upper bound of the range of assets to return (not
769             *         inclusive)
770             * @return the matching assets in the portlet within the company
771             */
772            @Override
773            public Hits search(
774                    long companyId, long userId, String portletId, long groupId,
775                    String type, String keywords, int start, int end) {
776    
777                    try {
778    
779                            // Search context
780    
781                            SearchContext searchContext = new SearchContext();
782    
783                            searchContext.setCompanyId(companyId);
784                            searchContext.setEnd(end);
785                            searchContext.setEntryClassNames(
786                                    SearchEngineHelperUtil.getEntryClassNames());
787    
788                            if (groupId > 0) {
789                                    searchContext.setGroupIds(new long[] {groupId});
790                            }
791    
792                            searchContext.setKeywords(keywords);
793    
794                            if (Validator.isNotNull(portletId)) {
795                                    searchContext.setPortletIds(new String[] {portletId});
796                            }
797    
798                            searchContext.setStart(start);
799                            searchContext.setUserId(userId);
800    
801                            // Always add facets as late as possible so that the search context
802                            // fields can be considered by the facets
803    
804                            Facet assetEntriesFacet = new AssetEntriesFacet(searchContext);
805    
806                            assetEntriesFacet.setStatic(true);
807    
808                            searchContext.addFacet(assetEntriesFacet);
809    
810                            Facet scopeFacet = new ScopeFacet(searchContext);
811    
812                            scopeFacet.setStatic(true);
813    
814                            searchContext.addFacet(scopeFacet);
815    
816                            // Search
817    
818                            Indexer<?> indexer = FacetedSearcher.getInstance();
819    
820                            return indexer.search(searchContext);
821                    }
822                    catch (Exception e) {
823                            throw new SystemException(e);
824                    }
825            }
826    
827            /**
828             * Updates the company.
829             *
830             * @param  companyId the primary key of the company
831             * @param  virtualHostname the company's virtual host name
832             * @param  mx the company's mail domain
833             * @param  maxUsers the max number of company users (optionally
834             *         <code>0</code>)
835             * @param  active whether the company is active
836             * @return the company with the primary key
837             */
838            @Override
839            public Company updateCompany(
840                            long companyId, String virtualHostname, String mx, int maxUsers,
841                            boolean active)
842                    throws PortalException {
843    
844                    // Company
845    
846                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
847    
848                    if (!active) {
849                            if (companyId == PortalInstances.getDefaultCompanyId()) {
850                                    active = true;
851                            }
852                    }
853    
854                    Company company = companyPersistence.findByPrimaryKey(companyId);
855    
856                    validateVirtualHost(company.getWebId(), virtualHostname);
857    
858                    if (PropsValues.MAIL_MX_UPDATE) {
859                            validateMx(mx);
860    
861                            company.setMx(mx);
862                    }
863    
864                    company.setMaxUsers(maxUsers);
865                    company.setActive(active);
866    
867                    companyPersistence.update(company);
868    
869                    // Virtual host
870    
871                    company = updateVirtualHostname(companyId, virtualHostname);
872    
873                    return company;
874            }
875    
876            /**
877             * Update the company with additional account information.
878             *
879             * @param  companyId the primary key of the company
880             * @param  virtualHostname the company's virtual host name
881             * @param  mx the company's mail domain
882             * @param  homeURL the company's home URL (optionally <code>null</code>)
883             * @param  logo whether to update the company's logo
884             * @param  logoBytes the new logo image data
885             * @param  name the company's account name(optionally <code>null</code>)
886             * @param  legalName the company's account legal name (optionally
887             *         <code>null</code>)
888             * @param  legalId the company's account legal ID (optionally
889             *         <code>null</code>)
890             * @param  legalType the company's account legal type (optionally
891             *         <code>null</code>)
892             * @param  sicCode the company's account SIC code (optionally
893             *         <code>null</code>)
894             * @param  tickerSymbol the company's account ticker symbol (optionally
895             *         <code>null</code>)
896             * @param  industry the company's account industry (optionally
897             *         <code>null</code>)
898             * @param  type the company's account type (optionally <code>null</code>)
899             * @param  size the company's account size (optionally <code>null</code>)
900             * @return the company with the primary key
901             */
902            @Override
903            public Company updateCompany(
904                            long companyId, String virtualHostname, String mx, String homeURL,
905                            boolean logo, byte[] logoBytes, String name, String legalName,
906                            String legalId, String legalType, String sicCode,
907                            String tickerSymbol, String industry, String type, String size)
908                    throws PortalException {
909    
910                    // Company
911    
912                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
913    
914                    Company company = companyPersistence.findByPrimaryKey(companyId);
915    
916                    validateVirtualHost(company.getWebId(), virtualHostname);
917    
918                    if (PropsValues.MAIL_MX_UPDATE) {
919                            validateMx(mx);
920                    }
921    
922                    validateName(companyId, name);
923    
924                    if (PropsValues.MAIL_MX_UPDATE) {
925                            company.setMx(mx);
926                    }
927    
928                    company.setHomeURL(homeURL);
929    
930                    PortalUtil.updateImageId(company, logo, logoBytes, "logoId", 0, 0, 0);
931    
932                    companyPersistence.update(company);
933    
934                    // Account
935    
936                    updateAccount(
937                            company, name, legalName, legalId, legalType, sicCode, tickerSymbol,
938                            industry, type, size);
939    
940                    // Virtual host
941    
942                    company = updateVirtualHostname(companyId, virtualHostname);
943    
944                    return company;
945            }
946    
947            /**
948             * Update the company with additional account information.
949             *
950             * @param      companyId the primary key of the company
951             * @param      virtualHostname the company's virtual host name
952             * @param      mx the company's mail domain
953             * @param      homeURL the company's home URL (optionally <code>null</code>)
954             * @param      name the company's account name(optionally <code>null</code>)
955             * @param      legalName the company's account legal name (optionally
956             *             <code>null</code>)
957             * @param      legalId the company's account legal ID (optionally
958             *             <code>null</code>)
959             * @param      legalType the company's account legal type (optionally
960             *             <code>null</code>)
961             * @param      sicCode the company's account SIC code (optionally
962             *             <code>null</code>)
963             * @param      tickerSymbol the company's account ticker symbol (optionally
964             *             <code>null</code>)
965             * @param      industry the company's account industry (optionally
966             *             <code>null</code>)
967             * @param      type the company's account type (optionally
968             *             <code>null</code>)
969             * @param      size the company's account size (optionally
970             *             <code>null</code>)
971             * @return     the company with the primary key
972             * @deprecated As of 7.0.0, replaced by {@link #updateCompany(long, String,
973             *             String, String, boolean, byte[], String, String, String,
974             *             String, String, String, String, String, String)}
975             */
976            @Deprecated
977            @Override
978            public Company updateCompany(
979                            long companyId, String virtualHostname, String mx, String homeURL,
980                            String name, String legalName, String legalId, String legalType,
981                            String sicCode, String tickerSymbol, String industry, String type,
982                            String size)
983                    throws PortalException {
984    
985                    return updateCompany(
986                            companyId, virtualHostname, mx, homeURL, true, null, name,
987                            legalName, legalId, legalType, sicCode, tickerSymbol, industry,
988                            type, size);
989            }
990    
991            /**
992             * Update the company's display.
993             *
994             * @param companyId the primary key of the company
995             * @param languageId the ID of the company's default user's language
996             * @param timeZoneId the ID of the company's default user's time zone
997             */
998            @Override
999            public void updateDisplay(
1000                            long companyId, String languageId, String timeZoneId)
1001                    throws PortalException {
1002    
1003                    User user = userLocalService.getDefaultUser(companyId);
1004    
1005                    user.setLanguageId(languageId);
1006                    user.setTimeZoneId(timeZoneId);
1007    
1008                    userPersistence.update(user);
1009            }
1010    
1011            /**
1012             * Updates the company's logo.
1013             *
1014             * @param  companyId the primary key of the company
1015             * @param  bytes the bytes of the company's logo image
1016             * @return the company with the primary key
1017             */
1018            @Override
1019            public Company updateLogo(long companyId, byte[] bytes)
1020                    throws PortalException {
1021    
1022                    Company company = checkLogo(companyId);
1023    
1024                    imageLocalService.updateImage(company.getLogoId(), bytes);
1025    
1026                    return company;
1027            }
1028    
1029            /**
1030             * Updates the company's logo.
1031             *
1032             * @param  companyId the primary key of the company
1033             * @param  file the file of the company's logo image
1034             * @return the company with the primary key
1035             */
1036            @Override
1037            public Company updateLogo(long companyId, File file)
1038                    throws PortalException {
1039    
1040                    Company company = checkLogo(companyId);
1041    
1042                    imageLocalService.updateImage(company.getLogoId(), file);
1043    
1044                    return company;
1045            }
1046    
1047            /**
1048             * Update the company's logo.
1049             *
1050             * @param  companyId the primary key of the company
1051             * @param  is the input stream of the company's logo image
1052             * @return the company with the primary key
1053             */
1054            @Override
1055            public Company updateLogo(long companyId, InputStream is)
1056                    throws PortalException {
1057    
1058                    Company company = checkLogo(companyId);
1059    
1060                    imageLocalService.updateImage(company.getLogoId(), is);
1061    
1062                    return company;
1063            }
1064    
1065            /**
1066             * Updates the company's preferences. The company's default properties are
1067             * found in portal.properties.
1068             *
1069             * @param companyId the primary key of the company
1070             * @param properties the company's properties. See {@link UnicodeProperties}
1071             */
1072            @Override
1073            public void updatePreferences(long companyId, UnicodeProperties properties)
1074                    throws PortalException {
1075    
1076                    PortletPreferences portletPreferences = PrefsPropsUtil.getPreferences(
1077                            companyId);
1078    
1079                    try {
1080                            String newLanguageIds = properties.getProperty(PropsKeys.LOCALES);
1081    
1082                            if (Validator.isNotNull(newLanguageIds)) {
1083                                    String oldLanguageIds = portletPreferences.getValue(
1084                                            PropsKeys.LOCALES, StringPool.BLANK);
1085    
1086                                    if (!Validator.equals(oldLanguageIds, newLanguageIds)) {
1087                                            validateLanguageIds(newLanguageIds);
1088    
1089                                            LanguageUtil.resetAvailableLocales(companyId);
1090    
1091                                            // Invalidate cache of all layout set prototypes that belong
1092                                            // to this company. See LPS-36403.
1093    
1094                                            Date now = new Date();
1095    
1096                                            for (LayoutSetPrototype layoutSetPrototype :
1097                                                            layoutSetPrototypeLocalService.
1098                                                                    getLayoutSetPrototypes(companyId)) {
1099    
1100                                                    layoutSetPrototype.setModifiedDate(now);
1101    
1102                                                    layoutSetPrototypeLocalService.updateLayoutSetPrototype(
1103                                                            layoutSetPrototype);
1104                                            }
1105                                    }
1106                            }
1107    
1108                            List<String> resetKeys = new ArrayList<>();
1109    
1110                            for (Map.Entry<String, String> entry : properties.entrySet()) {
1111                                    String key = entry.getKey();
1112                                    String value = entry.getValue();
1113    
1114                                    if (value.equals(Portal.TEMP_OBFUSCATION_VALUE)) {
1115                                            continue;
1116                                    }
1117    
1118                                    String propsUtilValue = PropsUtil.get(key);
1119    
1120                                    if (!value.equals(propsUtilValue)) {
1121                                            portletPreferences.setValue(key, value);
1122                                    }
1123                                    else {
1124                                            String portletPreferencesValue =
1125                                                    portletPreferences.getValue(key, null);
1126    
1127                                            if (portletPreferencesValue != null) {
1128                                                    resetKeys.add(key);
1129                                            }
1130                                    }
1131                            }
1132    
1133                            for (String key : resetKeys) {
1134                                    portletPreferences.reset(key);
1135                            }
1136    
1137                            portletPreferences.store();
1138                    }
1139                    catch (LocaleException le) {
1140                            throw le;
1141                    }
1142                    catch (Exception e) {
1143                            throw new SystemException(e);
1144                    }
1145            }
1146    
1147            /**
1148             * Updates the company's security properties.
1149             *
1150             * @param companyId the primary key of the company
1151             * @param authType the company's method of authenticating users
1152             * @param autoLogin whether to allow users to select the "remember me"
1153             *        feature
1154             * @param sendPassword whether to allow users to ask the company to send
1155             *        their password
1156             * @param strangers whether to allow strangers to create accounts register
1157             *        themselves in the company
1158             * @param strangersWithMx whether to allow strangers to create accounts with
1159             *        email addresses that match the company mail suffix
1160             * @param strangersVerify whether to require strangers who create accounts
1161             *        to be verified via email
1162             * @param siteLogo whether to allow site administrators to use their own
1163             *        logo instead of the enterprise logo
1164             */
1165            @Override
1166            public void updateSecurity(
1167                    long companyId, String authType, boolean autoLogin,
1168                    boolean sendPassword, boolean strangers, boolean strangersWithMx,
1169                    boolean strangersVerify, boolean siteLogo) {
1170    
1171                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
1172                            companyId);
1173    
1174                    try {
1175                            preferences.setValue(
1176                                    PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
1177                            preferences.setValue(
1178                                    PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
1179                                    String.valueOf(autoLogin));
1180                            preferences.setValue(
1181                                    PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
1182                                    String.valueOf(sendPassword));
1183                            preferences.setValue(
1184                                    PropsKeys.COMPANY_SECURITY_STRANGERS,
1185                                    String.valueOf(strangers));
1186                            preferences.setValue(
1187                                    PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
1188                                    String.valueOf(strangersWithMx));
1189                            preferences.setValue(
1190                                    PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
1191                                    String.valueOf(strangersVerify));
1192                            preferences.setValue(
1193                                    PropsKeys.COMPANY_SECURITY_SITE_LOGO, String.valueOf(siteLogo));
1194    
1195                            preferences.store();
1196                    }
1197                    catch (IOException | PortletException e) {
1198                            throw new SystemException(e);
1199                    }
1200            }
1201    
1202            protected Company checkLogo(long companyId) throws PortalException {
1203                    Company company = companyPersistence.findByPrimaryKey(companyId);
1204    
1205                    long logoId = company.getLogoId();
1206    
1207                    if (logoId <= 0) {
1208                            logoId = counterLocalService.increment();
1209    
1210                            company.setLogoId(logoId);
1211    
1212                            company = companyPersistence.update(company);
1213                    }
1214    
1215                    return company;
1216            }
1217    
1218            protected Company doDeleteCompany(final long companyId)
1219                    throws PortalException {
1220    
1221                    // Company
1222    
1223                    final Company company = companyPersistence.remove(companyId);
1224    
1225                    // Account
1226    
1227                    accountLocalService.deleteAccount(company.getAccountId());
1228    
1229                    // Groups
1230    
1231                    DeleteGroupActionableDynamicQuery deleteGroupActionableDynamicQuery =
1232                            new DeleteGroupActionableDynamicQuery();
1233    
1234                    deleteGroupActionableDynamicQuery.setCompanyId(companyId);
1235    
1236                    deleteGroupActionableDynamicQuery.performActions();
1237    
1238                    String[] systemGroups = PortalUtil.getSystemGroups();
1239    
1240                    for (String groupName : systemGroups) {
1241                            Group group = groupLocalService.getGroup(companyId, groupName);
1242    
1243                            deleteGroupActionableDynamicQuery.deleteGroup(group);
1244                    }
1245    
1246                    Group companyGroup = groupLocalService.getCompanyGroup(companyId);
1247    
1248                    deleteGroupActionableDynamicQuery.deleteGroup(companyGroup);
1249    
1250                    // Layout prototype
1251    
1252                    ActionableDynamicQuery layoutPrototypeActionableDynamicQuery =
1253                            layoutPrototypeLocalService.getActionableDynamicQuery();
1254    
1255                    layoutPrototypeActionableDynamicQuery.setCompanyId(companyId);
1256                    layoutPrototypeActionableDynamicQuery.setPerformActionMethod(
1257                            new ActionableDynamicQuery.PerformActionMethod<LayoutPrototype>() {
1258    
1259                                    @Override
1260                                    public void performAction(LayoutPrototype layoutPrototype)
1261                                            throws PortalException {
1262    
1263                                            layoutPrototypeLocalService.deleteLayoutPrototype(
1264                                                    layoutPrototype);
1265                                    }
1266    
1267                            });
1268    
1269                    layoutPrototypeActionableDynamicQuery.performActions();
1270    
1271                    // Layout set prototype
1272    
1273                    ActionableDynamicQuery layoutSetPrototypeActionableDynamicQuery =
1274                            layoutSetPrototypeLocalService.getActionableDynamicQuery();
1275    
1276                    layoutSetPrototypeActionableDynamicQuery.setCompanyId(companyId);
1277                    layoutSetPrototypeActionableDynamicQuery.setPerformActionMethod(
1278                            new ActionableDynamicQuery.
1279                                    PerformActionMethod<LayoutSetPrototype>() {
1280    
1281                                    @Override
1282                                    public void performAction(LayoutSetPrototype layoutSetPrototype)
1283                                            throws PortalException {
1284    
1285                                            layoutSetPrototypeLocalService.deleteLayoutSetPrototype(
1286                                                    layoutSetPrototype);
1287                                    }
1288    
1289                            });
1290    
1291                    layoutSetPrototypeActionableDynamicQuery.performActions();
1292    
1293                    // Organizations
1294    
1295                    DeleteOrganizationActionableDynamicQuery
1296                            deleteOrganizationActionableDynamicQuery =
1297                                    new DeleteOrganizationActionableDynamicQuery();
1298    
1299                    deleteOrganizationActionableDynamicQuery.setCompanyId(companyId);
1300    
1301                    deleteOrganizationActionableDynamicQuery.performActions();
1302    
1303                    // Roles
1304    
1305                    ActionableDynamicQuery roleActionableDynamicQuery =
1306                            roleLocalService.getActionableDynamicQuery();
1307    
1308                    roleActionableDynamicQuery.setCompanyId(companyId);
1309                    roleActionableDynamicQuery.setPerformActionMethod(
1310                            new ActionableDynamicQuery.PerformActionMethod<Role>() {
1311    
1312                                    @Override
1313                                    public void performAction(Role role) throws PortalException {
1314                                            roleLocalService.deleteRole(role);
1315                                    }
1316    
1317                            });
1318    
1319                    roleActionableDynamicQuery.performActions();
1320    
1321                    // Password policy
1322    
1323                    passwordPolicyLocalService.deleteNondefaultPasswordPolicies(companyId);
1324    
1325                    PasswordPolicy defaultPasswordPolicy =
1326                            passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
1327    
1328                    if (defaultPasswordPolicy != null) {
1329                            passwordPolicyLocalService.deletePasswordPolicy(
1330                                    defaultPasswordPolicy);
1331                    }
1332    
1333                    // Portal preferences
1334    
1335                    PortalPreferences portalPreferences =
1336                            portalPreferencesPersistence.findByO_O(
1337                                    companyId, PortletKeys.PREFS_OWNER_TYPE_COMPANY);
1338    
1339                    portalPreferencesLocalService.deletePortalPreferences(
1340                            portalPreferences);
1341    
1342                    // Portlets
1343    
1344                    List<Portlet> portlets = portletPersistence.findByCompanyId(companyId);
1345    
1346                    for (Portlet portlet : portlets) {
1347                            portletLocalService.deletePortlet(portlet.getId());
1348                    }
1349    
1350                    portletLocalService.removeCompanyPortletsPool(companyId);
1351    
1352                    // Users
1353    
1354                    ActionableDynamicQuery userActionableDynamicQuery =
1355                            userLocalService.getActionableDynamicQuery();
1356    
1357                    userActionableDynamicQuery.setCompanyId(companyId);
1358                    userActionableDynamicQuery.setPerformActionMethod(
1359                            new ActionableDynamicQuery.PerformActionMethod<User>() {
1360    
1361                                    @Override
1362                                    public void performAction(User user) throws PortalException {
1363                                            if (!user.isDefaultUser()) {
1364                                                    userLocalService.deleteUser(user.getUserId());
1365                                            }
1366                                    }
1367    
1368                            });
1369    
1370                    userActionableDynamicQuery.performActions();
1371    
1372                    User defaultUser = userLocalService.getDefaultUser(companyId);
1373    
1374                    userLocalService.deleteUser(defaultUser);
1375    
1376                    // Virtual host
1377    
1378                    VirtualHost companyVirtualHost =
1379                            virtualHostLocalService.fetchVirtualHost(companyId, 0);
1380    
1381                    virtualHostLocalService.deleteVirtualHost(companyVirtualHost);
1382    
1383                    // Portal instance
1384    
1385                    Callable<Void> callable = new Callable<Void>() {
1386    
1387                            @Override
1388                            public Void call() throws Exception {
1389                                    PortalInstances.removeCompany(companyId);
1390    
1391                                    unregisterCompany(company);
1392    
1393                                    return null;
1394                            }
1395    
1396                    };
1397    
1398                    TransactionCommitCallbackUtil.registerCallback(callable);
1399    
1400                    return company;
1401            }
1402    
1403            protected void registerCompany(Company company) {
1404                    PortalInstanceLifecycleManager portalInstanceLifecycleManager =
1405                            _serviceTracker.getService();
1406    
1407                    if (portalInstanceLifecycleManager != null) {
1408                            portalInstanceLifecycleManager.registerCompany(company);
1409                    }
1410                    else {
1411                            synchronized (_pendingCompanies) {
1412                                    _pendingCompanies.add(company);
1413                            }
1414                    }
1415            }
1416    
1417            protected void unregisterCompany(Company company) {
1418                    PortalInstanceLifecycleManager portalInstanceLifecycleManager =
1419                            _serviceTracker.getService();
1420    
1421                    if (portalInstanceLifecycleManager != null) {
1422                            portalInstanceLifecycleManager.unregisterCompany(company);
1423                    }
1424            }
1425    
1426            protected void updateAccount(
1427                    Company company, String name, String legalName, String legalId,
1428                    String legalType, String sicCode, String tickerSymbol, String industry,
1429                    String type, String size) {
1430    
1431                    Account account = accountPersistence.fetchByPrimaryKey(
1432                            company.getAccountId());
1433    
1434                    if (account == null) {
1435                            long accountId = counterLocalService.increment();
1436    
1437                            account = accountPersistence.create(accountId);
1438    
1439                            account.setCompanyId(company.getCompanyId());
1440                            account.setUserId(0);
1441                            account.setUserName(StringPool.BLANK);
1442    
1443                            company.setAccountId(accountId);
1444    
1445                            companyPersistence.update(company);
1446                    }
1447    
1448                    account.setName(name);
1449                    account.setLegalName(legalName);
1450                    account.setLegalId(legalId);
1451                    account.setLegalType(legalType);
1452                    account.setSicCode(sicCode);
1453                    account.setTickerSymbol(tickerSymbol);
1454                    account.setIndustry(industry);
1455                    account.setType(type);
1456                    account.setSize(size);
1457    
1458                    accountPersistence.update(account);
1459            }
1460    
1461            protected Company updateVirtualHostname(
1462                            long companyId, String virtualHostname)
1463                    throws CompanyVirtualHostException {
1464    
1465                    if (Validator.isNotNull(virtualHostname)) {
1466                            VirtualHost virtualHost = virtualHostPersistence.fetchByHostname(
1467                                    virtualHostname);
1468    
1469                            if (virtualHost == null) {
1470                                    virtualHostLocalService.updateVirtualHost(
1471                                            companyId, 0, virtualHostname);
1472                            }
1473                            else {
1474                                    if ((virtualHost.getCompanyId() != companyId) ||
1475                                            (virtualHost.getLayoutSetId() != 0)) {
1476    
1477                                            throw new CompanyVirtualHostException();
1478                                    }
1479                            }
1480                    }
1481                    else {
1482                            VirtualHost virtualHost = virtualHostPersistence.fetchByC_L(
1483                                    companyId, 0);
1484    
1485                            if (virtualHost != null) {
1486                                    virtualHostPersistence.remove(virtualHost);
1487                            }
1488                    }
1489    
1490                    return companyPersistence.fetchByPrimaryKey(companyId);
1491            }
1492    
1493            protected void validateLanguageIds(String languageIds)
1494                    throws PortalException {
1495    
1496                    String[] languageIdsArray = StringUtil.split(
1497                            languageIds, StringPool.COMMA);
1498    
1499                    for (String languageId : languageIdsArray) {
1500                            if (!ArrayUtil.contains(PropsValues.LOCALES, languageId)) {
1501                                    LocaleException le = new LocaleException(
1502                                            LocaleException.TYPE_DISPLAY_SETTINGS);
1503    
1504                                    le.setSourceAvailableLocales(
1505                                            Arrays.asList(
1506                                                    LocaleUtil.fromLanguageIds(PropsValues.LOCALES)));
1507                                    le.setTargetAvailableLocales(
1508                                            Arrays.asList(
1509                                                    LocaleUtil.fromLanguageIds(languageIdsArray)));
1510    
1511                                    throw le;
1512                            }
1513                    }
1514            }
1515    
1516            protected void validateMx(String mx) throws PortalException {
1517                    if (Validator.isNull(mx) || !Validator.isDomain(mx)) {
1518                            throw new CompanyMxException();
1519                    }
1520            }
1521    
1522            protected void validateName(long companyId, String name)
1523                    throws PortalException {
1524    
1525                    Group group = groupLocalService.fetchGroup(companyId, name);
1526    
1527                    if ((group != null) || Validator.isNull(name)) {
1528                            throw new AccountNameException();
1529                    }
1530            }
1531    
1532            protected void validateVirtualHost(String webId, String virtualHostname)
1533                    throws PortalException {
1534    
1535                    if (Validator.isNull(virtualHostname)) {
1536                            throw new CompanyVirtualHostException();
1537                    }
1538                    else if (virtualHostname.equals(_DEFAULT_VIRTUAL_HOST) &&
1539                                     !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
1540    
1541                            throw new CompanyVirtualHostException();
1542                    }
1543                    else if (!Validator.isDomain(virtualHostname)) {
1544                            throw new CompanyVirtualHostException();
1545                    }
1546                    else {
1547                            try {
1548                                    VirtualHost virtualHost = virtualHostPersistence.findByHostname(
1549                                            virtualHostname);
1550    
1551                                    long companyId = virtualHost.getCompanyId();
1552    
1553                                    Company virtualHostnameCompany =
1554                                            companyPersistence.findByPrimaryKey(companyId);
1555    
1556                                    if (!webId.equals(virtualHostnameCompany.getWebId())) {
1557                                            throw new CompanyVirtualHostException();
1558                                    }
1559                            }
1560                            catch (NoSuchVirtualHostException nsvhe) {
1561                            }
1562                    }
1563            }
1564    
1565            protected class DeleteGroupActionableDynamicQuery {
1566    
1567                    protected DeleteGroupActionableDynamicQuery() {
1568                            _actionableDynamicQuery =
1569                                    groupLocalService.getActionableDynamicQuery();
1570    
1571                            _actionableDynamicQuery.setAddCriteriaMethod(
1572                                    new ActionableDynamicQuery.AddCriteriaMethod() {
1573    
1574                                            @Override
1575                                            public void addCriteria(DynamicQuery dynamicQuery) {
1576                                                    Property parentGroupIdProperty =
1577                                                            PropertyFactoryUtil.forName("parentGroupId");
1578    
1579                                                    dynamicQuery.add(
1580                                                            parentGroupIdProperty.eq(_parentGroupId));
1581    
1582                                                    Property siteProperty = PropertyFactoryUtil.forName(
1583                                                            "site");
1584    
1585                                                    dynamicQuery.add(siteProperty.eq(Boolean.TRUE));
1586                                            }
1587    
1588                                    });
1589                            _actionableDynamicQuery.setPerformActionMethod(
1590                                    new ActionableDynamicQuery.PerformActionMethod<Group>() {
1591    
1592                                            @Override
1593                                            public void performAction(Group group)
1594                                                    throws PortalException {
1595    
1596                                                    if (!PortalUtil.isSystemGroup(group.getGroupKey()) &&
1597                                                            !group.isCompany()) {
1598    
1599                                                            deleteGroup(group);
1600                                                    }
1601                                            }
1602    
1603                                    });
1604                    }
1605    
1606                    protected void deleteGroup(Group group) throws PortalException {
1607                            DeleteGroupActionableDynamicQuery
1608                                    deleteGroupActionableDynamicQuery =
1609                                            new DeleteGroupActionableDynamicQuery();
1610    
1611                            deleteGroupActionableDynamicQuery.setCompanyId(
1612                                    group.getCompanyId());
1613                            deleteGroupActionableDynamicQuery.setParentGroupId(
1614                                    group.getGroupId());
1615    
1616                            deleteGroupActionableDynamicQuery.performActions();
1617    
1618                            groupLocalService.deleteGroup(group);
1619    
1620                            LiveUsers.deleteGroup(group.getCompanyId(), group.getGroupId());
1621                    }
1622    
1623                    protected void performActions() throws PortalException {
1624                            _actionableDynamicQuery.performActions();
1625                    }
1626    
1627                    protected void setCompanyId(long companyId) {
1628                            _actionableDynamicQuery.setCompanyId(companyId);
1629                    }
1630    
1631                    protected void setParentGroupId(long parentGroupId) {
1632                            _parentGroupId = parentGroupId;
1633                    }
1634    
1635                    private ActionableDynamicQuery _actionableDynamicQuery;
1636                    private long _parentGroupId = GroupConstants.DEFAULT_PARENT_GROUP_ID;
1637    
1638            }
1639    
1640            protected class DeleteOrganizationActionableDynamicQuery {
1641    
1642                    public void setParentOrganizationId(long parentOrganizationId) {
1643                            _parentOrganizationId = parentOrganizationId;
1644                    }
1645    
1646                    protected DeleteOrganizationActionableDynamicQuery() {
1647                            _actionableDynamicQuery =
1648                                    organizationLocalService.getActionableDynamicQuery();
1649    
1650                            _actionableDynamicQuery.setAddCriteriaMethod(
1651                                    new ActionableDynamicQuery.AddCriteriaMethod() {
1652    
1653                                            @Override
1654                                            public void addCriteria(DynamicQuery dynamicQuery) {
1655                                                    Property property = PropertyFactoryUtil.forName(
1656                                                            "parentOrganizationId");
1657    
1658                                                    dynamicQuery.add(property.eq(_parentOrganizationId));
1659                                            }
1660    
1661                                    });
1662                            _actionableDynamicQuery.setPerformActionMethod(
1663                                    new ActionableDynamicQuery.PerformActionMethod<Organization>() {
1664    
1665                                            @Override
1666                                            public void performAction(Organization organization)
1667                                                    throws PortalException {
1668    
1669                                                    deleteOrganization(organization);
1670                                            }
1671    
1672                                    });
1673                    }
1674    
1675                    protected void deleteOrganization(Organization organization)
1676                            throws PortalException {
1677    
1678                            DeleteOrganizationActionableDynamicQuery
1679                                    deleteOrganizationActionableDynamicQuery =
1680                                            new DeleteOrganizationActionableDynamicQuery();
1681    
1682                            deleteOrganizationActionableDynamicQuery.setCompanyId(
1683                                    organization.getCompanyId());
1684                            deleteOrganizationActionableDynamicQuery.setParentOrganizationId(
1685                                    organization.getOrganizationId());
1686    
1687                            deleteOrganizationActionableDynamicQuery.performActions();
1688    
1689                            organizationLocalService.deleteOrganization(organization);
1690                    }
1691    
1692                    protected void performActions() throws PortalException {
1693                            _actionableDynamicQuery.performActions();
1694                    }
1695    
1696                    protected void setCompanyId(long companyId) {
1697                            _actionableDynamicQuery.setCompanyId(companyId);
1698                    }
1699    
1700                    private ActionableDynamicQuery _actionableDynamicQuery;
1701                    private long _parentOrganizationId =
1702                            OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID;
1703    
1704            }
1705    
1706            private static final String _DEFAULT_VIRTUAL_HOST = "localhost";
1707    
1708            private static final Log _log = LogFactoryUtil.getLog(
1709                    CompanyLocalServiceImpl.class);
1710    
1711            @BeanReference(type = CompanyProviderWrapper.class)
1712            private CompanyProviderWrapper _companyProviderWrapper;
1713    
1714            private final Set<Company> _pendingCompanies = new HashSet<>();
1715            private final ServiceTracker
1716                    <PortalInstanceLifecycleManager, PortalInstanceLifecycleManager>
1717                            _serviceTracker;
1718    
1719            private static class CustomCompanyProvider implements CompanyProvider {
1720    
1721                    public CustomCompanyProvider(long companyId) {
1722                            _companyId = companyId;
1723                    }
1724    
1725                    @Override
1726                    public long getCompanyId() {
1727                            return _companyId;
1728                    }
1729    
1730                    @Override
1731                    public String getCompanyIdName() {
1732                            return "companyId";
1733                    }
1734    
1735                    private final long _companyId;
1736    
1737            }
1738    
1739            private class PortalInstanceLifecycleManagerServiceTrackerCustomizer
1740                    implements ServiceTrackerCustomizer
1741                            <PortalInstanceLifecycleManager, PortalInstanceLifecycleManager> {
1742    
1743                    @Override
1744                    public PortalInstanceLifecycleManager addingService(
1745                            ServiceReference<PortalInstanceLifecycleManager> serviceReference) {
1746    
1747                            Registry registry = RegistryUtil.getRegistry();
1748    
1749                            PortalInstanceLifecycleManager portalInstanceLifecycleManager =
1750                                    registry.getService(serviceReference);
1751    
1752                            synchronized (_pendingCompanies) {
1753                                    for (Company company : _pendingCompanies) {
1754                                            portalInstanceLifecycleManager.registerCompany(company);
1755                                    }
1756    
1757                                    _pendingCompanies.clear();
1758                            }
1759    
1760                            return portalInstanceLifecycleManager;
1761                    }
1762    
1763                    @Override
1764                    public void modifiedService(
1765                            ServiceReference<PortalInstanceLifecycleManager> serviceReference,
1766                            PortalInstanceLifecycleManager portalInstanceLifecycleManager) {
1767    
1768                            removedService(serviceReference, portalInstanceLifecycleManager);
1769    
1770                            addingService(serviceReference);
1771                    }
1772    
1773                    @Override
1774                    public void removedService(
1775                            ServiceReference<PortalInstanceLifecycleManager> serviceReference,
1776                            PortalInstanceLifecycleManager portalInstanceLifecycleManager) {
1777                    }
1778    
1779            }
1780    
1781    }