001    /**
002     * Copyright (c) 2000-2012 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.upgrade.dao.orm;
016    
017    import com.liferay.portal.kernel.util.ProxyUtil;
018    
019    import java.lang.reflect.InvocationHandler;
020    import java.lang.reflect.InvocationTargetException;
021    import java.lang.reflect.Method;
022    
023    import java.sql.PreparedStatement;
024    import java.sql.ResultSet;
025    import java.sql.SQLException;
026    
027    /**
028     * @author Minhchau Dang
029     */
030    public class UpgradeOptimizedPreparedStatementHandler
031            implements InvocationHandler {
032    
033            public UpgradeOptimizedPreparedStatementHandler(
034                    PreparedStatement preparedStatement) {
035    
036                    _preparedStatement = preparedStatement;
037            }
038    
039            public Object invoke(Object proxy, Method method, Object[] arguments)
040                    throws Throwable {
041    
042                    try {
043                            String methodName = method.getName();
044    
045                            if (methodName.equals("executeQuery")) {
046                                    return executeQuery();
047                            }
048    
049                            return method.invoke(_preparedStatement, arguments);
050                    }
051                    catch (InvocationTargetException ite) {
052                            throw ite.getTargetException();
053                    }
054            }
055    
056            protected ResultSet executeQuery() throws SQLException {
057                    Thread currentThread = Thread.currentThread();
058    
059                    ClassLoader classLoader = currentThread.getContextClassLoader();
060    
061                    ResultSet resultSet = _preparedStatement.executeQuery();
062    
063                    return (ResultSet) ProxyUtil.newProxyInstance(
064                            classLoader, new Class[] {ResultSet.class},
065                            new UpgradeOptimizedResultSetHandler(resultSet));
066            }
067    
068            private PreparedStatement _preparedStatement;
069    
070    }