com.mysql.cj.exceptions.CJCommunicationsException Java Examples

The following examples show how to use com.mysql.cj.exceptions.CJCommunicationsException. 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: AsyncSocketFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Closeable> T connect(String host, int port, Properties props, int loginTimeout) throws IOException {
    try {
        this.channel = AsynchronousSocketChannel.open();
        //channel.setOption(java.net.StandardSocketOptions.TCP_NODELAY, true);
        this.channel.setOption(java.net.StandardSocketOptions.SO_SNDBUF, 128 * 1024);
        this.channel.setOption(java.net.StandardSocketOptions.SO_RCVBUF, 128 * 1024);

        Future<Void> connectPromise = this.channel.connect(new InetSocketAddress(host, port));
        connectPromise.get();

    } catch (CJCommunicationsException e) {
        throw e;
    } catch (IOException | InterruptedException | ExecutionException | RuntimeException ex) {
        throw new CJCommunicationsException(ex);
    }
    return (T) this.channel;
}
 
Example #2
Source File: FailoverConnectionProxy.java    From FoxTelem with GNU General Public License v3.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 #3
Source File: MysqlConnectionTester.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public int statusOnException(Connection arg0, Throwable throwable) {
    if (throwable instanceof CommunicationsException || throwable instanceof CJCommunicationsException) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof SQLException) {
        String sqlState = ((SQLException) throwable).getSQLState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
 
Example #4
Source File: SessionFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates {@link Session} by given URL.
 * 
 * @param url
 *            the session URL.
 * @return a {@link Session} instance.
 */
public Session getSession(String url) {
    CJCommunicationsException latestException = null;
    ConnectionUrl connUrl = parseUrl(url);
    for (HostInfo hi : connUrl.getHostsList()) {
        try {
            return new SessionImpl(hi);
        } catch (CJCommunicationsException e) {
            latestException = e;
        }
    }
    if (latestException != null) {
        throw latestException;
    }
    return null;
}
 
Example #5
Source File: XAsyncSocketConnection.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void connect(String hostName, int portNumber, PropertySet propSet, ExceptionInterceptor excInterceptor, Log log, int loginTimeout) {
    this.port = portNumber;
    this.host = hostName;
    this.propertySet = propSet;
    this.socketFactory = new AsyncSocketFactory(); // TODO reuse PNAME_socketFactory

    try {
        this.channel = this.socketFactory.connect(hostName, portNumber, propSet, loginTimeout);

    } catch (CJCommunicationsException e) {
        throw e;
    } catch (IOException | RuntimeException ex) {
        throw new CJCommunicationsException(ex);
    }
}
 
Example #6
Source File: AsyncSocketFactory.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Closeable> T connect(String host, int port, PropertySet props, int loginTimeout) throws IOException {
    try {
        this.channel = AsynchronousSocketChannel.open();
        //channel.setOption(java.net.StandardSocketOptions.TCP_NODELAY, true);
        this.channel.setOption(java.net.StandardSocketOptions.SO_SNDBUF, 128 * 1024);
        this.channel.setOption(java.net.StandardSocketOptions.SO_RCVBUF, 128 * 1024);

        Future<Void> connectPromise = this.channel.connect(new InetSocketAddress(host, port));
        connectPromise.get();

    } catch (CJCommunicationsException e) {
        throw e;
    } catch (IOException | InterruptedException | ExecutionException | RuntimeException ex) {
        throw new CJCommunicationsException(ex);
    }
    return (T) this.channel;
}
 
Example #7
Source File: FailoverConnectionProxy.java    From lams with 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 #8
Source File: MysqlConnectionTester.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public int statusOnException(Connection arg0, Throwable throwable) {
    if (throwable instanceof CommunicationsException || throwable instanceof CJCommunicationsException) {
        return CONNECTION_IS_INVALID;
    }

    if (throwable instanceof SQLException) {
        String sqlState = ((SQLException) throwable).getSQLState();

        if (sqlState != null && sqlState.startsWith("08")) {
            return CONNECTION_IS_INVALID;
        }

        return CONNECTION_IS_OKAY;
    }

    // Runtime/Unchecked?

    return CONNECTION_IS_INVALID;
}
 
Example #9
Source File: AsyncMessageReader.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Handler for "read failed" event.
 */
@Override
public void failed(Throwable exc, Void attachment) {
    if (getMessageListener(false) != null) {
        // force any error to unblock pending message listener
        synchronized (AsyncMessageReader.this.pendingMsgMonitor) {
            AsyncMessageReader.this.pendingMsgMonitor.notify();
        }
        if (AsynchronousCloseException.class.equals(exc.getClass())) {
            AsyncMessageReader.this.currentMessageListener.error(new CJCommunicationsException("Socket closed", exc));
        } else {
            AsyncMessageReader.this.currentMessageListener.error(exc);
        }
    }
    // it's "done" after sending a closed() or error() signal
    AsyncMessageReader.this.currentMessageListener = null;
}
 
Example #10
Source File: SessionFailoverTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Assures that failover support doesn't affect single host connections.
 */
@Test
public void testGetSessionForSingleHost() throws Exception {
    if (!this.isSetForXTests) {
        return;
    }

    ConnectionsCounterFakeServer fakeServer = new ConnectionsCounterFakeServer();
    String fakeHost = fakeServer.getHostPortPair();

    try {
        this.fact.getSession(buildConnectionString(this.testsHost)).close();
        assertThrows(CJCommunicationsException.class, ".*", () -> this.fact.getSession(buildConnectionString(fakeHost)));
        assertEquals(1, fakeServer.getAndResetConnectionsCounter());
    } finally {
        fakeServer.shutdownSilently();
    }
}
 
Example #11
Source File: XProtocol.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public void close() throws IOException {
    try {
        send(this.messageBuilder.buildClose(), 0);
        readOk();
    } catch (Exception e) {
        // ignore exceptions
    } finally {
        try {
            if (this.managedResource == null) {
                throw new ConnectionIsClosedException();
            }
            this.managedResource.close();
            this.managedResource = null;
        } catch (IOException ex) {
            throw new CJCommunicationsException(ex);
        }
    }
}
 
Example #12
Source File: AsyncMessageReader.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void failed(Throwable exc, Void attachment) {
    if (getMessageListener(false) != null) {
        // force any error to unblock pending message listener
        synchronized (AsyncMessageReader.this.pendingMsgMonitor) {
            AsyncMessageReader.this.pendingMsgMonitor.notify();
        }
        if (AsynchronousCloseException.class.equals(exc.getClass())) {
            AsyncMessageReader.this.currentMessageListener.error(new CJCommunicationsException("Socket closed", exc));
        } else {
            AsyncMessageReader.this.currentMessageListener.error(exc);
        }
    }
    // it's "done" after sending a closed() or error() signal
    AsyncMessageReader.this.currentMessageListener = null;
}
 
Example #13
Source File: XProtocol.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void negotiateSSLConnection(int packLength) {

        if (!((XServerCapabilities) this.serverSession.getCapabilities()).hasCapability("tls")) {
            throw new CJCommunicationsException("A secure connection is required but the server is not configured with SSL.");
        }

        // the message reader is async and is always "reading". we need to stop it to use the socket for the TLS handshake
        ((AsyncMessageReader) this.reader).stopAfterNextMessage();
        setCapability("tls", true);

        try {
            this.socketConnection.performTlsHandshake(null);
        } catch (SSLParamsException | FeatureNotAvailableException | IOException e) {
            throw new CJCommunicationsException(e);
        }

        // resume message processing
        ((AsyncMessageSender) this.writer).setChannel(this.socketConnection.getAsynchronousSocketChannel());
        ((AsyncMessageReader) this.reader).start();
    }
 
Example #14
Source File: AsyncMessageSender.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Asynchronously write a message with a notification being delivered to <code>callback</code> upon completion of write of entire message.
 *
 * @param message
 *            message extending {@link XMessage}
 * @param callback
 *            an optional callback to receive notification of when the message is completely written
 */
public void writeAsync(XMessage message, CompletionHandler<Long, Void> callback) {
    MessageLite msg = message.getMessage();
    int type = MessageConstants.getTypeForMessageClass(msg.getClass());
    int size = msg.getSerializedSize();
    int payloadSize = size + 1;
    // we check maxAllowedPacket against payloadSize as that's considered the "packet size" (not including 4 byte size header)
    if (this.maxAllowedPacket > 0 && payloadSize > this.maxAllowedPacket) {
        throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
    }
    // for debugging
    //System.err.println("Initiating write of message (size=" + payloadSize + ", tag=" + com.mysql.cj.mysqlx.protobuf.Mysqlx.ClientMessages.Type.valueOf(type) + ")");
    ByteBuffer messageBuf = ByteBuffer.allocate(HEADER_LEN + size).order(ByteOrder.LITTLE_ENDIAN).putInt(payloadSize);
    messageBuf.put((byte) type);
    try {
        // directly access the ByteBuffer's backing array as protobuf's CodedOutputStream.newInstance(ByteBuffer) is giving a stream that doesn't actually
        // write any data
        msg.writeTo(CodedOutputStream.newInstance(messageBuf.array(), HEADER_LEN, size + HEADER_LEN));
        messageBuf.position(messageBuf.limit());
    } catch (IOException ex) {
        throw new CJCommunicationsException("Unable to write message", ex);
    }
    messageBuf.flip();
    this.bufferWriter.queueBuffer(messageBuf, callback);
}
 
Example #15
Source File: SyncMessageReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public XMessageHeader readHeader() throws IOException {
    if (!this.hasReadHeader) {
        try {
            readMessageHeader();
        } catch (IOException ex) {
            throw new CJCommunicationsException("Cannot read packet header", ex);
        }
    }
    int type = this.header.getMessageType(); // forces header read if necessary

    Class<? extends GeneratedMessage> messageClass = MessageConstants.getMessageClassForType(type);

    if (messageClass == Error.class) {
        // throw an error/exception if receive an Error message
        throw new XProtocolError(readAndParse((Parser<Error>) MessageConstants.MESSAGE_CLASS_TO_PARSER.get(Error.class)));
    }

    return this.header;
}
 
Example #16
Source File: SyncMessageSender.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Send a message.
 *
 * @param msg
 *            the message to send
 * @throws CJCommunicationsException
 *             to wrap any occurring IOException
 */
public void send(XMessage message) {
    MessageLite msg = message.getMessage();
    try {
        int type = MessageConstants.getTypeForMessageClass(msg.getClass());
        int size = 1 + msg.getSerializedSize();
        if (this.maxAllowedPacket > 0 && size > this.maxAllowedPacket) {
            throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
        }
        // for debugging
        // System.err.println("Initiating write of message (size=" + size + ", tag=" + ClientMessages.Type.valueOf(type) + ")");
        byte[] sizeHeader = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(size).array();
        this.outputStream.write(sizeHeader);
        this.outputStream.write(type);
        msg.writeTo(this.outputStream);
        this.outputStream.flush();
        this.lastPacketSentTime = System.currentTimeMillis();
    } catch (IOException ex) {
        throw new CJCommunicationsException("Unable to write message", ex);
    }
}
 
Example #17
Source File: SyncMessageSender.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public void send(XMessage message) {
    synchronized (this.waitingAsyncOperationMonitor) {
        MessageLite msg = message.getMessage();
        try {
            int type = MessageConstants.getTypeForMessageClass(msg.getClass());
            int size = 1 + msg.getSerializedSize();
            if (this.maxAllowedPacket > 0 && size > this.maxAllowedPacket) {
                throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
            }
            // for debugging
            // System.err.println("Initiating write of message (size=" + size + ", tag=" + ClientMessages.Type.valueOf(type) + ")");
            byte[] sizeHeader = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(size).array();
            this.outputStream.write(sizeHeader);
            this.outputStream.write(type);
            msg.writeTo(this.outputStream);
            this.outputStream.flush();
            this.previousPacketSentTime = this.lastPacketSentTime;
            this.lastPacketSentTime = System.currentTimeMillis();
        } catch (IOException ex) {
            throw new CJCommunicationsException("Unable to write message", ex);
        }
    }
}
 
Example #18
Source File: SyncMessageReader.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
private XMessageHeader readHeaderLocal() throws IOException {

        try {
            /*
             * Note that the "header" per-se is the size of all data following the header. This currently includes the message type tag (1 byte) and the
             * message bytes. However since we know the type tag is present we also read it as part of the header. This may change in the future if session
             * multiplexing is supported by the protocol. The protocol will be able to accommodate it but we will have to separate reading data after the
             * header (size).
             */
            byte[] len = new byte[5];
            this.inputStream.readFully(len);
            this.header = new XMessageHeader(len);
        } catch (IOException ex) {
            // TODO close socket?
            throw new CJCommunicationsException("Cannot read packet header", ex);
        }

        return this.header;
    }
 
Example #19
Source File: XAsyncSocketConnection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void connect(String hostName, int portNumber, PropertySet propSet, ExceptionInterceptor excInterceptor, Log log, int loginTimeout) {
    this.port = portNumber;
    this.host = hostName;
    this.propertySet = propSet;
    this.socketFactory = new AsyncSocketFactory(); // TODO reuse PNAME_socketFactory

    try {
        this.channel = this.socketFactory.connect(hostName, portNumber, propSet.exposeAsProperties(), loginTimeout);

    } catch (CJCommunicationsException e) {
        throw e;
    } catch (IOException | RuntimeException ex) {
        throw new CJCommunicationsException(ex);
    }
}
 
Example #20
Source File: AsyncMessageSender.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public void send(XMessage message, CompletionHandler<Long, Void> callback) {
    MessageLite msg = message.getMessage();
    int type = MessageConstants.getTypeForMessageClass(msg.getClass());
    int size = msg.getSerializedSize();
    int payloadSize = size + 1;
    // we check maxAllowedPacket against payloadSize as that's considered the "packet size" (not including 4 byte size header)
    if (this.maxAllowedPacket > 0 && payloadSize > this.maxAllowedPacket) {
        throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
    }
    // for debugging
    //System.err.println("Initiating write of message (size=" + payloadSize + ", tag=" + com.mysql.cj.mysqlx.protobuf.Mysqlx.ClientMessages.Type.valueOf(type) + ")");
    ByteBuffer messageBuf = ByteBuffer.allocate(HEADER_LEN + size).order(ByteOrder.LITTLE_ENDIAN).putInt(payloadSize);
    messageBuf.put((byte) type);
    try {
        // directly access the ByteBuffer's backing array as protobuf's CodedOutputStream.newInstance(ByteBuffer) is giving a stream that doesn't actually
        // write any data
        msg.writeTo(CodedOutputStream.newInstance(messageBuf.array(), HEADER_LEN, size));
        messageBuf.position(messageBuf.limit());
    } catch (IOException ex) {
        throw new CJCommunicationsException("Unable to write message", ex);
    }
    messageBuf.flip();
    this.bufferWriter.queueBuffer(messageBuf, callback);
}
 
Example #21
Source File: MysqlxSession.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void quit() {
    try {
        this.protocol.send(this.messageBuilder.buildClose(), 0);
        ((XProtocol) this.protocol).readOk();
    } finally {
        try {
            this.protocol.close();
        } catch (IOException ex) {
            throw new CJCommunicationsException(ex);
        }
    }
}
 
Example #22
Source File: XProtocol.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public void negotiateSSLConnection(int packLength) {

        if (!ExportControlled.enabled()) {
            throw new CJConnectionFeatureNotAvailableException();
        }

        if (!((XServerCapabilities) this.serverSession.getCapabilities()).hasCapability("tls")) {
            throw new CJCommunicationsException("A secure connection is required but the server is not configured with SSL.");
        }

        // the message reader is async and is always "reading". we need to stop it to use the socket for the TLS handshake
        this.reader.stopAfterNextMessage();
        setCapability("tls", true);

        try {
            this.socketConnection.performTlsHandshake(null); //(this.serverSession);
        } catch (SSLParamsException | FeatureNotAvailableException | IOException e) {
            throw new CJCommunicationsException(e);
        }

        if (this.socketConnection.isSynchronous()) {
            // i/o streams were replaced, build new packet sender/reader
            this.sender = new SyncMessageSender(this.socketConnection.getMysqlOutput());
            this.reader = new SyncMessageReader(this.socketConnection.getMysqlInput());
        } else {
            // resume message processing
            ((AsyncMessageSender) this.sender).setChannel(this.socketConnection.getAsynchronousSocketChannel());
            this.reader.start();
        }
    }
 
Example #23
Source File: AsyncMessageReader.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handler for "read completed" event. Consume the header data in header.headerBuf and initiate the reading of the message body.
 */
@Override
public void completed(Integer bytesRead, Void attachment) {
    if (bytesRead < 0) { // async socket closed
        onError(new CJCommunicationsException("Socket closed"));
        return;
    }

    try {
        if (AsyncMessageReader.this.currentReadResult == null) {
            AsyncMessageReader.this.currentReadResult = new CompletedRead();
            AsyncMessageReader.this.currentReadResult.header = new XMessageHeader();
        }

        if (AsyncMessageReader.this.currentReadResult.header.getBuffer().position() < 5) {
            AsyncMessageReader.this.sc.getAsynchronousSocketChannel().read(AsyncMessageReader.this.currentReadResult.header.getBuffer(), null, this);
            return; // loop to #completed() again if we're still waiting for more data
        }

        //AsyncMessageReader.this.state = ReadingState.READING_MESSAGE;
        // TODO: re-use buffers if possible. Note that synchronization will be necessary to prevent overwriting re-used buffers while still being parsed by
        // previous read. Also the buffer will have to be managed accordingly so that "remaining" isn't longer than the message otherwise it may consume
        // data from the next header+message
        AsyncMessageReader.this.messageBuf = ByteBuffer.allocate(AsyncMessageReader.this.currentReadResult.header.getMessageSize());
        // if there's no message listener waiting, expose the message class as pending for the next read
        if (getMessageListener(false) == null) {
            synchronized (AsyncMessageReader.this.pendingMsgMonitor) {
                AsyncMessageReader.this.pendingMsgHeader = CompletableFuture.completedFuture(AsyncMessageReader.this.currentReadResult.header);
                AsyncMessageReader.this.pendingMsgMonitor.notify();
            }
        }

        AsyncMessageReader.this.messageCompletionHandler.completed(0, null); // initiates message read cycle

    } catch (Throwable t) {
        onError(t); // error reading => illegal state, close connection
    }
}
 
Example #24
Source File: NoticeFactory.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends GeneratedMessageV3> T parseNotice(ByteString payload, Class<T> noticeClass) {
    try {
        Parser<T> parser = (Parser<T>) MessageConstants.MESSAGE_CLASS_TO_PARSER.get(noticeClass);
        return parser.parseFrom(payload);
    } catch (InvalidProtocolBufferException ex) {
        throw new CJCommunicationsException(ex);
    }
}
 
Example #25
Source File: SessionFactory.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates {@link Session} by given URL.
 * 
 * @param connUrl
 *            the session {@link ConnectionUrl}.
 * @return a {@link Session} instance.
 */
protected Session getSession(ConnectionUrl connUrl) {
    CJCommunicationsException latestException = null;
    for (HostInfo hi : connUrl.getHostsList()) {
        try {
            return new SessionImpl(hi);
        } catch (CJCommunicationsException e) {
            latestException = e;
        }
    }
    if (latestException != null) {
        throw latestException;
    }
    return null;
}
 
Example #26
Source File: MySQLJDBCReflections.java    From quarkus with 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 #27
Source File: StandardLoadBalanceExceptionChecker.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean shouldExceptionTriggerFailover(Throwable ex) {
    String sqlState = ex instanceof SQLException ? ((SQLException) ex).getSQLState() : null;

    if (sqlState != null) {
        if (sqlState.startsWith("08")) {
            // connection error
            return true;
        }
        if (this.sqlStateList != null) {
            // check against SQLState list
            for (Iterator<String> i = this.sqlStateList.iterator(); i.hasNext();) {
                if (sqlState.startsWith(i.next().toString())) {
                    return true;
                }
            }
        }
    }

    // always handle CommunicationException
    if (ex instanceof CommunicationsException || ex instanceof CJCommunicationsException) {
        return true;
    }

    if (this.sqlExClassList != null) {
        // check against configured class lists
        for (Iterator<Class<?>> i = this.sqlExClassList.iterator(); i.hasNext();) {
            if (i.next().isInstance(ex)) {
                return true;
            }
        }
    }
    // no matches
    return false;
}
 
Example #28
Source File: SyncMessageReader.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    synchronized (SyncMessageReader.this.waitingSyncOperationMonitor) {
        this.started = true;
        try {
            while (true) {
                MessageListener<XMessage> l;
                if ((l = SyncMessageReader.this.messageListenerQueue.poll(POLL_TIMEOUT, TimeUnit.MILLISECONDS)) == null) {
                    synchronized (SyncMessageReader.this.dispatchingThreadMonitor) {
                        if (SyncMessageReader.this.messageListenerQueue.peek() == null) {
                            SyncMessageReader.this.dispatchingThread = null;
                            break;
                        }
                    }
                } else {
                    try {
                        XMessage msg = null;
                        do {
                            XMessageHeader hdr = readHeader();
                            msg = readMessage(null, hdr);
                        } while (!l.createFromMessage(msg));
                    } catch (Throwable t) {
                        l.error(t);
                    }
                }
            }
        } catch (InterruptedException e) {
            throw new CJCommunicationsException("Read operation interrupted.", e);
        }
    }
}
 
