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.bean;
016    
017    import com.liferay.portal.kernel.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 final Object _bean;
062            private final ClassLoader _classLoader;
063    
064    }