001    /**
002     * Copyright (c) 2000-2013 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.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    }