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.kernel.util;
16  
17  import com.liferay.portal.kernel.portlet.PortletBag;
18  import com.liferay.portal.kernel.portlet.PortletBagPool;
19  import com.liferay.portal.kernel.servlet.PortletServlet;
20  
21  import javax.servlet.ServletContext;
22  
23  /**
24   * <a href="PortletClassInvoker.java.html"><b><i>View Source</i></b></a>
25   *
26   * @author Bruno Farache
27   * @author Shuyang Zhou
28   */
29  public class PortletClassInvoker {
30  
31      public static Object invoke(
32              boolean newInstance, String portletId, MethodKey methodKey,
33              Object... arguments)
34          throws Exception {
35  
36          portletId = _getRootPortletId(portletId);
37  
38          ClassLoader portletClassLoader = PortalClassLoaderUtil.getClassLoader();
39  
40          PortletBag portletBag = PortletBagPool.get(portletId);
41  
42          if (portletBag != null) {
43              ServletContext servletContext = portletBag.getServletContext();
44  
45              portletClassLoader = (ClassLoader)servletContext.getAttribute(
46                  PortletServlet.PORTLET_CLASS_LOADER);
47          }
48  
49          Thread currentThread = Thread.currentThread();
50  
51          ClassLoader contextClassLoader = currentThread.getContextClassLoader();
52  
53          try {
54              currentThread.setContextClassLoader(portletClassLoader);
55  
56              MethodHandler methodHandler = new MethodHandler(
57                  methodKey, arguments);
58  
59              return methodHandler.invoke(newInstance);
60          }
61          finally {
62              currentThread.setContextClassLoader(contextClassLoader);
63          }
64      }
65  
66      /**
67       * Copied from <code>com.liferay.portal.model.PortletConstants</code>.
68       */
69      private static String _getRootPortletId(String portletId) {
70          int pos = portletId.indexOf(_INSTANCE_SEPARATOR);
71  
72          if (pos == -1) {
73              return portletId;
74          }
75          else {
76              return portletId.substring(0, pos);
77          }
78      }
79  
80      private static final String _INSTANCE_SEPARATOR = "_INSTANCE_";
81  
82  }