com.mysql.cj.jdbc.JdbcConnection Java Examples

The following examples show how to use com.mysql.cj.jdbc.JdbcConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoadBalancedAutoCommitInterceptor.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public QueryInterceptor init(MysqlConnection connection, Properties props, Log log) {
    this.conn = (JdbcConnection) connection;

    String autoCommitSwapThresholdAsString = props.getProperty(PropertyKey.loadBalanceAutoCommitStatementThreshold.getKeyName(), "0");
    try {
        this.matchingAfterStatementThreshold = Integer.parseInt(autoCommitSwapThresholdAsString);
    } catch (NumberFormatException nfe) {
        // nothing here, being handled in LoadBalancedConnectionProxy.
    }
    String autoCommitSwapRegex = props.getProperty(PropertyKey.loadBalanceAutoCommitStatementRegex.getKeyName(), "");
    if (!"".equals(autoCommitSwapRegex)) {
        this.matchingAfterStatementRegex = autoCommitSwapRegex;
    }
    return this;

}
 
Example #2
Source File: LoadBalancedAutoCommitInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public QueryInterceptor init(MysqlConnection connection, Properties props, Log log) {
    this.conn = (JdbcConnection) connection;

    String autoCommitSwapThresholdAsString = props.getProperty(PropertyDefinitions.PNAME_loadBalanceAutoCommitStatementThreshold, "0");
    try {
        this.matchingAfterStatementThreshold = Integer.parseInt(autoCommitSwapThresholdAsString);
    } catch (NumberFormatException nfe) {
        // nothing here, being handled in LoadBalancedConnectionProxy.
    }
    String autoCommitSwapRegex = props.getProperty(PropertyDefinitions.PNAME_loadBalanceAutoCommitStatementRegex, "");
    if (!"".equals(autoCommitSwapRegex)) {
        this.matchingAfterStatementRegex = autoCommitSwapRegex;
    }
    return this;

}
 
Example #3
Source File: FailoverConnectionProxy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Falls back to primary host or keep current connection if primary not available.
 */
synchronized void fallBackToPrimaryIfAvailable() {
    JdbcConnection connection = null;
    try {
        connection = createConnectionForHostIndex(this.primaryHostIndex);
        switchCurrentConnectionTo(this.primaryHostIndex, connection);
    } catch (SQLException e1) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e2) {
            }
        }
        // Keep current connection and reset counters
        resetAutoFallBackCounters();
    }
}
 
Example #4
Source File: FailoverConnectionProxy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Replaces the previous underlying connection by the connection given. State from previous connection, if any, is synchronized with the new one.
 * 
 * @param hostIndex
 *            The host index in the global hosts list that matches the given connection.
 * @param connection
 *            The connection instance to switch to.
 */
private synchronized void switchCurrentConnectionTo(int hostIndex, JdbcConnection connection) throws SQLException {
    invalidateCurrentConnection();

    boolean readOnly;
    if (isPrimaryHostIndex(hostIndex)) {
        readOnly = this.explicitlyReadOnly == null ? false : this.explicitlyReadOnly;
    } else if (this.failoverReadOnly) {
        readOnly = true;
    } else if (this.explicitlyReadOnly != null) {
        readOnly = this.explicitlyReadOnly;
    } else if (this.currentConnection != null) {
        readOnly = this.currentConnection.isReadOnly();
    } else {
        readOnly = false;
    }
    syncSessionState(this.currentConnection, connection, readOnly);
    this.currentConnection = connection;
    this.currentHostIndex = hostIndex;
}
 
Example #5
Source File: FailoverConnectionProxy.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Falls back to primary host or keep current connection if primary not available.
 */
synchronized void fallBackToPrimaryIfAvailable() {
    JdbcConnection connection = null;
    try {
        connection = createConnectionForHostIndex(this.primaryHostIndex);
        switchCurrentConnectionTo(this.primaryHostIndex, connection);
    } catch (SQLException e1) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e2) {
            }
        }
        // Keep current connection and reset counters
        resetAutoFallBackCounters();
    }
}
 
Example #6
Source File: UtilsTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests Util.isJdbcPackage()
 * 
 * @throws Exception
 */
public void testGetImplementedInterfaces() throws Exception {
    Class<?>[] ifaces;
    ifaces = Util.getImplementedInterfaces(JdbcStatement.class);
    assertEquals(2, ifaces.length);
    assertEquals(ifaces[0], java.sql.Statement.class);

    ifaces = Util.getImplementedInterfaces(StatementImpl.class);
    assertEquals(1, ifaces.length);
    assertEquals(ifaces[0], JdbcStatement.class);

    ifaces = Util.getImplementedInterfaces(ConnectionImpl.class);
    assertEquals(3, ifaces.length);
    List<Class<?>> ifacesList = Arrays.asList(ifaces);
    for (Class<?> clazz : new Class<?>[] { JdbcConnection.class, Serializable.class }) {
        assertTrue(ifacesList.contains(clazz));
    }
}
 
