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            @Override
034            public Object invoke(Object proxy, Method method, Object[] arguments)
035                    throws Throwable {
036    
037                    ClassLoader contextClassLoader =
038                            ClassLoaderUtil.getContextClassLoader();
039    
040                    try {
041                            if ((_classLoader != null) &&
042                                    (_classLoader != contextClassLoader)) {
043    
044                                    ClassLoaderUtil.setContextClassLoader(_classLoader);
045                            }
046    
047                            return method.invoke(_bean, arguments);
048                    }
049                    catch (InvocationTargetException ite) {
050                            return null;
051                    }
052                    finally {
053                            if ((_classLoader != null) &&
054                                    (_classLoader != contextClassLoader)) {
055    
056                                    ClassLoaderUtil.setContextClassLoader(contextClassLoader);
057                            }
058                    }
059            }
060    
061            private Object _bean;
062            private ClassLoader _classLoader;
063    
064    }