001    /**
002     * Copyright (c) 2000-2012 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.util;
016    
017    import com.liferay.portal.NoSuchCompanyException;
018    import com.liferay.portal.events.EventsProcessorUtil;
019    import com.liferay.portal.kernel.dao.jdbc.DataAccess;
020    import com.liferay.portal.kernel.dao.shard.ShardUtil;
021    import com.liferay.portal.kernel.log.Log;
022    import com.liferay.portal.kernel.log.LogFactoryUtil;
023    import com.liferay.portal.kernel.util.ArrayUtil;
024    import com.liferay.portal.kernel.util.GetterUtil;
025    import com.liferay.portal.kernel.util.HttpUtil;
026    import com.liferay.portal.kernel.util.PropsKeys;
027    import com.liferay.portal.kernel.util.SetUtil;
028    import com.liferay.portal.kernel.util.Validator;
029    import com.liferay.portal.model.Company;
030    import com.liferay.portal.model.Group;
031    import com.liferay.portal.model.LayoutSet;
032    import com.liferay.portal.model.PortletCategory;
033    import com.liferay.portal.model.VirtualHost;
034    import com.liferay.portal.search.lucene.LuceneHelperUtil;
035    import com.liferay.portal.security.auth.CompanyThreadLocal;
036    import com.liferay.portal.security.ldap.LDAPSettingsUtil;
037    import com.liferay.portal.security.ldap.PortalLDAPImporterUtil;
038    import com.liferay.portal.service.CompanyLocalServiceUtil;
039    import com.liferay.portal.service.GroupLocalServiceUtil;
040    import com.liferay.portal.service.LayoutSetLocalServiceUtil;
041    import com.liferay.portal.service.PortletLocalServiceUtil;
042    import com.liferay.portal.service.VirtualHostLocalServiceUtil;
043    import com.liferay.portlet.journal.service.JournalContentSearchLocalServiceUtil;
044    
045    import java.sql.Connection;
046    import java.sql.PreparedStatement;
047    import java.sql.ResultSet;
048    import java.sql.SQLException;
049    
050    import java.util.ArrayList;
051    import java.util.List;
052    import java.util.Set;
053    
054    import javax.servlet.ServletContext;
055    import javax.servlet.http.HttpServletRequest;
056    
057    /**
058     * @author Brian Wing Shun Chan
059     * @author Jose Oliver
060     * @author Atul Patel
061     * @author Mika Koivisto
062     */
063    public class PortalInstances {
064    
065            public static void addCompanyId(long companyId) {
066                    _instance._addCompanyId(companyId);
067            }
068    
069            public static long getCompanyId(HttpServletRequest request) {
070                    return _instance._getCompanyId(request);
071            }
072    
073            public static long[] getCompanyIds() {
074                    return _instance._getCompanyIds();
075            }
076    
077            public static long[] getCompanyIdsBySQL() throws SQLException {
078                    return _instance._getCompanyIdsBySQL();
079            }
080    
081            public static long getDefaultCompanyId() {
082                    return _instance._getDefaultCompanyId();
083            }
084    
085            public static String[] getWebIds() {
086                    return _instance._getWebIds();
087            }
088    
089            public static long initCompany(
090                    ServletContext servletContext, String webId) {
091    
092                    return _instance._initCompany(servletContext, webId);
093            }
094    
095            public static boolean isAutoLoginIgnoreHost(String host) {
096                    return _instance._isAutoLoginIgnoreHost(host);
097            }
098    
099            public static boolean isAutoLoginIgnorePath(String path) {
100                    return _instance._isAutoLoginIgnorePath(path);
101            }
102    
103            public static boolean isCompanyActive(long companyId) {
104                    return _instance._isCompanyActive(companyId);
105            }
106    
107            public static boolean isVirtualHostsIgnoreHost(String host) {
108                    return _instance._isVirtualHostsIgnoreHost(host);
109            }
110    
111            public static boolean isVirtualHostsIgnorePath(String path) {
112                    return _instance._isVirtualHostsIgnorePath(path);
113            }
114    
115            public static void reload(ServletContext servletContext) {
116                    _instance._reload(servletContext);
117            }
118    
119            private PortalInstances() {
120                    _companyIds = new long[0];
121                    _autoLoginIgnoreHosts = SetUtil.fromArray(
122                            PropsUtil.getArray(PropsKeys.AUTO_LOGIN_IGNORE_HOSTS));
123                    _autoLoginIgnorePaths = SetUtil.fromArray(
124                            PropsUtil.getArray(PropsKeys.AUTO_LOGIN_IGNORE_PATHS));
125                    _virtualHostsIgnoreHosts = SetUtil.fromArray(
126                            PropsUtil.getArray(PropsKeys.VIRTUAL_HOSTS_IGNORE_HOSTS));
127                    _virtualHostsIgnorePaths = SetUtil.fromArray(
128                            PropsUtil.getArray(PropsKeys.VIRTUAL_HOSTS_IGNORE_PATHS));
129            }
130    
131            private void _addCompanyId(long companyId) {
132                    if (ArrayUtil.contains(_companyIds, companyId)) {
133                            return;
134                    }
135    
136                    long[] companyIds = new long[_companyIds.length + 1];
137    
138                    System.arraycopy(_companyIds, 0, companyIds, 0, _companyIds.length);
139    
140                    companyIds[_companyIds.length] = companyId;
141    
142                    _companyIds = companyIds;
143            }
144    
145            private long _getCompanyId(HttpServletRequest request) {
146                    if (_log.isDebugEnabled()) {
147                            _log.debug("Get company id");
148                    }
149    
150                    Long companyIdObj = (Long)request.getAttribute(WebKeys.COMPANY_ID);
151    
152                    if (_log.isDebugEnabled()) {
153                            _log.debug("Company id from request " + companyIdObj);
154                    }
155    
156                    if (companyIdObj != null) {
157                            return companyIdObj.longValue();
158                    }
159    
160                    long companyId = _getCompanyIdByVirtualHosts(request);
161    
162                    if (_log.isDebugEnabled()) {
163                            _log.debug("Company id from host " + companyId);
164                    }
165    
166                    if (companyId <= 0) {
167                            long cookieCompanyId = GetterUtil.getLong(
168                                    CookieKeys.getCookie(request, CookieKeys.COMPANY_ID, false));
169    
170                            if (cookieCompanyId > 0) {
171                                    try {
172                                            CompanyLocalServiceUtil.getCompanyById(cookieCompanyId);
173    
174                                            companyId = cookieCompanyId;
175    
176                                            if (_log.isDebugEnabled()) {
177                                                    _log.debug("Company id from cookie " + companyId);
178                                            }
179                                    }
180                                    catch (NoSuchCompanyException nsce) {
181                                            if (_log.isWarnEnabled()) {
182                                                    _log.warn(
183                                                            "Company id from cookie " + cookieCompanyId +
184                                                                    " does not exist");
185                                            }
186                                    }
187                                    catch (Exception e) {
188                                            _log.error(e, e);
189                                    }
190                            }
191                    }
192    
193                    if (companyId <= 0) {
194                            companyId = _getDefaultCompanyId();
195    
196                            if (_log.isDebugEnabled()) {
197                                    _log.debug("Default company id " + companyId);
198                            }
199                    }
200    
201                    if (_log.isDebugEnabled()) {
202                            _log.debug("Set company id " + companyId);
203                    }
204    
205                    request.setAttribute(WebKeys.COMPANY_ID, new Long(companyId));
206    
207                    CompanyThreadLocal.setCompanyId(companyId);
208    
209                    if (Validator.isNotNull(PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME) &&
210                            (request.getAttribute(WebKeys.VIRTUAL_HOST_LAYOUT_SET) == null)) {
211    
212                            try {
213                                    Group group = GroupLocalServiceUtil.getGroup(
214                                            companyId, PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME);
215    
216                                    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(
217                                            group.getGroupId(), false);
218    
219                                    if (Validator.isNull(layoutSet.getVirtualHostname())) {
220                                            request.setAttribute(
221                                                    WebKeys.VIRTUAL_HOST_LAYOUT_SET, layoutSet);
222                                    }
223                            }
224                            catch (Exception e) {
225                                    _log.error(e, e);
226                            }
227                    }
228    
229                    return companyId;
230            }
231    
232            private long _getCompanyIdByVirtualHosts(HttpServletRequest request) {
233                    String host = PortalUtil.getHost(request);
234    
235                    if (_log.isDebugEnabled()) {
236                            _log.debug("Host " + host);
237                    }
238    
239                    if (Validator.isNull(host) || _isVirtualHostsIgnoreHost(host)) {
240                            return 0;
241                    }
242    
243                    try {
244                            VirtualHost virtualHost =
245                                    VirtualHostLocalServiceUtil.fetchVirtualHost(host);
246    
247                            if (virtualHost == null) {
248                                    return 0;
249                            }
250    
251                            if (virtualHost.getLayoutSetId() != 0) {
252                                    LayoutSet layoutSet = null;
253    
254                                    try {
255                                            ShardUtil.pushCompanyService(virtualHost.getCompanyId());
256    
257                                            layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(
258                                                    virtualHost.getLayoutSetId());
259                                    }
260                                    finally {
261                                            ShardUtil.popCompanyService();
262                                    }
263    
264                                    if (_log.isDebugEnabled()) {
265                                            _log.debug(
266                                                    "Company " + virtualHost.getCompanyId() +
267                                                            " is associated with layout set " +
268                                                                    virtualHost.getLayoutSetId());
269                                    }
270    
271                                    request.setAttribute(
272                                            WebKeys.VIRTUAL_HOST_LAYOUT_SET, layoutSet);
273                            }
274    
275                            return virtualHost.getCompanyId();
276                    }
277                    catch (Exception e) {
278                            _log.error(e, e);
279                    }
280    
281                    return 0;
282            }
283    
284            private long[] _getCompanyIds() {
285                    return _companyIds;
286            }
287    
288            private long[] _getCompanyIdsBySQL() throws SQLException {
289                    List<Long> companyIds = new ArrayList<Long>();
290    
291                    Connection con = null;
292                    PreparedStatement ps = null;
293                    ResultSet rs = null;
294    
295                    try {
296                            con = DataAccess.getConnection();
297    
298                            ps = con.prepareStatement(_GET_COMPANY_IDS);
299    
300                            rs = ps.executeQuery();
301    
302                            while (rs.next()) {
303                                    long companyId = rs.getLong("companyId");
304    
305                                    companyIds.add(companyId);
306                            }
307                    }
308                    finally {
309                            DataAccess.cleanUp(con, ps, rs);
310                    }
311    
312                    return ArrayUtil.toArray(
313                            companyIds.toArray(new Long[companyIds.size()]));
314            }
315    
316            private long _getDefaultCompanyId() {
317                    return _companyIds[0];
318            }
319    
320            private String[] _getWebIds() {
321                    if (_webIds != null) {
322                            return _webIds;
323                    }
324    
325                    if (Validator.isNull(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
326                            throw new RuntimeException("Default web id must not be null");
327                    }
328    
329                    try {
330                            List<Company> companies = CompanyLocalServiceUtil.getCompanies(
331                                    false);
332    
333                            List<String> webIdsList = new ArrayList<String>(companies.size());
334    
335                            for (Company company : companies) {
336                                    String webId = company.getWebId();
337    
338                                    if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
339                                            webIdsList.add(0, webId);
340                                    }
341                                    else {
342                                            webIdsList.add(webId);
343                                    }
344                            }
345    
346                            _webIds = webIdsList.toArray(new String[webIdsList.size()]);
347                    }
348                    catch (Exception e) {
349                            _log.error(e, e);
350                    }
351    
352                    if ((_webIds == null) || (_webIds.length == 0)) {
353                            _webIds = new String[] {PropsValues.COMPANY_DEFAULT_WEB_ID};
354                    }
355    
356                    return _webIds;
357            }
358    
359            private long _initCompany(ServletContext servletContext, String webId) {
360    
361                    // Begin initializing company
362    
363                    if (_log.isDebugEnabled()) {
364                            _log.debug("Begin initializing company with web id " + webId);
365                    }
366    
367                    long companyId = 0;
368    
369                    try {
370                            Company company = CompanyLocalServiceUtil.checkCompany(webId);
371    
372                            companyId = company.getCompanyId();
373                    }
374                    catch (Exception e) {
375                            _log.error(e, e);
376                    }
377    
378                    CompanyThreadLocal.setCompanyId(companyId);
379    
380                    // Lucene
381    
382                    LuceneHelperUtil.startup(companyId);
383    
384                    // Initialize display
385    
386                    if (_log.isDebugEnabled()) {
387                            _log.debug("Initialize display");
388                    }
389    
390                    try {
391                            String xml = HttpUtil.URLtoString(servletContext.getResource(
392                                    "/WEB-INF/liferay-display.xml"));
393    
394                            PortletCategory portletCategory = (PortletCategory)WebAppPool.get(
395                                    companyId, WebKeys.PORTLET_CATEGORY);
396    
397                            if (portletCategory == null) {
398                                    portletCategory = new PortletCategory();
399                            }
400    
401                            PortletCategory newPortletCategory =
402                                    PortletLocalServiceUtil.getEARDisplay(xml);
403    
404                            portletCategory.merge(newPortletCategory);
405    
406                            for (int i = 0; i < _companyIds.length; i++) {
407                                    long currentCompanyId = _companyIds[i];
408    
409                                    PortletCategory currentPortletCategory =
410                                            (PortletCategory)WebAppPool.get(
411                                                    currentCompanyId, WebKeys.PORTLET_CATEGORY);
412    
413                                    if (currentPortletCategory != null) {
414                                            portletCategory.merge(currentPortletCategory);
415                                    }
416                            }
417    
418                            WebAppPool.put(
419                                    companyId, WebKeys.PORTLET_CATEGORY, portletCategory);
420                    }
421                    catch (Exception e) {
422                            _log.error(e, e);
423                    }
424    
425                    // Check journal content search
426    
427                    if (_log.isDebugEnabled()) {
428                            _log.debug("Check journal content search");
429                    }
430    
431                    if (GetterUtil.getBoolean(
432                                    PropsUtil.get(
433                                            PropsKeys.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP))) {
434    
435                            try {
436                                    JournalContentSearchLocalServiceUtil.checkContentSearches(
437                                            companyId);
438                            }
439                            catch (Exception e) {
440                                    _log.error(e, e);
441                            }
442                    }
443    
444                    // LDAP Import
445    
446                    try {
447                            if (LDAPSettingsUtil.isImportOnStartup(companyId)) {
448                                    PortalLDAPImporterUtil.importFromLDAP(companyId);
449                            }
450                    }
451                    catch (Exception e) {
452                            _log.error(e, e);
453                    }
454    
455                    // Process application startup events
456    
457                    if (_log.isDebugEnabled()) {
458                            _log.debug("Process application startup events");
459                    }
460    
461                    try {
462                            EventsProcessorUtil.process(
463                                    PropsKeys.APPLICATION_STARTUP_EVENTS,
464                                    PropsValues.APPLICATION_STARTUP_EVENTS,
465                                    new String[] {String.valueOf(companyId)});
466                    }
467                    catch (Exception e) {
468                            _log.error(e, e);
469                    }
470    
471                    // End initializing company
472    
473                    if (_log.isDebugEnabled()) {
474                            _log.debug(
475                                    "End initializing company with web id " + webId +
476                                            " and company id " + companyId);
477                    }
478    
479                    addCompanyId(companyId);
480    
481                    return companyId;
482            }
483    
484            private boolean _isAutoLoginIgnoreHost(String host) {
485                    return _autoLoginIgnoreHosts.contains(host);
486            }
487    
488            private boolean _isAutoLoginIgnorePath(String path) {
489                    return _autoLoginIgnorePaths.contains(path);
490            }
491    
492            private boolean _isCompanyActive(long companyId) {
493                    try {
494                            Company company = CompanyLocalServiceUtil.fetchCompanyById(
495                                    companyId);
496    
497                            if (company != null) {
498                                    return company.isActive();
499                            }
500                    }
501                    catch (Exception e) {
502                            _log.error(e, e);
503                    }
504    
505                    return false;
506            }
507    
508            private boolean _isVirtualHostsIgnoreHost(String host) {
509                    return _virtualHostsIgnoreHosts.contains(host);
510            }
511    
512            private boolean _isVirtualHostsIgnorePath(String path) {
513                    return _virtualHostsIgnorePaths.contains(path);
514            }
515    
516            private void _reload(ServletContext servletContext) {
517                    _companyIds = new long[0];
518                    _webIds = null;
519    
520                    String[] webIds = _getWebIds();
521    
522                    for (String webId : webIds) {
523                            _initCompany(servletContext, webId);
524                    }
525            }
526    
527            private static final String _GET_COMPANY_IDS =
528                    "select companyId from Company";
529    
530            private static Log _log = LogFactoryUtil.getLog(PortalInstances.class);
531    
532            private static PortalInstances _instance = new PortalInstances();
533    
534            private Set<String> _autoLoginIgnoreHosts;
535            private Set<String> _autoLoginIgnorePaths;
536            private long[] _companyIds;
537            private Set<String> _virtualHostsIgnoreHosts;
538            private Set<String> _virtualHostsIgnorePaths;
539            private String[] _webIds;
540    
541    }