1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portal.job;
16  
17  import com.liferay.portal.kernel.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.kernel.util.ThreadLocalRegistry;
22  import com.liferay.portal.util.PropsValues;
23  
24  import org.quartz.JobDetail;
25  import org.quartz.JobExecutionContext;
26  import org.quartz.StatefulJob;
27  
28  /**
29   * <a href="JobWrapper.java.html"><b><i>View Source</i></b></a>
30   *
31   * @author Brian Wing Shun Chan
32   */
33  public class JobWrapper implements StatefulJob {
34  
35      public void execute(JobExecutionContext context) {
36          try {
37              if (_job == null) {
38                  JobDetail jobDetail = context.getJobDetail();
39  
40                  Class<IntervalJob> intervalJobClass = JobClassUtil.get(
41                      jobDetail.getName());
42  
43                  _classLoader = intervalJobClass.getClassLoader();
44  
45                  _job = (IntervalJob)_classLoader.loadClass(
46                      intervalJobClass.getName()).newInstance();
47              }
48  
49              Thread currentThread = Thread.currentThread();
50  
51              ClassLoader contextClassLoader =
52                  currentThread.getContextClassLoader();
53  
54              try {
55                  currentThread.setContextClassLoader(_classLoader);
56  
57                  for (String shardName : PropsValues.SHARD_AVAILABLE_NAMES) {
58                      ShardUtil.pushCompanyService(shardName);
59  
60                      try {
61                          _job.execute(new JobExecutionContextImpl(context));
62                      }
63                      finally {
64                          ShardUtil.popCompanyService();
65                      }
66                  }
67              }
68              finally {
69                  currentThread.setContextClassLoader(contextClassLoader);
70  
71                  ThreadLocalRegistry.resetThreadLocals();
72              }
73          }
74          catch (Exception e) {
75              _log.error(e, e);
76          }
77      }
78  
79      private static Log _log = LogFactoryUtil.getLog(JobWrapper.class);
80  
81      private ClassLoader _classLoader;
82      private IntervalJob _job;
83  
84  }