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