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.Validator;
28  import com.liferay.portal.model.Company;
29  import com.liferay.portal.model.LayoutSet;
30  import com.liferay.portal.model.PortletCategory;
31  import com.liferay.portal.model.impl.CompanyImpl;
32  import com.liferay.portal.security.auth.CompanyThreadLocal;
33  import com.liferay.portal.security.ldap.PortalLDAPUtil;
34  import com.liferay.portal.service.CompanyLocalServiceUtil;
35  import com.liferay.portal.service.LayoutSetLocalServiceUtil;
36  import com.liferay.portal.service.PortletLocalServiceUtil;
37  import com.liferay.portal.struts.MultiMessageResources;
38  import com.liferay.portlet.journal.service.JournalContentSearchLocalServiceUtil;
39  import com.liferay.util.Http;
40  import com.liferay.util.SetUtil;
41  
42  import java.util.ArrayList;
43  import java.util.Iterator;
44  import java.util.List;
45  import java.util.Set;
46  
47  import javax.servlet.ServletContext;
48  import javax.servlet.http.HttpServletRequest;
49  
50  import org.apache.commons.logging.Log;
51  import org.apache.commons.logging.LogFactory;
52  import org.apache.struts.Globals;
53  
54  /**
55   * <a href="PortalInstances.java.html"><b><i>View Source</i></b></a>
56   *
57   * @author Brian Wing Shun Chan
58   * @author Jose Oliver
59   * @author Atul Patel
60   * @author Mika Koivisto
61   *
62   */
63  public class PortalInstances {
64  
65      public static final String DEFAULT_VIRTUAL_HOST = "localhost";
66  
67      public static void addCompanyId(long companyId) {
68          _instance._addCompanyId(companyId);
69      }
70  
71      public static long getCompanyId(HttpServletRequest req) {
72          return _instance._getCompanyId(req);
73      }
74  
75      public static long[] getCompanyIds() {
76          return _instance._getCompanyIds();
77      }
78  
79      public static long getDefaultCompanyId() {
80          return _instance._getDefaultCompanyId();
81      }
82  
83      public static String[] getWebIds() {
84          return _instance._getWebIds();
85      }
86  
87      public static long initCompany(ServletContext ctx, String webId) {
88          return _instance._initCompany(ctx, webId);
89      }
90  
91      public static boolean isIgnoreHost(String host) {
92          return _instance._isIgnoreHost(host);
93      }
94  
95      public static boolean isIgnorePath(String path) {
96          return _instance._isIgnorePath(path);
97      }
98  
99      private PortalInstances() {
100         _companyIds = new long[0];
101         _ignoreHosts = SetUtil.fromArray(PropsUtil.getArray(
102             PropsUtil.VIRTUAL_HOSTS_IGNORE_HOSTS));
103         _ignorePaths = SetUtil.fromArray(PropsUtil.getArray(
104             PropsUtil.VIRTUAL_HOSTS_IGNORE_PATHS));
105     }
106 
107     private void _addCompanyId(long companyId) {
108         long[] companyIds = new long[_companyIds.length + 1];
109 
110         System.arraycopy(
111             _companyIds, 0, companyIds, 0, _companyIds.length);
112 
113         companyIds[_companyIds.length] = companyId;
114 
115         _companyIds = companyIds;
116     }
117 
118     private long _getCompanyId(HttpServletRequest req) {
119         if (_log.isDebugEnabled()) {
120             _log.debug("Get company id");
121         }
122 
123         Long companyIdObj = (Long)req.getAttribute(WebKeys.COMPANY_ID);
124 
125         if (_log.isDebugEnabled()) {
126             _log.debug("Company id from request " + companyIdObj);
127         }
128 
129         if (companyIdObj != null) {
130             return companyIdObj.longValue();
131         }
132 
133         String host = PortalUtil.getHost(req);
134 
135         if (_log.isDebugEnabled()) {
136             _log.debug("Host " + host);
137         }
138 
139         long companyId = _getCompanyIdByVirtualHost(host);
140 
141         if (_log.isDebugEnabled()) {
142             _log.debug("Company id from host " + companyId);
143         }
144 
145         if (companyId <= 0) {
146             LayoutSet layoutSet = _getLayoutSetByVirtualHost(host);
147 
148             if (layoutSet != null) {
149                 companyId = layoutSet.getCompanyId();
150 
151                 if (_log.isDebugEnabled()) {
152                     _log.debug(
153                         "Company id " + companyId + " is associated with " +
154                             "layout set " + layoutSet.getLayoutSetId());
155                 }
156 
157                 req.setAttribute(WebKeys.VIRTUAL_HOST_LAYOUT_SET, layoutSet);
158             }
159         }
160 
161         if (companyId <= 0) {
162             companyId = GetterUtil.getLong(
163                 CookieKeys.getCookie(req, CookieKeys.COMPANY_ID));
164 
165             if (_log.isDebugEnabled()) {
166                 _log.debug("Company id from cookie " + companyId);
167             }
168         }
169 
170         if (companyId <= 0) {
171             companyId = _getDefaultCompanyId();
172 
173             if (_log.isDebugEnabled()) {
174                 _log.debug("Default company id " + companyId);
175             }
176         }
177 
178         if (_log.isDebugEnabled()) {
179             _log.debug("Set company id " + companyId);
180         }
181 
182         req.setAttribute(WebKeys.COMPANY_ID, new Long(companyId));
183 
184         CompanyThreadLocal.setCompanyId(companyId);
185 
186         return companyId;
187     }
188 
189     private long _getCompanyIdByVirtualHost(String host) {
190         if (Validator.isNull(host)) {
191             return 0;
192         }
193 
194         try {
195             Iterator itr = CompanyLocalServiceUtil.getCompanies().iterator();
196 
197             while (itr.hasNext()) {
198                 Company company = (Company)itr.next();
199 
200                 if (company.getVirtualHost().equals(host)) {
201                     return company.getCompanyId();
202                 }
203             }
204         }
205         catch (Exception e) {
206             _log.error(e, e);
207         }
208 
209         return 0;
210     }
211 
212     private long[] _getCompanyIds() {
213         return _companyIds;
214     }
215 
216     private long _getDefaultCompanyId() {
217         return _companyIds[0];
218     }
219 
220     private LayoutSet _getLayoutSetByVirtualHost(String host) {
221         if (Validator.isNull(host)) {
222             return null;
223         }
224 
225         if (_isIgnoreHost(host)) {
226             return null;
227         }
228 
229         try {
230             return LayoutSetLocalServiceUtil.getLayoutSet(host);
231         }
232         catch (Exception e) {
233             return null;
234         }
235     }
236 
237     private String[] _getWebIds() {
238         if (_webIds != null) {
239             return _webIds;
240         }
241 
242         if (Validator.isNull(CompanyImpl.DEFAULT_WEB_ID)) {
243             throw new RuntimeException("Default web id must not be null");
244         }
245 
246         try {
247             List companies = CompanyLocalServiceUtil.getCompanies();
248 
249             List webIdsList = new ArrayList(companies.size());
250 
251             Iterator itr = companies.iterator();
252 
253             while (itr.hasNext()) {
254                 Company company = (Company)itr.next();
255 
256                 webIdsList.add(company.getWebId());
257             }
258 
259             _webIds = (String[])webIdsList.toArray(new String[0]);
260         }
261         catch (Exception e) {
262             _log.error(e, e);
263         }
264 
265         if ((_webIds == null) || (_webIds.length == 0)) {
266             _webIds = new String[] {CompanyImpl.DEFAULT_WEB_ID};
267         }
268 
269         return _webIds;
270     }
271 
272     private long _initCompany(ServletContext ctx, String webId) {
273 
274         // Begin initializing company
275 
276         if (_log.isDebugEnabled()) {
277             _log.debug("Begin initializing company with web id " + webId);
278         }
279 
280         long companyId = 0;
281 
282         try {
283             Company company = CompanyLocalServiceUtil.checkCompany(webId);
284 
285             companyId = company.getCompanyId();
286         }
287         catch (Exception e) {
288             _log.error(e, e);
289         }
290 
291         CompanyThreadLocal.setCompanyId(companyId);
292 
293         // Initialize display
294 
295         if (_log.isDebugEnabled()) {
296             _log.debug("Initialize display");
297         }
298 
299         try {
300             String xml = Http.URLtoString(ctx.getResource(
301                 "/WEB-INF/liferay-display.xml"));
302 
303             PortletCategory portletCategory =
304                 (PortletCategory)WebAppPool.get(
305                     String.valueOf(companyId), WebKeys.PORTLET_CATEGORY);
306 
307             if (portletCategory == null) {
308                 portletCategory = new PortletCategory();
309             }
310 
311             PortletCategory newPortletCategory =
312                 PortletLocalServiceUtil.getEARDisplay(xml);
313 
314             portletCategory.merge(newPortletCategory);
315 
316             WebAppPool.put(
317                 String.valueOf(companyId), WebKeys.PORTLET_CATEGORY,
318                 portletCategory);
319         }
320         catch (Exception e) {
321             _log.error(e, e);
322         }
323 
324         // Check journal content search
325 
326         if (_log.isDebugEnabled()) {
327             _log.debug("Check journal content search");
328         }
329 
330         if (GetterUtil.getBoolean(PropsUtil.get(
331                 CompanyImpl.SYSTEM,
332                 PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP)) ||
333             GetterUtil.getBoolean(PropsUtil.get(
334                 PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP))) {
335 
336             try {
337                 JournalContentSearchLocalServiceUtil.checkContentSearches(
338                     companyId);
339             }
340             catch (Exception e) {
341                 _log.error(e, e);
342             }
343         }
344 
345         // LDAP Import
346 
347         try {
348             if (PortalLDAPUtil.isImportOnStartup(companyId)) {
349                 PortalLDAPUtil.importFromLDAP(companyId);
350             }
351         }
352         catch (Exception e){
353             _log.error(e, e);
354         }
355 
356         // Message resources
357 
358         if (_log.isDebugEnabled()) {
359             _log.debug("Message resources");
360         }
361 
362         MultiMessageResources messageResources =
363             (MultiMessageResources)ctx.getAttribute(Globals.MESSAGES_KEY);
364 
365         messageResources.setServletContext(ctx);
366 
367         WebAppPool.put(
368             String.valueOf(companyId), Globals.MESSAGES_KEY, messageResources);
369 
370         // Process application startup events
371 
372         if (_log.isDebugEnabled()) {
373             _log.debug("Process application startup events");
374         }
375 
376         try {
377             EventsProcessor.process(PropsUtil.getArray(
378                 PropsUtil.APPLICATION_STARTUP_EVENTS),
379                 new String[] {String.valueOf(companyId)});
380         }
381         catch (Exception e) {
382             _log.error(e, e);
383         }
384 
385         // End initializing company
386 
387         if (_log.isDebugEnabled()) {
388             _log.debug(
389                 "End initializing company with web id " + webId +
390                     " and company id " + companyId);
391         }
392 
393         addCompanyId(companyId);
394 
395         return companyId;
396     }
397 
398     private boolean _isIgnoreHost(String host) {
399         return _ignoreHosts.contains(host);
400     }
401 
402     private boolean _isIgnorePath(String path) {
403         return _ignorePaths.contains(path);
404     }
405 
406     private static Log _log = LogFactory.getLog(PortalInstances.class);
407 
408     private static PortalInstances _instance = new PortalInstances();
409 
410     private long[] _companyIds;
411     private String[] _webIds;
412     private Set _ignoreHosts;
413     private Set _ignorePaths;
414 
415 }