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