001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.bean;
016    
017    import com.liferay.portal.util.ClassLoaderUtil;
018    
019    import java.lang.reflect.InvocationHandler;
020    import java.lang.reflect.InvocationTargetException;
021    import java.lang.reflect.Method;
022    
023    /**
024     * @author Brian Wing Shun Chan
025     */
026    public class VelocityBeanHandler implements InvocationHandler {
027    
028            public VelocityBeanHandler(Object bean, ClassLoader classLoader) {
029                    _bean = bean;
030                    _classLoader = classLoader;
031            }
032    
033            public ClassLoader getClassLoader() {
034                    return _classLoader;
035            }
036    
037            @Override
038            public Object invoke(Object proxy, Method method, Object[] arguments)
039                    throws Throwable {
040    
041                    ClassLoader contextClassLoader =
042                            ClassLoaderUtil.getContextClassLoader();
043    
044                    try {
045                            if ((_classLoader != null) &&
046                                    (_classLoader != contextClassLoader)) {
047    
048                                    ClassLoaderUtil.setContextClassLoader(_classLoader);
049                            }
050    
051                            return method.invoke(_bean, arguments);
052                    }
053                    catch (InvocationTargetException ite) {
054                            return null;
055                    }
056                    finally {
057                            if ((_classLoader != null) &&
058                                    (_classLoader != contextClassLoader)) {
059    
060                                    ClassLoaderUtil.setContextClassLoader(contextClassLoader);
061                            }
062                    }
063            }
064    
065            private Object _bean;
066            private ClassLoader _classLoader;
067    
068    }