Search in sources :

Example 1 with CJException

use of com.mysql.cj.exceptions.CJException in project ABC by RuiPinto96274.

the class ServerPreparedQuery method sendExecutePacket.

public NativePacketPayload sendExecutePacket(NativePacketPayload packet, String queryAsString) {
    // TODO queryAsString should be shared instead of passed
    final long begin = this.session.getCurrentTimeNanosOrMillis();
    resetCancelledState();
    CancelQueryTask timeoutTask = null;
    try {
        // Get this before executing to avoid a shared packet pollution in the case some other query is issued internally, such as when using I_S.
        timeoutTask = startQueryTimer(this, this.timeoutInMillis);
        statementBegins();
        NativePacketPayload resultPacket = this.session.sendCommand(packet, false, 0);
        final long queryEndTime = this.session.getCurrentTimeNanosOrMillis();
        if (timeoutTask != null) {
            stopQueryTimer(timeoutTask, true, true);
            timeoutTask = null;
        }
        final long executeTime = queryEndTime - begin;
        setExecuteTime(executeTime);
        if (this.logSlowQueries) {
            this.queryWasSlow = // 
            this.useAutoSlowLog ? this.session.getProtocol().getMetricsHolder().checkAbonormallyLongQuery(executeTime) : executeTime > this.slowQueryThresholdMillis.getValue();
            if (this.queryWasSlow) {
                this.session.getProfilerEventHandler().processEvent(ProfilerEvent.TYPE_SLOW_QUERY, this.session, this, null, executeTime, new Throwable(), Messages.getString("ServerPreparedStatement.15", new String[] { String.valueOf(this.session.getSlowQueryThreshold()), String.valueOf(executeTime), this.originalSql, queryAsString }));
            }
        }
        if (this.gatherPerfMetrics) {
            this.session.getProtocol().getMetricsHolder().registerQueryExecutionTime(executeTime);
            this.session.getProtocol().getMetricsHolder().incrementNumberOfPreparedExecutes();
        }
        if (this.profileSQL) {
            this.session.getProfilerEventHandler().processEvent(ProfilerEvent.TYPE_EXECUTE, this.session, this, null, executeTime, new Throwable(), truncateQueryToLog(queryAsString));
        }
        return resultPacket;
    } catch (CJException sqlEx) {
        if (this.session.shouldIntercept()) {
            this.session.invokeQueryInterceptorsPost(() -> {
                return getOriginalSql();
            }, this, null, true);
        }
        throw sqlEx;
    } finally {
        this.statementExecuting.set(false);
        stopQueryTimer(timeoutTask, false, false);
    }
}
Also used : NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) CJException(com.mysql.cj.exceptions.CJException)

Example 2 with CJException

use of com.mysql.cj.exceptions.CJException in project ABC by RuiPinto96274.

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 3 with CJException

use of com.mysql.cj.exceptions.CJException in project ABC by RuiPinto96274.

the class NativeProtocol method explainSlowQuery.

/**
 * Runs an 'EXPLAIN' on the given query and dumps the results to the log
 *
 * @param query
 *            full query string
 * @param truncatedQuery
 *            query string truncated for profiling
 */
public void explainSlowQuery(String query, String truncatedQuery) {
    if (StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT) || (versionMeetsMinimum(5, 6, 3) && StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT_EXTENSION) != -1)) {
        try {
            NativePacketPayload resultPacket = sendCommand(getCommandBuilder().buildComQuery(getSharedSendPacket(), "EXPLAIN " + query), false, 0);
            Resultset rs = readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));
            StringBuilder explainResults = new StringBuilder(Messages.getString("Protocol.6"));
            explainResults.append(truncatedQuery);
            explainResults.append(Messages.getString("Protocol.7"));
            appendResultSetSlashGStyle(explainResults, rs);
            this.log.logWarn(explainResults.toString());
        } catch (CJException sqlEx) {
            throw sqlEx;
        } catch (Exception ex) {
            throw ExceptionFactory.createException(ex.getMessage(), ex, getExceptionInterceptor());
        }
    }
}
Also used : Resultset(com.mysql.cj.protocol.Resultset) CJException(com.mysql.cj.exceptions.CJException) WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) CJCommunicationsException(com.mysql.cj.exceptions.CJCommunicationsException) InvalidPathException(java.nio.file.InvalidPathException) CJConnectionFeatureNotAvailableException(com.mysql.cj.exceptions.CJConnectionFeatureNotAvailableException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) CJPacketTooBigException(com.mysql.cj.exceptions.CJPacketTooBigException) URISyntaxException(java.net.URISyntaxException) DataTruncationException(com.mysql.cj.exceptions.DataTruncationException) FeatureNotAvailableException(com.mysql.cj.exceptions.FeatureNotAvailableException) MalformedURLException(java.net.MalformedURLException) CJOperationNotSupportedException(com.mysql.cj.exceptions.CJOperationNotSupportedException) ClosedOnExpiredPasswordException(com.mysql.cj.exceptions.ClosedOnExpiredPasswordException) CJException(com.mysql.cj.exceptions.CJException)

Example 4 with CJException

