Java Code Examples for com.mysql.cj.exceptions.CJException

The following examples show how to use com.mysql.cj.exceptions.CJException. 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
protected SocketFactory createSocketFactory(String socketFactoryClassName) {
    try {
        if (socketFactoryClassName == null) {
            throw ExceptionFactory.createException(UnableToConnectException.class, Messages.getString("SocketConnection.0"), getExceptionInterceptor());
        }

        Object sf = Class.forName(socketFactoryClassName).newInstance();
        if (sf instanceof SocketFactory) {
            return (SocketFactory) (Class.forName(socketFactoryClassName).newInstance());
        }

        // wrap legacy socket factories
        return new SocketFactoryWrapper(sf);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | CJException ex) {
        throw ExceptionFactory.createException(UnableToConnectException.class,
                Messages.getString("SocketConnection.1", new String[] { socketFactoryClassName }), getExceptionInterceptor());
    }
}
 
Example 2
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void changeDatabase(String database) {
    if (database == null || database.length() == 0) {
        return;
    }

    try {
        sendCommand(this.commandBuilder.buildComInitDb(getSharedSendPacket(), database), false, 0);
    } catch (CJException ex) {
        if (this.getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_createDatabaseIfNotExist).getValue()) {
            sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "CREATE DATABASE IF NOT EXISTS " + database), false, 0);

            sendCommand(this.commandBuilder.buildComInitDb(getSharedSendPacket(), database), false, 0);
        } else {
            throw ExceptionFactory.createCommunicationsException(this.getPropertySet(), this.serverSession,
                    this.getPacketSentTimeHolder().getLastPacketSentTime(), this.getPacketReceivedTimeHolder().getLastPacketReceivedTime(), ex,
                    getExceptionInterceptor());
        }
    }
}
 
Example 3
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks for errors in the reply packet, and if none, returns the reply
 * packet, ready for reading
 * 
 * @param command
 *            the command being issued (if used)
 * 
 * @throws CJException
 *             if an error packet was received
 * @throws CJCommunicationsException
 */
private NativePacketPayload checkErrorMessage(int command) {

    NativePacketPayload resultPacket = null;
    this.serverSession.setStatusFlags(0);

    try {
        // Check return value, if we get a java.io.EOFException, the server has gone away. We'll pass it on up the exception chain and let someone higher up
        // decide what to do (barf, reconnect, etc).
        resultPacket = readMessage(this.reusablePacket);
    } catch (CJException ex) {
        // Don't wrap CJExceptions
        throw ex;
    } catch (Exception fallThru) {
        throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder().getLastPacketSentTime(),
                this.getPacketReceivedTimeHolder().getLastPacketReceivedTime(), fallThru, getExceptionInterceptor());
    }

    checkErrorMessage(resultPacket);

    return resultPacket;
}
 
Example 4
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs an 'EXPLAIN' on the given query and dumps the results to the log
 * 
 * @param querySQL
 * @param truncatedQuery
 * 
 */
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(this.commandBuilder.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());
        }
    }
}
 
Example 5
Source Project: lams   Source File: ServerPreparedStatement.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new ServerPreparedStatement object.
 * 
 * @param conn
 *            the connection creating us.
 * @param sql
 *            the SQL containing the statement to prepare.
 * @param catalog
 *            the catalog in use when we were created.
 * 
 * @throws SQLException
 *             If an error occurs
 */
protected ServerPreparedStatement(JdbcConnection conn, String sql, String catalog, int resultSetType, int resultSetConcurrency) throws SQLException {
    super(conn, catalog);

    checkNullOrEmptyQuery(sql);
    String statementComment = this.session.getProtocol().getQueryComment();
    ((PreparedQuery<?>) this.query).setOriginalSql(statementComment == null ? sql : "/* " + statementComment + " */ " + sql);
    ((PreparedQuery<?>) this.query).setParseInfo(new ParseInfo(((PreparedQuery<?>) this.query).getOriginalSql(), this.session, this.charEncoding));

    this.hasOnDuplicateKeyUpdate = ((PreparedQuery<?>) this.query).getParseInfo().getFirstStmtChar() == 'I' && containsOnDuplicateKeyInString(sql);

    try {
        serverPrepare(sql);
    } catch (CJException | SQLException sqlEx) {
        realClose(false, true);

        throw SQLExceptionsMapping.translateException(sqlEx, this.exceptionInterceptor);
    }

    setResultSetType(resultSetType);
    setResultSetConcurrency(resultSetConcurrency);

}
 
