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

The following examples show how to use com.mysql.cj.exceptions.CJCommunicationsException. 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
Source Project: lams   Source File: XAsyncSocketConnection.java    License: 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 2
Source Project: lams   Source File: SyncMessageSender.java    License: 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 3
Source Project: lams   Source File: SyncMessageReader.java    License: 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 4
Source Project: lams   Source File: AsyncMessageSender.java    License: 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 5
Source Project: lams   Source File: XProtocol.java    License: 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 6
Source Project: lams   Source File: AsyncSocketFactory.java    License: 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 7
Source Project: lams   Source File: MysqlConnectionTester.java    License: 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 8
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 9
Source Project: lams   Source File: SessionFactory.java    License: 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 10
@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 11
@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 12
@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 13
Source Project: FoxTelem   Source File: AsyncMessageReader.java    License: 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 14
Source Project: FoxTelem   Source File: AsyncMessageReader.java    License: 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 15
Source Project: FoxTelem   Source File: SyncMessageSender.java    License: 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 16
Source Project: FoxTelem   Source File: SyncMessageReader.java    License: 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 17
Source Project: FoxTelem   Source File: AsyncMessageSender.java    License: 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 18
Source Project: FoxTelem   Source File: XProtocol.java    License: 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 19
Source Project: FoxTelem   Source File: AsyncSocketFactory.java    License: 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 20
Source Project: FoxTelem   Source File: SessionFailoverTest.java    License: 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 21
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 22
Source Project: lams   Source File: AsyncMessageReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Queue a {@link MessageListener} to receive messages.
 * 
 * @param l
 *            {@link MessageListener}
 */
public void pushMessageListener(MessageListener<XMessage> l) {
    if (!this.sc.getAsynchronousSocketChannel().isOpen()) {
        throw new CJCommunicationsException("async closed");
    }

    this.messageListenerQueue.add(l);
}
 
Example 23
Source Project: lams   Source File: NoticeFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends GeneratedMessage> 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 24
Source Project: lams   Source File: XProtocol.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void beforeHandshake() {
    this.serverSession = new XServerSession();

    if (this.socketConnection.isSynchronous()) {
        this.reader = new SyncMessageReader(this.socketConnection.getMysqlInput());
        this.writer = new SyncMessageSender(this.socketConnection.getMysqlOutput());
        this.managedResource = this.socketConnection.getMysqlSocket();

        this.serverSession.setCapabilities(getCapabilities());
        return;
    }

    XAsyncSocketConnection sc = (XAsyncSocketConnection) this.socketConnection;
    this.reader = new AsyncMessageReader(this.propertySet, sc);
    ((AsyncMessageReader) this.reader).start();
    this.writer = new AsyncMessageSender(sc.getAsynchronousSocketChannel());

    this.managedResource = sc.getAsynchronousSocketChannel();

    this.serverSession.setCapabilities(getCapabilities());

    SslMode sslMode = this.propertySet.<SslMode> getEnumReadableProperty(PropertyDefinitions.PNAME_sslMode).getValue();
    boolean verifyServerCert = sslMode == SslMode.VERIFY_CA || sslMode == SslMode.VERIFY_IDENTITY;
    String trustStoreUrl = this.propertySet.getStringReadableProperty(PropertyDefinitions.PNAME_sslTrustStoreUrl).getValue();

    if (!verifyServerCert && !StringUtils.isNullOrEmpty(trustStoreUrl)) {
        StringBuilder msg = new StringBuilder("Incompatible security settings. The property '");
        msg.append(PropertyDefinitions.PNAME_sslTrustStoreUrl).append("' requires '");
        msg.append(PropertyDefinitions.PNAME_sslMode).append("' as '");
        msg.append(PropertyDefinitions.SslMode.VERIFY_CA).append("' or '");
        msg.append(PropertyDefinitions.SslMode.VERIFY_IDENTITY).append("'.");
        throw new CJCommunicationsException(msg.toString());
    }

    if (sslMode != SslMode.DISABLED) {
        negotiateSSLConnection(0);
    }
}
 
Example 25
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 26
Source Project: lams   Source File: MysqlxSession.java    License: 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 27
Source Project: lams   Source File: MysqlxSession.java    License: 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;
}
 
Example 28
@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 29
Source Project: FoxTelem   Source File: AsyncMessageReader.java    License: 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 30
Source Project: FoxTelem   Source File: NoticeFactory.java    License: 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);
    }
}