use of com.mysql.cj.exceptions.CJException in project ABC by RuiPinto96274.

the class DefaultPropertySet method initializeProperties.

public void initializeProperties(Properties props) {
    if (props != null) {
        Properties infoCopy = (Properties) props.clone();
        // TODO do we need to remove next properties (as it was before)?
        infoCopy.remove(PropertyKey.HOST.getKeyName());
        infoCopy.remove(PropertyKey.PORT.getKeyName());
        infoCopy.remove(PropertyKey.USER.getKeyName());
        infoCopy.remove(PropertyKey.PASSWORD.getKeyName());
        infoCopy.remove(PropertyKey.DBNAME.getKeyName());
        for (PropertyKey propKey : PropertyDefinitions.PROPERTY_KEY_TO_PROPERTY_DEFINITION.keySet()) {
            try {
                RuntimeProperty<?> propToSet = getProperty(propKey);
                propToSet.initializeFrom(infoCopy, null);
            } catch (CJException e) {
                throw ExceptionFactory.createException(WrongArgumentException.class, e.getMessage(), e);
            }
        }
        // Translate legacy SSL properties if sslMode isn't explicitly set. Default sslMode is PREFERRED.
        RuntimeProperty<SslMode> sslMode = this.<SslMode>getEnumProperty(PropertyKey.sslMode);
        if (!sslMode.isExplicitlySet()) {
            RuntimeProperty<Boolean> useSSL = this.getBooleanProperty(PropertyKey.useSSL);
            RuntimeProperty<Boolean> verifyServerCertificate = this.getBooleanProperty(PropertyKey.verifyServerCertificate);
            RuntimeProperty<Boolean> requireSSL = this.getBooleanProperty(PropertyKey.requireSSL);
            if (useSSL.isExplicitlySet() || verifyServerCertificate.isExplicitlySet() || requireSSL.isExplicitlySet()) {
                if (!useSSL.getValue()) {
                    sslMode.setValue(SslMode.DISABLED);
                } else if (verifyServerCertificate.getValue()) {
                    sslMode.setValue(SslMode.VERIFY_CA);
                } else if (requireSSL.getValue()) {
                    sslMode.setValue(SslMode.REQUIRED);
                }
            }
        }
        // add user-defined properties
        for (Object key : infoCopy.keySet()) {
            String val = infoCopy.getProperty((String) key);
            PropertyDefinition<String> def = new StringPropertyDefinition((String) key, null, val, PropertyDefinitions.RUNTIME_MODIFIABLE, Messages.getString("ConnectionProperties.unknown"), "8.0.10", PropertyDefinitions.CATEGORY_USER_DEFINED, Integer.MIN_VALUE);
            RuntimeProperty<String> p = new StringProperty(def);
            addProperty(p);
        }
        postInitialization();
    }
}
Also used : WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) Properties(java.util.Properties) SslMode(com.mysql.cj.conf.PropertyDefinitions.SslMode) CJException(com.mysql.cj.exceptions.CJException)

Example 5 with CJException

use of com.mysql.cj.exceptions.CJException in project ABC by RuiPinto96274.

the class AuthenticationTest method authLdapSaslCliPluginChallengeBadNonce.

/**
 * Test wrong 'server-first-message' due to bad server nonce.
 * 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 authLdapSaslCliPluginChallengeBadNonce() throws Exception {
    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());
    // Replace the internal plugin data in order to match the expected 'client-first-message':
    // [n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL]
    overrideSaslClientData(authPlugin, "fyko+d2lbbFgONRv9qkxdawL");
    // Server's 'server-first-message':
    // [r=XXXXXXXXXXXXXXXXXXXXXXXX3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096]
    // ;; Bad 'r' attribute.
    NativePacketPayload badChallenge = new NativePacketPayload("r=XXXXXXXXXXXXXXXXXXXXXXXX3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096".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("Invalid server nonce for SCRAM-SHA-1 authentication.", 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)63 NativePacketPayload (com.mysql.cj.protocol.a.NativePacketPayload)27 ArrayList (java.util.ArrayList)18 AuthenticationLdapSaslClientPlugin (com.mysql.cj.protocol.a.authentication.AuthenticationLdapSaslClientPlugin)15 Test (org.junit.jupiter.api.Test)15 IOException (java.io.IOException)12 SQLException (java.sql.SQLException)12 CJCommunicationsException (com.mysql.cj.exceptions.CJCommunicationsException)10 UnableToConnectException (com.mysql.cj.exceptions.UnableToConnectException)9 WrongArgumentException (com.mysql.cj.exceptions.WrongArgumentException)9 ServerPreparedQuery (com.mysql.cj.ServerPreparedQuery)6 OperationCancelledException (com.mysql.cj.exceptions.OperationCancelledException)6 PasswordExpiredException (com.mysql.cj.exceptions.PasswordExpiredException)6 Resultset (com.mysql.cj.protocol.Resultset)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 Properties (java.util.Properties)6 LazyString (com.mysql.cj.util.LazyString)5 NativeSession (com.mysql.cj.NativeSession)3 PreparedQuery (com.mysql.cj.PreparedQuery)3