Example 6
Source Project: lams   Source File: FailoverConnectionProxy.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
boolean shouldExceptionTriggerConnectionSwitch(Throwable t) {

    String sqlState = null;
    if (t instanceof CommunicationsException || t instanceof CJCommunicationsException) {
        return true;
    } else if (t instanceof SQLException) {
        sqlState = ((SQLException) t).getSQLState();
    } else if (t instanceof CJException) {
        sqlState = ((CJException) t).getSQLState();
    }

    if (sqlState != null) {
        if (sqlState.startsWith("08")) {
            // connection error
            return true;
        }
    }

    return false;
}
 
Example 7
Source Project: lams   Source File: FailoverConnectionProxy.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Connects this dynamic failover connection proxy to the host pointed out by the given host index.
 * 
 * @param hostIndex
 *            The host index in the global hosts list.
 */
private synchronized void connectTo(int hostIndex) throws SQLException {
    try {
        switchCurrentConnectionTo(hostIndex, createConnectionForHostIndex(hostIndex));
    } catch (SQLException e) {
        if (this.currentConnection != null) {
            StringBuilder msg = new StringBuilder("Connection to ").append(isPrimaryHostIndex(hostIndex) ? "primary" : "secondary").append(" host '")
                    .append(this.hostsList.get(hostIndex)).append("' failed");
            try {
                this.currentConnection.getSession().getLog().logWarn(msg.toString(), e);
            } catch (CJException ex) {
                throw SQLExceptionsMapping.translateException(e, this.currentConnection.getExceptionInterceptor());
            }
        }
        throw e;
    }
}
 
Example 8
Source Project: lams   Source File: ClientPreparedStatement.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new PreparedStatement object.
 * 
 * @param conn
 *            the connection creating this statement
 * @param sql
 *            the SQL for this statement
 * @param catalog
 *            the catalog/database this statement should be issued against
 * @param cachedParseInfo
 *            already created parseInfo or null.
 * 
 * @throws SQLException
 */
public ClientPreparedStatement(JdbcConnection conn, String sql, String catalog, ParseInfo cachedParseInfo) throws SQLException {
    this(conn, catalog);

    try {
        ((PreparedQuery<?>) this.query).checkNullOrEmptyQuery(sql);
        ((PreparedQuery<?>) this.query).setOriginalSql(sql);
        ((PreparedQuery<?>) this.query).setParseInfo(cachedParseInfo != null ? cachedParseInfo : new ParseInfo(sql, this.session, this.charEncoding));
    } catch (CJException e) {
        throw SQLExceptionsMapping.translateException(e, this.exceptionInterceptor);
    }

    this.doPingInstead = sql.startsWith(PING_MARKER);

    initializeFromParseInfo();

}
 
Example 9
/**
 * Creates a new ServerPreparedStatement object.
 * 
 * @param conn
 *            the connection creating us.
 * @param sql
 *            the SQL containing the statement to prepare.
 * @param catalog
 *            the catalog in use when we were created.
 * @param resultSetType
 *            ResultSet type
 * @param resultSetConcurrency
 *            ResultSet concurrency
 * 
 * @throws SQLException
 *             If an error occurs
 */
protected ServerPreparedStatement(JdbcConnection conn, String sql, String catalog, int resultSetType, int resultSetConcurrency) throws SQLException {
    super(conn, catalog);

    checkNullOrEmptyQuery(sql);
    String statementComment = this.session.getProtocol().getQueryComment();
    ((PreparedQuery<?>) this.query).setOriginalSql(statementComment == null ? sql : "/* " + statementComment + " */ " + sql);
    ((PreparedQuery<?>) this.query).setParseInfo(new ParseInfo(((PreparedQuery<?>) this.query).getOriginalSql(), this.session, this.charEncoding));

    this.hasOnDuplicateKeyUpdate = ((PreparedQuery<?>) this.query).getParseInfo().getFirstStmtChar() == 'I' && containsOnDuplicateKeyInString(sql);

    try {
        serverPrepare(sql);
    } catch (CJException | SQLException sqlEx) {
        realClose(false, true);

        throw SQLExceptionsMapping.translateException(sqlEx, this.exceptionInterceptor);
    }

    setResultSetType(resultSetType);
    setResultSetConcurrency(resultSetConcurrency);

}
 