Example #7
Source File: LoadBalancedConnectionProxy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Closes specified connection and removes it from required mappings.
 * 
 * @param conn
 * @throws SQLException
 */
@Override
synchronized void invalidateConnection(JdbcConnection conn) throws SQLException {
    super.invalidateConnection(conn);

    // add host to the global blacklist, if enabled
    if (this.isGlobalBlacklistEnabled()) {
        addToGlobalBlacklist(this.connectionsToHostsMap.get(conn));
    }

    // remove from liveConnections
    this.liveConnections.remove(this.connectionsToHostsMap.get(conn));
    Object mappedHost = this.connectionsToHostsMap.remove(conn);
    if (mappedHost != null && this.hostsToListIndexMap.containsKey(mappedHost)) {
        int hostIndex = this.hostsToListIndexMap.get(mappedHost);
        // reset the statistics for the host
        synchronized (this.responseTimes) {
            this.responseTimes[hostIndex] = 0;
        }
    }
}
 
Example #8
Source File: LoadBalancedConnectionProxy.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Closes specified connection and removes it from required mappings.
 * 
 * @param conn
 *            connection
 * @throws SQLException
 *             if an error occurs
 */
@Override
synchronized void invalidateConnection(JdbcConnection conn) throws SQLException {
    super.invalidateConnection(conn);

    // add host to the global blacklist, if enabled
    if (this.isGlobalBlacklistEnabled()) {
        addToGlobalBlacklist(this.connectionsToHostsMap.get(conn));
    }

    // remove from liveConnections
    this.liveConnections.remove(this.connectionsToHostsMap.get(conn));
    Object mappedHost = this.connectionsToHostsMap.remove(conn);
    if (mappedHost != null && this.hostsToListIndexMap.containsKey(mappedHost)) {
        int hostIndex = this.hostsToListIndexMap.get(mappedHost);
        // reset the statistics for the host
        synchronized (this.responseTimes) {
            this.responseTimes[hostIndex] = 0;
        }
    }
}
 
Example #9
Source File: LoadBalancedConnectionProxy.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public synchronized String getCurrentActiveHost() {
    JdbcConnection c = this.currentConnection;
    if (c != null) {
        Object o = this.connectionsToHostsMap.get(c);
        if (o != null) {
            return o.toString();
        }
    }
    return null;
}
 
Example #10
Source File: MysqlConnectionTester.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public MysqlConnectionTester() {
    try {
        this.pingMethod = JdbcConnection.class.getMethod("ping", (Class[]) null);
    } catch (Exception ex) {
        // punt, we have no way to recover, other than we now use 'SELECT 1' for handling the connection testing.
    }
}
 
Example #11
Source File: ConnectionTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public void testLocalInfileDisabled() throws Exception {
    createTable("testLocalInfileDisabled", "(field1 varchar(255))");

    File infile = File.createTempFile("foo", "txt");
    infile.deleteOnExit();
    //String url = infile.toURL().toExternalForm();
    FileWriter output = new FileWriter(infile);
    output.write("Test");
    output.flush();
    output.close();

    Connection loadConn = getConnectionWithProps(new Properties());

    try {
        // have to do this after connect, otherwise it's the server that's enforcing it
        ((com.mysql.cj.jdbc.JdbcConnection) loadConn).getPropertySet().getProperty(PropertyKey.allowLoadLocalInfile).setValue(false);
        try {
            loadConn.createStatement().execute("LOAD DATA LOCAL INFILE '" + infile.getCanonicalPath() + "' INTO TABLE testLocalInfileDisabled");
            fail("Should've thrown an exception.");
        } catch (SQLException sqlEx) {
            assertEquals(MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, sqlEx.getSQLState());
        }

        assertFalse(loadConn.createStatement().executeQuery("SELECT * FROM testLocalInfileDisabled").next());
    } finally {
        loadConn.close();
    }
}
 
Example #12
Source File: MiniAdmin.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new MiniAdmin using the given connection
 * 
 * @param conn
 *            the existing connection to use.
 * 
 * @throws SQLException
 *             if an error occurs
 */
