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