Example 10
@Override
boolean shouldExceptionTriggerConnectionSwitch(Throwable t) {

    String sqlState = null;
    if (t instanceof CommunicationsException || t instanceof CJCommunicationsException) {
        return true;
    } else if (t instanceof SQLException) {
        sqlState = ((SQLException) t).getSQLState();
    } else if (t instanceof CJException) {
        sqlState = ((CJException) t).getSQLState();
    }

    if (sqlState != null) {
        if (sqlState.startsWith("08")) {
            // connection error
            return true;
        }
    }

    return false;
}
 
Example 11
/**
 * Connects this dynamic failover connection proxy to the host pointed out by the given host index.
 * 
 * @param hostIndex
 *            The host index in the global hosts list.
 * @throws SQLException
 *             if an error occurs
 */
private synchronized void connectTo(int hostIndex) throws SQLException {
    try {
        switchCurrentConnectionTo(hostIndex, createConnectionForHostIndex(hostIndex));
    } catch (SQLException e) {
        if (this.currentConnection != null) {
            StringBuilder msg = new StringBuilder("Connection to ").append(isPrimaryHostIndex(hostIndex) ? "primary" : "secondary").append(" host '")
                    .append(this.hostsList.get(hostIndex)).append("' failed");
            try {
                this.currentConnection.getSession().getLog().logWarn(msg.toString(), e);
            } catch (CJException ex) {
                throw SQLExceptionsMapping.translateException(e, this.currentConnection.getExceptionInterceptor());
            }
        }
        throw e;
    }
}
 
Example 12
/**
 * Creates a new PreparedStatement object.
 * 
 * @param conn
 *            the connection creating this statement
 * @param sql
 *            the SQL for this statement
 * @param catalog
 *            the catalog/database this statement should be issued against
 * @param cachedParseInfo
 *            already created parseInfo or null.
 * 
 * @throws SQLException
 *             if a database access error occurs
 */
public ClientPreparedStatement(JdbcConnection conn, String sql, String catalog, ParseInfo cachedParseInfo) throws SQLException {
    this(conn, catalog);

    try {
        ((PreparedQuery<?>) this.query).checkNullOrEmptyQuery(sql);
        ((PreparedQuery<?>) this.query).setOriginalSql(sql);
        ((PreparedQuery<?>) this.query).setParseInfo(cachedParseInfo != null ? cachedParseInfo : new ParseInfo(sql, this.session, this.charEncoding));
    } catch (CJException e) {
        throw SQLExceptionsMapping.translateException(e, this.exceptionInterceptor);
    }

    this.doPingInstead = sql.startsWith(PING_MARKER);

    initializeFromParseInfo();

}
 
Example 13
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void changeDatabase(String database) {
    if (database == null || database.length() == 0) {
        return;
    }

    try {
        sendCommand(this.commandBuilder.buildComInitDb(getSharedSendPacket(), database), false, 0);
    } catch (CJException ex) {
        if (this.getPropertySet().getBooleanProperty(PropertyKey.createDatabaseIfNotExist).getValue()) {
            sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "CREATE DATABASE IF NOT EXISTS " + database), false, 0);

            sendCommand(this.commandBuilder.buildComInitDb(getSharedSendPacket(), database), false, 0);
        } else {
            throw ExceptionFactory.createCommunicationsException(this.getPropertySet(), this.serverSession, this.getPacketSentTimeHolder(),
                    this.getPacketReceivedTimeHolder(), ex, getExceptionInterceptor());
        }
    }
}
 
Example 14
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks for errors in the reply packet, and if none, returns the reply
 * packet, ready for reading
 * 
 * @param command
 *            the command being issued (if used)
 * @return NativePacketPayload
 * @throws CJException
 *             if an error packet was received
 * @throws CJCommunicationsException
 *             if a database error occurs
 */
