1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.job;
16  
17  import com.liferay.portal.dao.shard.ShardUtil;
18  import com.liferay.portal.kernel.job.IntervalJob;
19  import com.liferay.portal.kernel.log.Log;
20  import com.liferay.portal.kernel.log.LogFactoryUtil;
21  import com.liferay.portal.util.PropsValues;
22  
23  import org.quartz.JobDetail;
24  import org.quartz.JobExecutionContext;
25  import org.quartz.StatefulJob;
26  
27  /**
28   * <a href="JobWrapper.java.html"><b><i>View Source</i></b></a>
29   *
30   * @author Brian Wing Shun Chan
31   */
32  public class JobWrapper implements StatefulJob {
33  
34      public void execute(JobExecutionContext context) {
35          try {
36              if (_job == null) {
37                  JobDetail jobDetail = context.getJobDetail();
38  
39                  Class<IntervalJob> intervalJobClass = JobClassUtil.get(
40                      jobDetail.getName());
41  
42                  _classLoader = intervalJobClass.getClassLoader();
43  
44                  _job = (IntervalJob)_classLoader.loadClass(
45                      intervalJobClass.getName()).newInstance();
46              }
47  
48              Thread currentThread = Thread.currentThread();
49  
50              ClassLoader contextClassLoader =
51                  currentThread.getContextClassLoader();
52  
53              try {
54                  currentThread.setContextClassLoader(_classLoader);
55  
56                  for (String shardName : PropsValues.SHARD_AVAILABLE_NAMES) {
57                      ShardUtil.pushCompanyService(shardName);
58  
59                      try {
60                          _job.execute(new JobExecutionContextImpl(context));
61                      }
62                      finally {
63                          ShardUtil.popCompanyService();
64                      }
65                  }
66              }
67              finally {
68                  currentThread.setContextClassLoader(contextClassLoader);
69              }
70          }
71          catch (Exception e) {
72              _log.error(e, e);
73          }
74      }
75  
76      private static Log _log = LogFactoryUtil.getLog(JobWrapper.class);
77  
78      private ClassLoader _classLoader;
79      private IntervalJob _job;
80  
81  }