Example #29
Source File: ExportControlled.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private static KeyStoreConf getTrustStoreConf(PropertySet propertySet, PropertyKey keyStoreUrlPropertyKey, PropertyKey keyStorePasswordPropertyKey,
        PropertyKey keyStoreTypePropertyKey, boolean required) {

    String trustStoreUrl = propertySet.getStringProperty(keyStoreUrlPropertyKey).getValue();
    String trustStorePassword = propertySet.getStringProperty(keyStorePasswordPropertyKey).getValue();
    String trustStoreType = propertySet.getStringProperty(keyStoreTypePropertyKey).getValue();

    if (StringUtils.isNullOrEmpty(trustStoreUrl)) {
        trustStoreUrl = System.getProperty("javax.net.ssl.trustStore");
        trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
        trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
        if (StringUtils.isNullOrEmpty(trustStoreType)) {
            trustStoreType = propertySet.getStringProperty(keyStoreTypePropertyKey).getInitialValue();
        }
        // check URL
        if (!StringUtils.isNullOrEmpty(trustStoreUrl)) {
            try {
                new URL(trustStoreUrl);
            } catch (MalformedURLException e) {
                trustStoreUrl = "file:" + trustStoreUrl;
            }
        }
    }

    if (required && StringUtils.isNullOrEmpty(trustStoreUrl)) {
        throw new CJCommunicationsException("No truststore provided to verify the Server certificate.");
    }

    return new KeyStoreConf(trustStoreUrl, trustStorePassword, trustStoreType);
}
 