private NativePacketPayload checkErrorMessage(int command) {

    NativePacketPayload resultPacket = null;
    this.serverSession.setStatusFlags(0);

    try {
        // Check return value, if we get a java.io.EOFException, the server has gone away. We'll pass it on up the exception chain and let someone higher up
        // decide what to do (barf, reconnect, etc).
        resultPacket = readMessage(this.reusablePacket);
    } catch (CJException ex) {
        // Don't wrap CJExceptions
        throw ex;
    } catch (Exception fallThru) {
        throw ExceptionFactory.createCommunicationsException(this.propertySet, this.serverSession, this.getPacketSentTimeHolder(),
                this.getPacketReceivedTimeHolder(), fallThru, getExceptionInterceptor());
    }

    checkErrorMessage(resultPacket);

    return resultPacket;
}
 
Example 15
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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(this.commandBuilder.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());
        }
    }
}
 
Example 16
protected SocketFactory createSocketFactory(String socketFactoryClassName) {
    try {
        if (socketFactoryClassName == null) {
            throw ExceptionFactory.createException(UnableToConnectException.class, Messages.getString("SocketConnection.0"), getExceptionInterceptor());
        }

        Object sf = Class.forName(socketFactoryClassName).newInstance();
        if (sf instanceof SocketFactory) {
            return (SocketFactory) (Class.forName(socketFactoryClassName).newInstance());
        }

        // wrap legacy socket factories
        return new SocketFactoryWrapper(sf);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | CJException ex) {
        throw ExceptionFactory.createException(UnableToConnectException.class,
                Messages.getString("SocketConnection.1", new String[] { socketFactoryClassName }), getExceptionInterceptor());
    }
}
 
Example 17
Source Project: quarkus   Source File: MySQLJDBCReflections.java    License: Apache License 2.0 5 votes vote down vote up
@BuildStep
void registerExceptionsForReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJCommunicationsException.class.getName()));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, CJConnectionFeatureNotAvailableException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJOperationNotSupportedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJTimeoutException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJPacketTooBigException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, AssertionFailedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CJOperationNotSupportedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, ClosedOnExpiredPasswordException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, ConnectionIsClosedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DataConversionException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DataReadException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DataTruncationException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DeadlockTimeoutRollbackMarker.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, FeatureNotAvailableException.class.getName()));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, InvalidConnectionAttributeException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, NumberOutOfRange.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, OperationCancelledException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, PasswordExpiredException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, PropertyNotModifiableException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, RSAException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, SSLParamsException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, StatementIsClosedException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, StreamingNotifiable.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, UnableToConnectException.class.getName()));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, UnsupportedConnectionStringException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, WrongArgumentException.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, "com.mysql.cj.jdbc.MysqlXAException"));
    reflectiveClass
            .produce(new ReflectiveClassBuildItem(false, false, StandardLoadBalanceExceptionChecker.class.getName()));
    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, NdbLoadBalanceExceptionChecker.class.getName()));
}
 
Example 18
Source Project: lams   Source File: JdbcPropertySetImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> ModifiableProperty<T> getJdbcModifiableProperty(String name) throws SQLException {
    try {
        return getModifiableProperty(name);
    } catch (CJException ex) {
        throw SQLExceptionsMapping.translateException(ex);
    }
}
 
Example 19
Source Project: lams   Source File: ServerPreparedStatement.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void serverPrepare(String sql) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        try {

            ServerPreparedQuery q = (ServerPreparedQuery) this.query;
            q.serverPrepare(sql);
        } catch (IOException ioEx) {
            throw SQLError.createCommunicationsException(this.connection, this.session.getProtocol().getPacketSentTimeHolder().getLastPacketSentTime(),
                    this.session.getProtocol().getPacketReceivedTimeHolder().getLastPacketReceivedTime(), 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);
            }

            throw ex;
        } finally {
            // Leave the I/O channel in a known state...there might be packets out there that we're not interested in
            this.session.clearInputStream();
        }
    }
}
 
