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