Search in sources :

Example 6 with CJException

use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.

the class AbstractQuery method checkCancelTimeout.

@Override
public void checkCancelTimeout() {
    synchronized (this.cancelTimeoutMutex) {
        if (this.cancelStatus != CancelStatus.NOT_CANCELED) {
            CJException cause = this.cancelStatus == CancelStatus.CANCELED_BY_TIMEOUT ? new CJTimeoutException() : new OperationCancelledException();
            resetCancelledState();
            throw cause;
        }
    }
}
Also used : OperationCancelledException(com.mysql.cj.exceptions.OperationCancelledException) CJTimeoutException(com.mysql.cj.exceptions.CJTimeoutException) CJException(com.mysql.cj.exceptions.CJException)

Example 7 with CJException

use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.

the class ConnectionImpl method connectOneTryOnly.

private void connectOneTryOnly(boolean isForReconnect) throws SQLException {
    Exception connectionNotEstablishedBecause = null;
    try {
        JdbcConnection c = getProxy();
        this.session.connect(this.origHostInfo, this.user, this.password, this.database, getLoginTimeout(), c);
        // save state from old connection
        boolean oldAutoCommit = getAutoCommit();
        int oldIsolationLevel = this.isolationLevel;
        boolean oldReadOnly = isReadOnly(false);
        String oldDb = getDatabase();
        this.session.setQueryInterceptors(this.queryInterceptors);
        // Server properties might be different from previous connection, so initialize again...
        initializePropsFromServer();
        if (isForReconnect) {
            // Restore state from old connection
            setAutoCommit(oldAutoCommit);
            setTransactionIsolation(oldIsolationLevel);
            setDatabase(oldDb);
            setReadOnly(oldReadOnly);
        }
        return;
    } catch (UnableToConnectException rejEx) {
        close();
        this.session.getProtocol().getSocketConnection().forceClose();
        throw rejEx;
    } catch (Exception EEE) {
        if ((EEE instanceof PasswordExpiredException || EEE instanceof SQLException && ((SQLException) EEE).getErrorCode() == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD) && !this.disconnectOnExpiredPasswords.getValue()) {
            return;
        }
        if (this.session != null) {
            this.session.forceClose();
        }
        connectionNotEstablishedBecause = EEE;
        if (EEE instanceof SQLException) {
            throw (SQLException) EEE;
        }
        if (EEE.getCause() != null && EEE.getCause() instanceof SQLException) {
            throw (SQLException) EEE.getCause();
        }
        if (EEE instanceof CJException) {
            throw (CJException) EEE;
        }
        SQLException chainedEx = SQLError.createSQLException(Messages.getString("Connection.UnableToConnect"), MysqlErrorNumbers.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, getExceptionInterceptor());
        chainedEx.initCause(connectionNotEstablishedBecause);
        throw chainedEx;
    }
}
Also used : PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) SQLException(java.sql.SQLException) CJException(com.mysql.cj.exceptions.CJException) CJCommunicationsException(com.mysql.cj.exceptions.CJCommunicationsException) UnableToConnectException(com.mysql.cj.exceptions.UnableToConnectException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) Savepoint(java.sql.Savepoint) UnableToConnectException(com.mysql.cj.exceptions.UnableToConnectException) CJException(com.mysql.cj.exceptions.CJException)

Example 8 with CJException

use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.

the class ServerPreparedStatement method serverPrepare.