Example 20
Source Project: lams   Source File: ConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void changeUser(String userName, String newPassword) throws SQLException {
    synchronized (getConnectionMutex()) {
        checkClosed();

        if ((userName == null) || userName.equals("")) {
            userName = "";
        }

        if (newPassword == null) {
            newPassword = "";
        }

        try {
            this.session.changeUser(userName, newPassword, this.database);
        } catch (CJException ex) {
            // After Bug#16241992 fix the server doesn't return to previous credentials if COM_CHANGE_USER attempt failed. 
            if ("28000".equals(ex.getSQLState())) {
                cleanup(ex);
            }
            throw ex;
        }
        this.user = userName;
        this.password = newPassword;

        this.session.configureClientCharacterSet(true);

        this.session.setSessionVariables();

        setupServerForTruncationChecks();
    }
}
 
Example 21
Source Project: lams   Source File: ConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Destroys this connection and any underlying resources
 * 
 * @param fromWhere
 * @param whyCleanedUp
 */
@Override
public void cleanup(Throwable whyCleanedUp) {
    try {
        if (this.session != null) {
            if (isClosed()) {
                this.session.forceClose();
            } else {
                realClose(false, false, false, whyCleanedUp);
            }
        }
    } catch (SQLException | CJException sqlEx) {
        // ignore, we're going away.
    }
}
 
Example 22
Source Project: lams   Source File: ConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Used by MiniAdmin to shutdown a MySQL server
 * 
 * @throws SQLException
 *             if the command can not be issued.
 */
public void shutdownServer() throws SQLException {
    try {
        this.session.shutdownServer();
    } catch (CJException ex) {
        SQLException sqlEx = SQLError.createSQLException(Messages.getString("Connection.UnhandledExceptionDuringShutdown"),
                MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());

        sqlEx.initCause(ex);

        throw sqlEx;
    }
}
 
Example 23
Source Project: lams   Source File: ConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean isServerLocal() throws SQLException {
    synchronized (getConnectionMutex()) {
        try {
            return this.session.isServerLocal(this.getSession());
        } catch (CJException ex) {
            SQLException sqlEx = SQLExceptionsMapping.translateException(ex, getExceptionInterceptor());
            throw sqlEx;
        }
    }
}
 