public MiniAdmin(java.sql.Connection conn) throws SQLException {
    if (conn == null) {
        throw SQLError.createSQLException(Messages.getString("MiniAdmin.0"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, null);
    }

    if (!(conn instanceof JdbcConnection)) {
        throw SQLError.createSQLException(Messages.getString("MiniAdmin.1"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR,
                ((com.mysql.cj.jdbc.ConnectionImpl) conn).getExceptionInterceptor());
    }

    this.conn = (JdbcConnection) conn;
}
 
Example #13
Source File: MiniAdmin.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new MiniAdmin using the given connection
 * 
 * @param conn
 *            the existing connection to use.
 * 
 * @throws SQLException
 *             if an error occurs
 */
public MiniAdmin(java.sql.Connection conn) throws SQLException {
    if (conn == null) {
        throw SQLError.createSQLException(Messages.getString("MiniAdmin.0"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, null);
    }

    if (!(conn instanceof JdbcConnection)) {
        throw SQLError.createSQLException(Messages.getString("MiniAdmin.1"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR,
                ((com.mysql.cj.jdbc.ConnectionImpl) conn).getExceptionInterceptor());
    }

    this.conn = (JdbcConnection) conn;
}
 
Example #14
Source File: MysqlConnectionTester.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int activeCheckConnection(Connection con) {
    try {
        if (this.pingMethod != null) {
            if (con instanceof JdbcConnection) {
                // We've been passed an instance of a MySQL connection -- no need for reflection
                ((JdbcConnection) con).ping();
            } else {
                // Assume the connection is a C3P0 proxy
                C3P0ProxyConnection castCon = (C3P0ProxyConnection) con;
                castCon.rawConnectionOperation(this.pingMethod, C3P0ProxyConnection.RAW_CONNECTION, NO_ARGS_ARRAY);
            }
        } else {
            Statement pingStatement = null;

            try {
                pingStatement = con.createStatement();
                pingStatement.executeQuery("SELECT 1").close();
            } finally {
                if (pingStatement != null) {
                    pingStatement.close();
                }
            }
        }

        return CONNECTION_IS_OKAY;
    } catch (Exception ex) {
        return CONNECTION_IS_INVALID;
    }
}
 
Example #15
Source File: ReplicationMySQLConnection.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private JdbcConnection getValidatedMasterConnection() {
    JdbcConnection conn = getThisAsProxy().masterConnection;
    try {
        return conn == null || conn.isClosed() ? null : conn;
    } catch (SQLException e) {
        return null;
    }
}
 
Example #16
Source File: ResultSetImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Ensures that the result set is not closed
 * 
 * @throws SQLException
 *             if the result set is closed
 */
protected final JdbcConnection checkClosed() throws SQLException {
    JdbcConnection c = this.connection;

    if (c == null) {
        throw SQLError.createSQLException(Messages.getString("ResultSet.Operation_not_allowed_after_ResultSet_closed_144"),
                MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
    }

    return c;
}
 
Example #17
Source File: ReplicationMySQLConnection.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void setStatementComment(String comment) {
    JdbcConnection conn;
    if ((conn = getValidatedMasterConnection()) != null) {
        conn.setStatementComment(comment);
    }
    if ((conn = getValidatedSlavesConnection()) != null) {
        conn.setStatementComment(comment);
    }
}
 
Example #18
Source File: MultiHostConnectionProxy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Synchronizes session state between two connections.
 * 
 * @param source
 *            The connection where to get state from.
 * @param target
 *            The connection where to set state.
 */
void syncSessionState(JdbcConnection source, JdbcConnection target) throws SQLException {
    if (source == null || target == null) {
        return;
    }

    ModifiableProperty<Boolean> sourceUseLocalSessionState = source.getPropertySet()
            .getBooleanModifiableProperty(PropertyDefinitions.PNAME_useLocalSessionState);
    boolean prevUseLocalSessionState = sourceUseLocalSessionState.getValue();
    sourceUseLocalSessionState.setValue(true);
    boolean readOnly = source.isReadOnly();
    sourceUseLocalSessionState.setValue(prevUseLocalSessionState);

    syncSessionState(source, target, readOnly);
}
 
Example #19
Source File: ReplicationMySQLConnection.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private JdbcConnection getValidatedSlavesConnection() {
    JdbcConnection conn = getThisAsProxy().slavesConnection;
    try {
        return conn == null || conn.isClosed() ? null : conn;
    } catch (SQLException e) {
        return null;
    }
}
 
Example #20
Source File: ReplicationMySQLConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private JdbcConnection getValidatedSlavesConnection() {
    JdbcConnection conn = getThisAsProxy().slavesConnection;
    try {
        return conn == null || conn.isClosed() ? null : conn;
    } catch (SQLException e) {
        return null;
    }
}
 
Example #21
Source File: BaseTestCase.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
protected void dropSchemaObject(Statement st, String objectType, String objectName) throws SQLException {
    if (st != null) {
        if (!objectType.equalsIgnoreCase("USER") || ((JdbcConnection) st.getConnection()).getSession().versionMeetsMinimum(5, 7, 8)) {
            st.executeUpdate("DROP " + objectType + " IF EXISTS " + objectName);
        } else {
            st.executeUpdate("DROP " + objectType + " " + objectName);
        }
        st.executeUpdate("flush privileges");
    }
}
 
Example #22
Source File: ReplicationMySQLConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean hasSameProperties(JdbcConnection c) {
    JdbcConnection connM = getValidatedMasterConnection();
    JdbcConnection connS = getValidatedSlavesConnection();
    if (connM == null && connS == null) {
        return false;
    }
    return (connM == null || connM.hasSameProperties(c)) && (connS == null || connS.hasSameProperties(c));
}
 
Example #23
Source File: ReplicationMySQLConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Properties getProperties() {
    Properties props = new Properties();
    JdbcConnection conn;
    if ((conn = getValidatedMasterConnection()) != null) {
        props.putAll(conn.getProperties());
    }
    if ((conn = getValidatedSlavesConnection()) != null) {
        props.putAll(conn.getProperties());
    }

    return props;
}
 
Example #24
Source File: ReplicationConnectionProxy.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Propagates the connection proxy down through all live connections.
 * 
 * @param proxyConn
 *            The top level connection in the multi-host connections chain.
 */
@Override
protected void propagateProxyDown(JdbcConnection proxyConn) {
    if (this.masterConnection != null) {
        this.masterConnection.setProxy(proxyConn);
    }
    if (this.slavesConnection != null) {
        this.slavesConnection.setProxy(proxyConn);
    }
}
 
Example #25
Source File: ReplicationMySQLConnection.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Properties getProperties() {
    Properties props = new Properties();
    JdbcConnection conn;
    if ((conn = getValidatedMasterConnection()) != null) {
        props.putAll(conn.getProperties());
    }
    if ((conn = getValidatedSlavesConnection()) != null) {
        props.putAll(conn.getProperties());
    }

    return props;
}
 
Example #26
Source File: ReplicationConnectionProxy.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private JdbcConnection initializeSlavesConnection() throws SQLException {
    this.slavesConnection = null;

    if (this.slaveHosts.size() == 0) {
        return null;
    }

    LoadBalancedConnection newSlavesConn = LoadBalancedConnectionProxy
            .createProxyInstance(new LoadbalanceConnectionUrl(this.slaveHosts, this.connectionUrl.getOriginalProperties()));
    newSlavesConn.setProxy(getProxy());
    newSlavesConn.setReadOnly(true);

    this.slavesConnection = newSlavesConn;
    return this.slavesConnection;
}
 
Example #27
Source File: MultiHostConnectionProxy.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Invalidates the specified connection by closing it.
 * 
 * @param conn
 *            The connection instance to invalidate.
 * @throws SQLException
 *             if an error occurs
 */
synchronized void invalidateConnection(JdbcConnection conn) throws SQLException {
    try {
        if (conn != null && !conn.isClosed()) {
            conn.realClose(true, !conn.getAutoCommit(), true, null);
        }
    } catch (SQLException e) {
        // swallow this exception, current connection should be useless anyway.
    }
}
 
Example #28
Source File: SQLError.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public static SQLException createCommunicationsException(JdbcConnection conn, PacketSentTimeHolder packetSentTimeHolder,
        PacketReceivedTimeHolder packetReceivedTimeHolder, Exception underlyingException, ExceptionInterceptor interceptor) {

    SQLException exToReturn = new CommunicationsException(conn, packetSentTimeHolder, packetReceivedTimeHolder, underlyingException);

    if (underlyingException != null) {
        try {
            exToReturn.initCause(underlyingException);
        } catch (Throwable t) {
            // we're not going to muck with that here, since it's an error condition anyway!
        }
    }

    return runThroughExceptionInterceptor(interceptor, exToReturn);
}
 
Example #29
Source File: ReplicationConnectionProxy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private JdbcConnection initializeMasterConnection() throws SQLException {
    this.masterConnection = null;

    if (this.masterHosts.size() == 0) {
        return null;
    }

    LoadBalancedConnection newMasterConn = LoadBalancedConnectionProxy
            .createProxyInstance(new LoadbalanceConnectionUrl(this.masterHosts, this.connectionUrl.getOriginalProperties()));
    newMasterConn.setProxy(getProxy());

    this.masterConnection = newMasterConn;
    return this.masterConnection;
}
 
Example #30
Source File: ReplicationConnectionProxy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Propagates the connection proxy down through all live connections.
 * 
 * @param proxyConn
 *            The top level connection in the multi-host connections chain.
 */
@Override
protected void propagateProxyDown(JdbcConnection proxyConn) {
    if (this.masterConnection != null) {
        this.masterConnection.setProxy(proxyConn);
    }
    if (this.slavesConnection != null) {
        this.slavesConnection.setProxy(proxyConn);
    }
}