Java Code Examples for com.mysql.cj.jdbc.JdbcConnection

The following examples show how to use com.mysql.cj.jdbc.JdbcConnection. These examples are extracted from open source projects. 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
/**
 * 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 2
/**
 * 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 3
Source Project: lams   Source File: FailoverConnectionProxy.java    License: 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 4
Source Project: lams   Source File: FailoverConnectionProxy.java    License: 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 5
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 6
@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 7
Source Project: FoxTelem   Source File: UtilsTest.java    License: 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 8
/**
 * 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 Project: lams   Source File: MysqlConnectionTester.java    License: 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 10
Source Project: FoxTelem   Source File: ConnectionTest.java    License: 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 11
Source Project: lams   Source File: MiniAdmin.java    License: 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 12
@Override
public synchronized void setStatementComment(String comment) {
    JdbcConnection conn;
    if ((conn = getValidatedMasterConnection()) != null) {
        conn.setStatementComment(comment);
    }
    if ((conn = getValidatedSlavesConnection()) != null) {
        conn.setStatementComment(comment);
    }
}
 
Example 13
/**
 * 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 14
private JdbcConnection getValidatedMasterConnection() {
    JdbcConnection conn = getThisAsProxy().masterConnection;
    try {
        return conn == null || conn.isClosed() ? null : conn;
    } catch (SQLException e) {
        return null;
    }
}
 
Example 15
private JdbcConnection getValidatedSlavesConnection() {
    JdbcConnection conn = getThisAsProxy().slavesConnection;
    try {
        return conn == null || conn.isClosed() ? null : conn;
    } catch (SQLException e) {
        return null;
    }
}
 
Example 16
/**
 * 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) {
    for (JdbcConnection c : this.liveConnections.values()) {
        c.setProxy(proxyConn);
    }
}
 
Example 17
Source Project: FoxTelem   Source File: BaseTestCase.java    License: 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 18
@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 19
@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 20
/**
 * 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 21
private JdbcConnection getValidatedMasterConnection() {
    JdbcConnection conn = getThisAsProxy().masterConnection;
    try {
        return conn == null || conn.isClosed() ? null : conn;
    } catch (SQLException e) {
        return null;
    }
}
 
Example 22
@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 23
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 24
Source Project: FoxTelem   Source File: SQLError.java    License: 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 25
/**
 * 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 26
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 27
@Override
void syncSessionState(JdbcConnection source, JdbcConnection target, boolean readOnly) throws SQLException {
    LoadBalancedAutoCommitInterceptor lbAutoCommitStmtInterceptor = null;
    for (QueryInterceptor stmtInterceptor : target.getQueryInterceptorsInstances()) {
        if (stmtInterceptor instanceof LoadBalancedAutoCommitInterceptor) {
            lbAutoCommitStmtInterceptor = (LoadBalancedAutoCommitInterceptor) stmtInterceptor;
            lbAutoCommitStmtInterceptor.pauseCounters();
            break;
        }
    }
    super.syncSessionState(source, target, readOnly);
    if (lbAutoCommitStmtInterceptor != null) {
        lbAutoCommitStmtInterceptor.resumeCounters();
    }
}
 
Example 28
private JdbcConnection getValidatedSlavesConnection() {
    JdbcConnection conn = getThisAsProxy().slavesConnection;
    try {
        return conn == null || conn.isClosed() ? null : conn;
    } catch (SQLException e) {
        return null;
    }
}
 
Example 29
Source Project: lams   Source File: ResultSetImpl.java    License: 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 30
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;
}