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