Example #30
Source File: MysqlxSession.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SqlResult executeSql(String sql, List<Object> args) {
    this.protocol.send(this.messageBuilder.buildSqlStatement(sql, args), 0);
    boolean readLastResult[] = new boolean[1];
    Supplier<StatementExecuteOk> okReader = () -> {
        if (readLastResult[0]) {
            throw new CJCommunicationsException("Invalid state attempting to read ok packet");
        }
        if (((XProtocol) this.protocol).hasMoreResults()) {
            // empty/fabricated OK packet
            return new StatementExecuteOkBuilder().build();
        }
        readLastResult[0] = true;
        return this.protocol.readQueryResult();
    };
    Supplier<SqlResult> resultStream = () -> {
        if (readLastResult[0]) {
            return null;
        } else if (((XProtocol) this.protocol).isSqlResultPending()) {
            ColumnDefinition metadata = this.protocol.readMetadata();
            return new SqlDataResult(metadata, this.protocol.getServerSession().getDefaultTimeZone(), this.protocol.getRowInputStream(metadata), okReader);
        } else {
            readLastResult[0] = true;
            return new SqlUpdateResult(this.protocol.readQueryResult());
        }
    };
    SqlResultImpl res = new SqlResultImpl(resultStream);
    this.protocol.setCurrentResultStreamer(res);
    return res;
}