/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.kernel.portlet;

import aQute.bnd.annotation.ProviderType;

import com.liferay.portal.kernel.servlet.ServletContextClassLoaderPool;
import com.liferay.portal.kernel.security.pacl.permission.PortalRuntimePermission;
import com.liferay.portal.kernel.util.AutoResetThreadLocal;
import com.liferay.portal.kernel.util.ClassLoaderPool;

import javax.servlet.ServletContext;

/**
 * @author Brian Wing Shun Chan
 */
@ProviderType
public class PortletClassLoaderUtil {

	public static ClassLoader getClassLoader() {
		String servletContextName = getServletContextName();

 		ClassLoader classLoader = ServletContextClassLoaderPool.getClassLoader(
			servletContextName);
 
 		if (classLoader == null) {
			throw new IllegalStateException(
				"Unable to find the class loader for servlet context " +
					servletContextName);
		}
 
 		return classLoader;
	}

	public static ClassLoader getClassLoader(String portletId) {
		PortalRuntimePermission.checkGetClassLoader(portletId);

		PortletBag portletBag = PortletBagPool.get(portletId);

		if (portletBag == null) {
			return null;
		}

		ServletContext servletContext = portletBag.getServletContext();

		return servletContext.getClassLoader();
	}

	public static String getServletContextName() {
		String servletContextName = _servletContextName.get();

		if (servletContextName == null) {
			throw new IllegalStateException(
				"No servlet context name specified");
		}

		return servletContextName;
	}

	public static void setServletContextName(String servletContextName) {
		PortalRuntimePermission.checkSetBeanProperty(
			PortletClassLoaderUtil.class);

		_servletContextName.set(servletContextName);
	}

	private static final ThreadLocal<String> _servletContextName =
		new AutoResetThreadLocal<>(
			PortletClassLoaderUtil.class + "._servletContextName");

}