1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.util;
24  
25  import com.liferay.portal.events.EventsProcessor;
26  import com.liferay.portal.kernel.util.GetterUtil;
27  import com.liferay.portal.kernel.util.HttpUtil;
28  import com.liferay.portal.kernel.util.Validator;
29  import com.liferay.portal.model.Company;
30  import com.liferay.portal.model.CompanyConstants;
31  import com.liferay.portal.model.LayoutSet;
32  import com.liferay.portal.model.PortletCategory;
33  import com.liferay.portal.security.auth.CompanyThreadLocal;
34  import com.liferay.portal.security.ldap.PortalLDAPUtil;
35  import com.liferay.portal.service.CompanyLocalServiceUtil;
36  import com.liferay.portal.service.LayoutSetLocalServiceUtil;
37  import com.liferay.portal.service.PortletLocalServiceUtil;
38  import com.liferay.portal.struts.MultiMessageResources;
39  import com.liferay.portlet.journal.service.JournalContentSearchLocalServiceUtil;
40  import com.liferay.util.SetUtil;
41  
42  import java.util.ArrayList;
43  import java.util.List;
44  import java.util.Set;
45  
46  import javax.servlet.ServletContext;
47  import javax.servlet.http.HttpServletRequest;
48  
49  import org.apache.commons.logging.Log;
50  import org.apache.commons.logging.LogFactory;
51  import org.apache.struts.Globals;
52  
53  /**
54   * <a href="PortalInstances.java.html"><b><i>View Source</i></b></a>
55   *
56   * @author Brian Wing Shun Chan
57   * @author Jose Oliver
58   * @author Atul Patel
59   * @author Mika Koivisto
60   *
61   */
62  public class PortalInstances {
63  
64      public static final String DEFAULT_VIRTUAL_HOST = "localhost";
65  
66      public static void addCompanyId(long companyId) {
67          _instance._addCompanyId(companyId);
68      }
69  
70      public static long getCompanyId(HttpServletRequest req) {
71          return _instance._getCompanyId(req);
72      }
73  
74      public static long[] getCompanyIds() {
75          return _instance._getCompanyIds();
76      }
77  
78      public static long getDefaultCompanyId() {
79          return _instance._getDefaultCompanyId();
80      }
81  
82      public static String[] getWebIds() {
83          return _instance._getWebIds();
84      }
85  
86      public static long initCompany(ServletContext ctx, String webId) {
87          return _instance._initCompany(ctx, webId);
88      }
89  
90      public static boolean isAutoLoginIgnoreHost(String host) {
91          return _instance._isAutoLoginIgnoreHost(host);
92      }
93  
94      public static boolean isAutoLoginIgnorePath(String path) {
95          return _instance._isAutoLoginIgnorePath(path);
96      }
97  
98      public static boolean isVirtualHostsIgnoreHost(String host) {
99          return _instance._isVirtualHostsIgnoreHost(host);
100     }
101 
102     public static boolean isVirtualHostsIgnorePath(String path) {
103         return _instance._isVirtualHostsIgnorePath(path);
104     }
105 
106     private PortalInstances() {
107         _companyIds = new long[0];
108         _autoLoginIgnoreHosts = SetUtil.fromArray(PropsUtil.getArray(
109             PropsUtil.AUTO_LOGIN_IGNORE_HOSTS));
110         _autoLoginIgnorePaths = SetUtil.fromArray(PropsUtil.getArray(
111             PropsUtil.AUTO_LOGIN_IGNORE_PATHS));
112         _virtualHostsIgnoreHosts = SetUtil.fromArray(PropsUtil.getArray(
113             PropsUtil.VIRTUAL_HOSTS_IGNORE_HOSTS));
114         _virtualHostsIgnorePaths = SetUtil.fromArray(PropsUtil.getArray(
115             PropsUtil.VIRTUAL_HOSTS_IGNORE_PATHS));
116     }
117 
118     private void _addCompanyId(long companyId) {
119         long[] companyIds = new long[_companyIds.length + 1];
120 
121         System.arraycopy(
122             _companyIds, 0, companyIds, 0, _companyIds.length);
123 
124         companyIds[_companyIds.length] = companyId;
125 
126         _companyIds = companyIds;
127     }
128 
129     private long _getCompanyId(HttpServletRequest req) {
130         if (_log.isDebugEnabled()) {
131             _log.debug("Get company id");
132         }
133 
134         Long companyIdObj = (Long)req.getAttribute(WebKeys.COMPANY_ID);
135 
136         if (_log.isDebugEnabled()) {
137             _log.debug("Company id from request " + companyIdObj);
138         }
139 
140         if (companyIdObj != null) {
141             return companyIdObj.longValue();
142         }
143 
144         String host = PortalUtil.getHost(req);
145 
146         if (_log.isDebugEnabled()) {
147             _log.debug("Host " + host);
148         }
149 
150         long companyId = _getCompanyIdByVirtualHosts(host);
151 
152         if (_log.isDebugEnabled()) {
153             _log.debug("Company id from host " + companyId);
154         }
155 
156         if (companyId <= 0) {
157             LayoutSet layoutSet = _getLayoutSetByVirtualHosts(host);
158 
159             if (layoutSet != null) {
160                 companyId = layoutSet.getCompanyId();
161 
162                 if (_log.isDebugEnabled()) {
163                     _log.debug(
164                         "Company id " + companyId + " is associated with " +
165                             "layout set " + layoutSet.getLayoutSetId());
166                 }
167 
168                 req.setAttribute(WebKeys.VIRTUAL_HOST_LAYOUT_SET, layoutSet);
169             }
170         }
171 
172         if (companyId <= 0) {
173             companyId = GetterUtil.getLong(
174                 CookieKeys.getCookie(req, CookieKeys.COMPANY_ID));
175 
176             if (_log.isDebugEnabled()) {
177                 _log.debug("Company id from cookie " + companyId);
178             }
179         }
180 
181         if (companyId <= 0) {
182             companyId = _getDefaultCompanyId();
183 
184             if (_log.isDebugEnabled()) {
185                 _log.debug("Default company id " + companyId);
186             }
187         }
188 
189         if (_log.isDebugEnabled()) {
190             _log.debug("Set company id " + companyId);
191         }
192 
193         req.setAttribute(WebKeys.COMPANY_ID, new Long(companyId));
194 
195         CompanyThreadLocal.setCompanyId(companyId);
196 
197         return companyId;
198     }
199 
200     private long _getCompanyIdByVirtualHosts(String host) {
201         if (Validator.isNull(host)) {
202             return 0;
203         }
204 
205         try {
206             List<Company> companies = CompanyLocalServiceUtil.getCompanies();
207 
208             for (Company company : companies) {
209                 if (company.getVirtualHost().equals(host)) {
210                     return company.getCompanyId();
211                 }
212             }
213         }
214         catch (Exception e) {
215             _log.error(e, e);
216         }
217 
218         return 0;
219     }
220 
221     private long[] _getCompanyIds() {
222         return _companyIds;
223     }
224 
225     private long _getDefaultCompanyId() {
226         return _companyIds[0];
227     }
228 
229     private LayoutSet _getLayoutSetByVirtualHosts(String host) {
230         if (Validator.isNull(host)) {
231             return null;
232         }
233 
234         if (_isVirtualHostsIgnoreHost(host)) {
235             return null;
236         }
237 
238         try {
239             return LayoutSetLocalServiceUtil.getLayoutSet(host);
240         }
241         catch (Exception e) {
242             return null;
243         }
244     }
245 
246     private String[] _getWebIds() {
247         if (_webIds != null) {
248             return _webIds;
249         }
250 
251         if (Validator.isNull(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
252             throw new RuntimeException("Default web id must not be null");
253         }
254 
255         try {
256             List<Company> companies = CompanyLocalServiceUtil.getCompanies();
257 
258             List<String> webIdsList = new ArrayList<String>(companies.size());
259 
260             for (Company company : companies) {
261                 webIdsList.add(company.getWebId());
262             }
263 
264             _webIds = webIdsList.toArray(new String[webIdsList.size()]);
265         }
266         catch (Exception e) {
267             _log.error(e, e);
268         }
269 
270         if ((_webIds == null) || (_webIds.length == 0)) {
271             _webIds = new String[] {PropsValues.COMPANY_DEFAULT_WEB_ID};
272         }
273 
274         return _webIds;
275     }
276 
277     private long _initCompany(ServletContext ctx, String webId) {
278 
279         // Begin initializing company
280 
281         if (_log.isDebugEnabled()) {
282             _log.debug("Begin initializing company with web id " + webId);
283         }
284 
285         long companyId = 0;
286 
287         try {
288             Company company = CompanyLocalServiceUtil.checkCompany(webId);
289 
290             companyId = company.getCompanyId();
291         }
292         catch (Exception e) {
293             _log.error(e, e);
294         }
295 
296         CompanyThreadLocal.setCompanyId(companyId);
297 
298         // Initialize display
299 
300         if (_log.isDebugEnabled()) {
301             _log.debug("Initialize display");
302         }
303 
304         try {
305             String xml = HttpUtil.URLtoString(ctx.getResource(
306                 "/WEB-INF/liferay-display.xml"));
307 
308             PortletCategory portletCategory =
309                 (PortletCategory)WebAppPool.get(
310                     String.valueOf(companyId), WebKeys.PORTLET_CATEGORY);
311 
312             if (portletCategory == null) {
313                 portletCategory = new PortletCategory();
314             }
315 
316             PortletCategory newPortletCategory =
317                 PortletLocalServiceUtil.getEARDisplay(xml);
318 
319             portletCategory.merge(newPortletCategory);
320 
321             WebAppPool.put(
322                 String.valueOf(companyId), WebKeys.PORTLET_CATEGORY,
323                 portletCategory);
324         }
325         catch (Exception e) {
326             _log.error(e, e);
327         }
328 
329         // Check journal content search
330 
331         if (_log.isDebugEnabled()) {
332             _log.debug("Check journal content search");
333         }
334 
335         if (GetterUtil.getBoolean(PropsUtil.get(
336                 CompanyConstants.SYSTEM,
337                 PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP)) ||
338             GetterUtil.getBoolean(PropsUtil.get(
339                 PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP))) {
340 
341             try {
342                 JournalContentSearchLocalServiceUtil.checkContentSearches(
343                     companyId);
344             }
345             catch (Exception e) {
346                 _log.error(e, e);
347             }
348         }
349 
350         // LDAP Import
351 
352         try {
353             if (PortalLDAPUtil.isImportOnStartup(companyId)) {
354                 PortalLDAPUtil.importFromLDAP(companyId);
355             }
356         }
357         catch (Exception e){
358             _log.error(e, e);
359         }
360 
361         // Message resources
362 
363         if (_log.isDebugEnabled()) {
364             _log.debug("Message resources");
365         }
366 
367         MultiMessageResources messageResources =
368             (MultiMessageResources)ctx.getAttribute(Globals.MESSAGES_KEY);
369 
370         messageResources.setServletContext(ctx);
371 
372         WebAppPool.put(
373             String.valueOf(companyId), Globals.MESSAGES_KEY, messageResources);
374 
375         // Process application startup events
376 
377         if (_log.isDebugEnabled()) {
378             _log.debug("Process application startup events");
379         }
380 
381         try {
382             EventsProcessor.process(PropsUtil.getArray(
383                 PropsUtil.APPLICATION_STARTUP_EVENTS),
384                 new String[] {String.valueOf(companyId)});
385         }
386         catch (Exception e) {
387             _log.error(e, e);
388         }
389 
390         // End initializing company
391 
392         if (_log.isDebugEnabled()) {
393             _log.debug(
394                 "End initializing company with web id " + webId +
395                     " and company id " + companyId);
396         }
397 
398         addCompanyId(companyId);
399 
400         return companyId;
401     }
402 
403     private boolean _isAutoLoginIgnoreHost(String host) {
404         return _autoLoginIgnoreHosts.contains(host);
405     }
406 
407     private boolean _isAutoLoginIgnorePath(String path) {
408         return _autoLoginIgnorePaths.contains(path);
409     }
410 
411     private boolean _isVirtualHostsIgnoreHost(String host) {
412         return _virtualHostsIgnoreHosts.contains(host);
413     }
414 
415     private boolean _isVirtualHostsIgnorePath(String path) {
416         return _virtualHostsIgnorePaths.contains(path);
417     }
418 
419     private static Log _log = LogFactory.getLog(PortalInstances.class);
420 
421     private static PortalInstances _instance = new PortalInstances();
422 
423     private long[] _companyIds;
424     private String[] _webIds;
425     private Set<String> _autoLoginIgnoreHosts;
426     private Set<String> _autoLoginIgnorePaths;
427     private Set<String> _virtualHostsIgnoreHosts;
428     private Set<String> _virtualHostsIgnorePaths;
429 
430 }