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.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            @Override
040            public Object invoke(Object proxy, Method method, Object[] arguments)
041                    throws Throwable {
042    
043                    try {
044                            String methodName = method.getName();
045    
046                            if (methodName.equals("executeQuery")) {
047                                    return executeQuery();
048                            }
049    
050                            return method.invoke(_preparedStatement, arguments);
051                    }
052                    catch (InvocationTargetException ite) {
053                            throw ite.getTargetException();
054                    }
055            }
056    
057            protected ResultSet executeQuery() throws SQLException {
058                    Thread currentThread = Thread.currentThread();
059    
060                    ClassLoader classLoader = currentThread.getContextClassLoader();
061    
062                    ResultSet resultSet = _preparedStatement.executeQuery();
063    
064                    return (ResultSet)ProxyUtil.newProxyInstance(
065                            classLoader, new Class[] {ResultSet.class},
066                            new UpgradeOptimizedResultSetHandler(resultSet));
067            }
068    
069            private PreparedStatement _preparedStatement;
070    
071    }