001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.portlet;
016    
017    import aQute.bnd.annotation.ProviderType;
018    
019    import com.liferay.portal.kernel.security.pacl.permission.PortalRuntimePermission;
020    import com.liferay.portal.kernel.util.AutoResetThreadLocal;
021    import com.liferay.portal.kernel.util.ClassLoaderPool;
022    
023    import javax.servlet.ServletContext;
024    
025    /**
026     * @author Brian Wing Shun Chan
027     */
028    @ProviderType
029    public class PortletClassLoaderUtil {
030    
031            public static ClassLoader getClassLoader() {
032                    return ClassLoaderPool.getClassLoader(getServletContextName());
033            }
034    
035            public static ClassLoader getClassLoader(String portletId) {
036                    PortalRuntimePermission.checkGetClassLoader(portletId);
037    
038                    PortletBag portletBag = PortletBagPool.get(portletId);
039    
040                    if (portletBag == null) {
041                            return null;
042                    }
043    
044                    ServletContext servletContext = portletBag.getServletContext();
045    
046                    return servletContext.getClassLoader();
047            }
048    
049            public static String getServletContextName() {
050                    String servletContextName = _servletContextName.get();
051    
052                    if (servletContextName == null) {
053                            throw new IllegalStateException(
054                                    "No servlet context name specified");
055                    }
056    
057                    return servletContextName;
058            }
059    
060            public static void setServletContextName(String servletContextName) {
061                    PortalRuntimePermission.checkSetBeanProperty(
062                            PortletClassLoaderUtil.class);
063    
064                    _servletContextName.set(servletContextName);
065            }
066    
067            private static final ThreadLocal<String> _servletContextName =
068                    new AutoResetThreadLocal<>(
069                            PortletClassLoaderUtil.class + "._servletContextName");
070    
071    }