protected void serverPrepare(String sql) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        SQLException t = null;
        try {
            ServerPreparedQuery q = (ServerPreparedQuery) this.query;
            q.serverPrepare(sql);
        } catch (IOException ioEx) {
            t = SQLError.createCommunicationsException(this.connection, this.session.getProtocol().getPacketSentTimeHolder(), this.session.getProtocol().getPacketReceivedTimeHolder(), ioEx, this.exceptionInterceptor);
        } catch (CJException sqlEx) {
            SQLException ex = SQLExceptionsMapping.translateException(sqlEx);
            if (this.dumpQueriesOnException.getValue()) {
                StringBuilder messageBuf = new StringBuilder(((PreparedQuery<?>) this.query).getOriginalSql().length() + 32);
                messageBuf.append("\n\nQuery being prepared when exception was thrown:\n\n");
                messageBuf.append(((PreparedQuery<?>) this.query).getOriginalSql());
                ex = appendMessageToException(ex, messageBuf.toString(), this.exceptionInterceptor);
            }
            t = ex;
        } finally {
            // Leave the I/O channel in a known state...there might be packets out there that we're not interested in
            try {
                this.session.clearInputStream();
            } catch (Exception e) {
                if (t == null) {
                    t = SQLError.createCommunicationsException(this.connection, this.session.getProtocol().getPacketSentTimeHolder(), this.session.getProtocol().getPacketReceivedTimeHolder(), e, this.exceptionInterceptor);
                }
            }
            if (t != null) {
                throw t;
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) ServerPreparedQuery(com.mysql.cj.ServerPreparedQuery) PreparedQuery(com.mysql.cj.PreparedQuery) IOException(java.io.IOException) ServerPreparedQuery(com.mysql.cj.ServerPreparedQuery) CJException(com.mysql.cj.exceptions.CJException) SQLException(java.sql.SQLException) WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) MySQLStatementCancelledException(com.mysql.cj.jdbc.exceptions.MySQLStatementCancelledException) IOException(java.io.IOException) MySQLTimeoutException(com.mysql.cj.jdbc.exceptions.MySQLTimeoutException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CJException(com.mysql.cj.exceptions.CJException)

Example 9 with CJException

use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.

the class SessionFactory method getSession.

/**
 * Creates {@link Session} by given URL.
 *
 * @param connUrl
 *            the session {@link ConnectionUrl}.
 * @return a {@link Session} instance.
 */
protected Session getSession(ConnectionUrl connUrl) {
    CJException latestException = null;
    List<HostInfo> hostsList = connUrl.getHostsList();
    for (HostInfo hi : hostsList) {
        try {
            return new SessionImpl(hi);
        } catch (CJCommunicationsException e) {
            if (e.getCause() == null) {
                throw e;
            }
            latestException = e;
        }
    }
    if (latestException != null) {
        throw ExceptionFactory.createException(CJCommunicationsException.class, Messages.getString("Session.Create.Failover.0"), latestException);
    }
    return null;
}
Also used : HostInfo(com.mysql.cj.conf.HostInfo) CJCommunicationsException(com.mysql.cj.exceptions.CJCommunicationsException) CJException(com.mysql.cj.exceptions.CJException)

Example 10 with CJException

use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.

the class AuthenticationTest method authLdapSaslCliPluginChallengeMissingAttributes.

/**
 * Test wrong 'server-first-message' due to missing attributes.
 * Data based on test vector from <a href="https://tools.ietf.org/html/rfc5802#section-5">RFC 5802, Section 5</a>.
 *
 * @throws Exception
 */
@Test
public void authLdapSaslCliPluginChallengeMissingAttributes() throws Exception {
    // Server's 'server-first-message' attributes:
    String ar = "r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j";
    String as = "s=QSXCR+Q6sek8bf92";
    String ai = "i=4096";
    for (int i = 0; i < 3; i++) {
        AuthenticationPlugin<NativePacketPayload> authPlugin = new AuthenticationLdapSaslClientPlugin();
        // Initialize plugin with some protocol (none is needed).
        authPlugin.init(null);
        // Set authentication parameters.
        authPlugin.setAuthenticationParameters("user", "pencil");
        // Initial server packet: Protocol::AuthSwitchRequest
        // [authentication_ldap_sasl_client.SCRAM-SHA-1]
        // ;; "." --> 0 byte.
        // ;; first part of the packet is already processed.
        NativePacketPayload challenge = new NativePacketPayload("SCRAM-SHA-1".getBytes("ASCII"));
        // Expected 'client-first-message':
        // [n,,n=user,r=<CNONCE>]
        // ;; <CNONCE> is generated internally and needs to be replaced by the expected value from the test vector in order to continue the test.
        List<NativePacketPayload> response = new ArrayList<>();
        authPlugin.nextAuthenticationStep(challenge, response);
        assertEquals(1, response.size());
        String data = response.get(0).readString(StringSelfDataType.STRING_EOF, "UTF-8");
        assertTrue(data.startsWith("n,,n=user,r="));
        assertEquals("n,,n=user,r=".length() + 32, data.length());
        // Server's 'server-first-message':
        // [r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096]
        // ;; But skip one of the attributes at a time.
        String sfm = null;
        switch(i) {
            case 0:
                sfm = String.join(",", as, ai);
                break;
            case 1:
                sfm = String.join(",", ar, ai);
                break;
            case 2:
                sfm = String.join(",", ar, as);
                break;
        }
        NativePacketPayload badChallenge = new NativePacketPayload(sfm.getBytes("UTF-8"));
        // Expect Exception.
        CJException ex = assertThrows(CJException.class, "Error while processing an authentication iteration for the authentication mechanism 'SCRAM-SHA-1'\\.", () -> authPlugin.nextAuthenticationStep(badChallenge, response));
        assertEquals(SaslException.class, ex.getCause().getClass());
        assertEquals("Missing required SCRAM attribute from server first message.", ex.getCause().getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) AuthenticationLdapSaslClientPlugin(com.mysql.cj.protocol.a.authentication.AuthenticationLdapSaslClientPlugin) NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) CJException(com.mysql.cj.exceptions.CJException) Test(org.junit.jupiter.api.Test)

Aggregations

CJException (com.mysql.cj.exceptions.CJException)21 NativePacketPayload (com.mysql.cj.protocol.a.NativePacketPayload)9 ArrayList (java.util.ArrayList)6 AuthenticationLdapSaslClientPlugin (com.mysql.cj.protocol.a.authentication.AuthenticationLdapSaslClientPlugin)5 Test (org.junit.jupiter.api.Test)5 CJCommunicationsException (com.mysql.cj.exceptions.CJCommunicationsException)4 IOException (java.io.IOException)4 SQLException (java.sql.SQLException)4 UnableToConnectException (com.mysql.cj.exceptions.UnableToConnectException)3 WrongArgumentException (com.mysql.cj.exceptions.WrongArgumentException)3 ServerPreparedQuery (com.mysql.cj.ServerPreparedQuery)2 OperationCancelledException (com.mysql.cj.exceptions.OperationCancelledException)2 PasswordExpiredException (com.mysql.cj.exceptions.PasswordExpiredException)2 Resultset (com.mysql.cj.protocol.Resultset)2 LazyString (com.mysql.cj.util.LazyString)2 Properties (java.util.Properties)2 NativeSession (com.mysql.cj.NativeSession)1 PreparedQuery (com.mysql.cj.PreparedQuery)1 UsernameCallback (com.mysql.cj.callback.UsernameCallback)1 HostInfo (com.mysql.cj.conf.HostInfo)1