aboutsummaryrefslogtreecommitdiffstats
path: root/dblib/common/src/main/java/org/apache/tomcat/jdbc/pool/interceptor/ConnectionState.java
blob: 95049c68ba2b0faf5498a9043a00da4774936b78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/*-
 * ============LICENSE_START=======================================================
 * openecomp
 * ================================================================================
 * Copyright (C) 2016 - 2017 AT&T
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.tomcat.jdbc.pool.interceptor;

import java.lang.reflect.Method;
import java.sql.SQLException;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.ConnectionPool;
import org.apache.tomcat.jdbc.pool.DataSourceFactory;
import org.apache.tomcat.jdbc.pool.JdbcInterceptor;
import org.apache.tomcat.jdbc.pool.PoolConfiguration;
import org.apache.tomcat.jdbc.pool.PooledConnection;

/**
 * Interceptor that keep track of connection state to avoid roundtrips to the database.
 * The {@link org.apache.tomcat.jdbc.pool.ConnectionPool} is optimized to do as little work as possible.
 * The pool itself doesn't remember settings like {@link java.sql.Connection#setAutoCommit(boolean)},
 * {@link java.sql.Connection#setReadOnly(boolean)}, {@link java.sql.Connection#setCatalog(String)} or
 * {@link java.sql.Connection#setTransactionIsolation(int)}. It relies on the application to remember how and when
 * these settings have been applied.
 * In the cases where the application code doesn't know or want to keep track of the state, this interceptor helps cache the
 * state, and it also avoids roundtrips to the database asking for it.
 *
 */

public class ConnectionState extends JdbcInterceptor  {
    private static final Log log = LogFactory.getLog(ConnectionState.class);

    protected final String[] readState = {"getAutoCommit","getTransactionIsolation","isReadOnly","getCatalog"};
    protected final String[] writeState = {"setAutoCommit","setTransactionIsolation","setReadOnly","setCatalog"};

    protected Boolean autoCommit = null;
    protected Integer transactionIsolation = null;
    protected Boolean readOnly = null;
    protected String catalog = null;


    @Override
    public void reset(ConnectionPool parent, PooledConnection con) {
        if (parent==null || con==null) {
            //we are resetting, reset our defaults
            autoCommit = null;
            transactionIsolation = null;
            readOnly = null;
            catalog = null;
            return;
        }
        PoolConfiguration poolProperties = parent.getPoolProperties();
        if (poolProperties.getDefaultTransactionIsolation()!=DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION) {
            try {
                if (transactionIsolation==null || transactionIsolation.intValue()!=poolProperties.getDefaultTransactionIsolation()) {
                    con.getConnection().setTransactionIsolation(poolProperties.getDefaultTransactionIsolation());
                    transactionIsolation = Integer.valueOf(poolProperties.getDefaultTransactionIsolation());
                }
            }catch (SQLException x) {
                transactionIsolation = null;
                log.error("Unable to reset transaction isolation state to connection.",x);
            }
        }
        if (poolProperties.getDefaultReadOnly()!=null) {
            try {
                if (readOnly==null || readOnly.booleanValue()!=poolProperties.getDefaultReadOnly().booleanValue()) {
                    con.getConnection().setReadOnly(poolProperties.getDefaultReadOnly().booleanValue());
                    readOnly = poolProperties.getDefaultReadOnly();
                }
            }catch (SQLException x) {
                readOnly = null;
                log.error("Unable to reset readonly state to connection.",x);
            }
        }
        if (poolProperties.getDefaultAutoCommit()!=null) {
            try {
                if (autoCommit==null || autoCommit.booleanValue()!=poolProperties.getDefaultAutoCommit().booleanValue()) {
                    con.getConnection().setAutoCommit(poolProperties.getDefaultAutoCommit().booleanValue());
                    autoCommit = poolProperties.getDefaultAutoCommit();
                }
            }catch (SQLException x) {
                autoCommit = null;
                log.error("Unable to reset autocommit state to connection.",x);
            }
        }
        if (poolProperties.getDefaultCatalog()!=null) {
            try {
                if (catalog==null || (!catalog.equals(poolProperties.getDefaultCatalog()))) {
                    con.getConnection().setCatalog(poolProperties.getDefaultCatalog());
                    catalog = poolProperties.getDefaultCatalog();
                }
            }catch (SQLException x) {
                catalog = null;
                log.error("Unable to reset default catalog state to connection.",x);
            }
        }

    }


    @Override
    public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
        //we are resetting, reset our defaults
        autoCommit = null;
        transactionIsolation = null;
        readOnly = null;
        catalog = null;
        super.disconnected(parent, con, finalizing);
    }



    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String name = method.getName();
        boolean read = false;
        int index = -1;
        for (int i=0; (!read) && i<readState.length; i++) {
            read = compare(name,readState[i]);
            if (read) index = i;
        }
        boolean write = false;
        for (int i=0; (!write) && (!read) && i<writeState.length; i++) {
            write = compare(name,writeState[i]);
            if (write) index = i;
        }
        Object result = null;
        if (read) {
            switch (index) {
                case 0:{result = autoCommit; break;}
                case 1:{result = transactionIsolation; break;}
                case 2:{result = readOnly; break;}
                case 3:{result = catalog; break;}
                default: // NOOP
            }
            //return cached result, if we have it
            if (result!=null) return result;
        }

        result = super.invoke(proxy, method, args);
        if (read || write) {
            switch (index) {
                case 0:{autoCommit = (Boolean) (read?result:args[0]); break;}
                case 1:{transactionIsolation = (Integer)(read?result:args[0]); break;}
                case 2:{readOnly = (Boolean)(read?result:args[0]); break;}
                case 3:{catalog = (String)(read?result:args[0]); break;}
            }
        }
        return result;
    }

}