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