Example 24
Source Project: lams   Source File: ConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ClientInfoProvider getClientInfoProviderImpl() throws SQLException {
    synchronized (getConnectionMutex()) {
        if (this.infoProvider == null) {
            String clientInfoProvider = this.propertySet.getStringReadableProperty(PropertyDefinitions.PNAME_clientInfoProvider).getStringValue();
            try {
                try {
                    this.infoProvider = (ClientInfoProvider) Util.getInstance(clientInfoProvider, new Class<?>[0], new Object[0],
                            getExceptionInterceptor());
                } catch (CJException ex) {
                    if (ex.getCause() instanceof ClassCastException) {
                        // try with package name prepended
                        try {
                            this.infoProvider = (ClientInfoProvider) Util.getInstance("com.mysql.cj.jdbc." + clientInfoProvider, new Class<?>[0],
                                    new Object[0], getExceptionInterceptor());
                        } catch (CJException e) {
                            throw SQLExceptionsMapping.translateException(e, getExceptionInterceptor());
                        }
                    }
                }
            } catch (ClassCastException cce) {
                throw SQLError.createSQLException(Messages.getString("Connection.ClientInfoNotImplemented", new Object[] { clientInfoProvider }),
                        MysqlErrorNumbers.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }

            this.infoProvider.initialize(this, this.props);
        }

        return this.infoProvider;
    }
}
 
Example 25
Source Project: lams   Source File: ConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void setClientInfo(String name, String value) throws SQLClientInfoException {
    try {
        getClientInfoProviderImpl().setClientInfo(this, name, value);
    } catch (SQLClientInfoException ciEx) {
        throw ciEx;
    } catch (SQLException | CJException sqlEx) {
        SQLClientInfoException clientInfoEx = new SQLClientInfoException();
        clientInfoEx.initCause(sqlEx);

        throw clientInfoEx;
    }
}
 
Example 26
Source Project: lams   Source File: ConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void setClientInfo(Properties properties) throws SQLClientInfoException {
    try {
        getClientInfoProviderImpl().setClientInfo(this, properties);
    } catch (SQLClientInfoException ciEx) {
        throw ciEx;
    } catch (SQLException | CJException sqlEx) {
        SQLClientInfoException clientInfoEx = new SQLClientInfoException();
        clientInfoEx.initCause(sqlEx);

        throw clientInfoEx;
    }
}
 
Example 27
Source Project: lams   Source File: NonRegisteringDriver.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given
 * URL. This will be common, as when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each loaded driver in turn.
 * 
 * <p>
 * The driver should raise an SQLException if the URL is null or if it is the right driver to connect to the given URL, but has trouble connecting to the
 * database.
 * </p>
 * 
 * <p>
 * The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as connection arguments. These properties take precedence over any
 * properties sent in the URL.
 * </p>
 * 
 * <p>
 * MySQL protocol takes the form:
 * 
 * <PRE>
 * jdbc:mysql://host:port/database
 * </PRE>
 * 
 * </p>
 * 
 * @param url
 *            the URL of the database to connect to
 * @param info
 *            a list of arbitrary tag/value pairs as connection arguments
 * 
 * @return a connection to the URL or null if it isn't us
 * 
 * @exception SQLException
 *                if a database access error occurs or the url is {@code null}
 * 
 * @see java.sql.Driver#connect
 */
public java.sql.Connection connect(String url, Properties info) throws SQLException {

    try {
        ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
        if (conStr.getType() == null) {
            /*
             * According to JDBC spec:
             * The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the
             * JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn.
             */
            return null;
        }

        switch (conStr.getType()) {
            case LOADBALANCE_CONNECTION:
                return LoadBalancedConnectionProxy.createProxyInstance((LoadbalanceConnectionUrl) conStr);

            case FAILOVER_CONNECTION:
                return FailoverConnectionProxy.createProxyInstance(conStr);

            case REPLICATION_CONNECTION:
                return ReplicationConnectionProxy.createProxyInstance((ReplicationConnectionUrl) conStr);

            case XDEVAPI_SESSION:
                // TODO test it
                //return new XJdbcConnection(conStr.getProperties());

            default:
                return com.mysql.cj.jdbc.ConnectionImpl.getInstance(conStr.getMainHost());

        }

    } catch (CJException ex) {
        throw ExceptionFactory.createException(UnableToConnectException.class,
                Messages.getString("NonRegisteringDriver.17", new Object[] { ex.toString() }), ex);
    }
}
 
Example 28
Source Project: lams   Source File: AbstractQuery.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
        }
    }
}
 
Example 29
Source Project: lams   Source File: ConnectionUrl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets up the {@link ConnectionPropertiesTransform} if one was provided.
 */
protected void setupPropertiesTransformer() {
    String propertiesTransformClassName = this.properties.get(PropertyDefinitions.PNAME_propertiesTransform);
    if (!isNullOrEmpty(propertiesTransformClassName)) {
        try {
            this.propertiesTransformer = (ConnectionPropertiesTransform) Class.forName(propertiesTransformClassName).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | CJException e) {
            throw ExceptionFactory.createException(InvalidConnectionAttributeException.class,
                    Messages.getString("ConnectionString.9", new Object[] { propertiesTransformClassName, e.toString() }), e);
        }
    }
}
 
Example 30
Source Project: lams   Source File: DefaultPropertySet.java    License: GNU General Public License v2.0 5 votes vote down vote up
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(PropertyDefinitions.HOST_PROPERTY_KEY);
        infoCopy.remove(PropertyDefinitions.PNAME_user);
        infoCopy.remove(PropertyDefinitions.PNAME_password);
        infoCopy.remove(PropertyDefinitions.DBNAME_PROPERTY_KEY);
        infoCopy.remove(PropertyDefinitions.PORT_PROPERTY_KEY);

        for (String propName : PropertyDefinitions.PROPERTY_NAME_TO_PROPERTY_DEFINITION.keySet()) {
            try {
                ReadableProperty<?> propToSet = getReadableProperty(propName);
                propToSet.initializeFrom(infoCopy, null);

            } catch (CJException e) {
                throw ExceptionFactory.createException(WrongArgumentException.class, e.getMessage(), e);
            }
        }

        // 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 ModifiableStringProperty(def);
            addProperty(p);
        }
        postInitialization();
    }
}