com.mysql.cj.conf.PropertySet Java Examples

The following examples show how to use com.mysql.cj.conf.PropertySet. 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: CoreSession.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public CoreSession(HostInfo hostInfo, PropertySet propSet) {
    this.connectionCreationTimeMillis = System.currentTimeMillis();
    this.hostInfo = hostInfo;
    this.propertySet = propSet;

    this.gatherPerfMetrics = getPropertySet().getBooleanProperty(PropertyKey.gatherPerfMetrics);
    this.characterEncoding = getPropertySet().getStringProperty(PropertyKey.characterEncoding);
    this.disconnectOnExpiredPasswords = getPropertySet().getBooleanProperty(PropertyKey.disconnectOnExpiredPasswords);
    this.cacheServerConfiguration = getPropertySet().getBooleanProperty(PropertyKey.cacheServerConfiguration);
    this.autoReconnect = getPropertySet().getBooleanProperty(PropertyKey.autoReconnect);
    this.autoReconnectForPools = getPropertySet().getBooleanProperty(PropertyKey.autoReconnectForPools);
    this.maintainTimeStats = getPropertySet().getBooleanProperty(PropertyKey.maintainTimeStats);

    this.log = LogFactory.getLogger(getPropertySet().getStringProperty(PropertyKey.logger).getStringValue(), Log.LOGGER_INSTANCE_NAME);
    if (getPropertySet().getBooleanProperty(PropertyKey.profileSQL).getValue()
            || getPropertySet().getBooleanProperty(PropertyKey.useUsageAdvisor).getValue()) {
        ProfilerEventHandlerFactory.getInstance(this);
    }
}
 
Example #2
Source File: JDBCMySQLProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
List<NativeImageProxyDefinitionBuildItem> registerProxies() {
    List<NativeImageProxyDefinitionBuildItem> proxies = new ArrayList<>();
    proxies.add(new NativeImageProxyDefinitionBuildItem(JdbcConnection.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(MysqlConnection.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(Statement.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(AutoCloseable.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(JdbcStatement.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(Connection.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(ResultSet.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(JdbcPreparedStatement.class.getName(), JdbcStatement.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(JdbcPropertySet.class.getName(), PropertySet.class.getName(),
            Serializable.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(Resultset.class.getName(), ResultSetInternalMethods.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(LoadBalancedConnection.class.getName(),
            JdbcConnection.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(ReplicationConnection.class.getName(), JdbcConnection.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(ResultSetInternalMethods.class.getName(),
                    WarningListener.class.getName(), Resultset.class.getName()));
    return proxies;
}
 
Example #3
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 #4
Source File: ExceptionFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static CJCommunicationsException createCommunicationsException(PropertySet propertySet, ServerSession serverSession, long lastPacketSentTimeMs,
        long lastPacketReceivedTimeMs, Throwable cause, ExceptionInterceptor interceptor) {
    CJCommunicationsException sqlEx = createException(CJCommunicationsException.class, null, cause, interceptor);
    sqlEx.init(propertySet, serverSession, lastPacketSentTimeMs, lastPacketReceivedTimeMs);

    // TODO: Decide whether we need to intercept exceptions at this level
    //if (interceptor != null) {
    //    @SuppressWarnings("unchecked")
    //    T interceptedEx = (T) interceptor.interceptException(sqlEx, null);
    //    if (interceptedEx != null) {
    //        return interceptedEx;
    //    }
    //}

    return sqlEx;
}
 
Example #5
Source File: MysqlxSession.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public MysqlxSession(HostInfo hostInfo, PropertySet propSet) {
    super(hostInfo, propSet);

    // create protocol instance
    this.host = hostInfo.getHost();
    if (this.host == null || StringUtils.isEmptyOrWhitespaceOnly(this.host)) {
        this.host = "localhost";
    }
    this.port = hostInfo.getPort();
    if (this.port < 0) {
        this.port = 33060;
    }

    this.protocol = XProtocol.getInstance(this.host, this.port, propSet);

    this.messageBuilder = this.protocol.getMessageBuilder();

    this.protocol.connect(hostInfo.getUser(), hostInfo.getPassword(), hostInfo.getDatabase());
}
 
Example #6
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public String getUri() {
    PropertySet pset = this.session.getPropertySet();

    StringBuilder sb = new StringBuilder(ConnectionUrl.Type.XDEVAPI_SESSION.getProtocol());
    sb.append("//").append(this.session.getProcessHost()).append(":").append(this.session.getPort()).append("/").append(this.defaultSchemaName).append("?");

    for (String propName : PropertyDefinitions.PROPERTY_NAME_TO_PROPERTY_DEFINITION.keySet()) {
        ReadableProperty<?> propToGet = pset.getReadableProperty(propName);

        String propValue = propToGet.getStringValue();

        if (propValue != null && !propValue.equals(propToGet.getPropertyDefinition().getDefaultValue().toString())) {
            sb.append(",");
            sb.append(propName);
            sb.append("=");
            sb.append(propValue);
        }
    }

    // TODO modify for multi-host connections

    return sb.toString();

}
 
Example #7
Source File: CoreSession.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public CoreSession(HostInfo hostInfo, PropertySet propSet) {
    this.connectionCreationTimeMillis = System.currentTimeMillis();
    this.hostInfo = hostInfo;
    this.propertySet = propSet;

    this.gatherPerfMetrics = getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_gatherPerfMetrics);
    this.characterEncoding = getPropertySet().getModifiableProperty(PropertyDefinitions.PNAME_characterEncoding);
    this.useOldUTF8Behavior = getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_useOldUTF8Behavior);
    this.disconnectOnExpiredPasswords = getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_disconnectOnExpiredPasswords);
    this.cacheServerConfiguration = getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_cacheServerConfiguration);
    this.autoReconnect = getPropertySet().<Boolean> getModifiableProperty(PropertyDefinitions.PNAME_autoReconnect);
    this.autoReconnectForPools = getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_autoReconnectForPools);
    this.maintainTimeStats = getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_maintainTimeStats);

    this.log = LogFactory.getLogger(getPropertySet().getStringReadableProperty(PropertyDefinitions.PNAME_logger).getStringValue(),
            Log.LOGGER_INSTANCE_NAME);
    if (getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_profileSQL).getValue()
            || getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_useUsageAdvisor).getValue()) {
        ProfilerEventHandlerFactory.getInstance(this);
    }
}
 
Example #8
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 #9
Source File: XProtocol.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public XProtocol(String host, int port, String defaultSchema, PropertySet propertySet) {

        this.defaultSchemaName = defaultSchema;

        // Override common connectTimeout with xdevapi.connect-timeout to provide unified logic in StandardSocketFactory
        RuntimeProperty<Integer> connectTimeout = propertySet.getIntegerProperty(PropertyKey.connectTimeout);
        RuntimeProperty<Integer> xdevapiConnectTimeout = propertySet.getIntegerProperty(PropertyKey.xdevapiConnectTimeout);
        if (xdevapiConnectTimeout.isExplicitlySet() || !connectTimeout.isExplicitlySet()) {
            connectTimeout.setValue(xdevapiConnectTimeout.getValue());
        }

        SocketConnection socketConn = propertySet.getBooleanProperty(PropertyKey.xdevapiUseAsyncProtocol).getValue() ? new XAsyncSocketConnection()
                : new NativeSocketConnection();
        socketConn.connect(host, port, propertySet, null, null, 0);
        init(null, socketConn, propertySet, null);
    }
 
Example #10
Source File: XProtocol.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public XProtocol(HostInfo hostInfo, PropertySet propertySet) {
    String host = hostInfo.getHost();
    if (host == null || StringUtils.isEmptyOrWhitespaceOnly(host)) {
        host = "localhost";
    }
    int port = hostInfo.getPort();
    if (port < 0) {
        port = 33060;
    }
    this.defaultSchemaName = hostInfo.getDatabase();

    // Override common connectTimeout with xdevapi.connect-timeout to provide unified logic in StandardSocketFactory
    RuntimeProperty<Integer> connectTimeout = propertySet.getIntegerProperty(PropertyKey.connectTimeout);
    RuntimeProperty<Integer> xdevapiConnectTimeout = propertySet.getIntegerProperty(PropertyKey.xdevapiConnectTimeout);
    if (xdevapiConnectTimeout.isExplicitlySet() || !connectTimeout.isExplicitlySet()) {
        connectTimeout.setValue(xdevapiConnectTimeout.getValue());
    }

    SocketConnection socketConn = propertySet.getBooleanProperty(PropertyKey.xdevapiUseAsyncProtocol).getValue() ? new XAsyncSocketConnection()
            : new NativeSocketConnection();
    socketConn.connect(host, port, propertySet, null, null, 0);
    init(null, socketConn, propertySet, null);
}
 
Example #11
Source File: ExceptionFactory.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public static CJCommunicationsException createCommunicationsException(PropertySet propertySet, ServerSession serverSession,
        PacketSentTimeHolder packetSentTimeHolder, PacketReceivedTimeHolder packetReceivedTimeHolder, Throwable cause, ExceptionInterceptor interceptor) {
    CJCommunicationsException sqlEx = createException(CJCommunicationsException.class, null, cause, interceptor);
    sqlEx.init(propertySet, serverSession, packetSentTimeHolder, packetReceivedTimeHolder);

    // TODO: Decide whether we need to intercept exceptions at this level
    //if (interceptor != null) {
    //    @SuppressWarnings("unchecked")
    //    T interceptedEx = (T) interceptor.interceptException(sqlEx, null);
    //    if (interceptedEx != null) {
    //        return interceptedEx;
    //    }
    //}

    return sqlEx;
}
 
Example #12
Source File: StandardSocketFactory.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Configures socket properties based on properties from the connection
 * (tcpNoDelay, snd/rcv buf, traffic class, etc).
 * 
 * @param sock
 *            socket
 * @param pset
 *            properties
 * @throws SocketException
 *             if an error occurs
 * @throws IOException
 *             if an error occurs
 */
private void configureSocket(Socket sock, PropertySet pset) throws SocketException, IOException {
    sock.setTcpNoDelay(pset.getBooleanProperty(PropertyKey.tcpNoDelay).getValue());
    sock.setKeepAlive(pset.getBooleanProperty(PropertyKey.tcpKeepAlive).getValue());

    int receiveBufferSize = pset.getIntegerProperty(PropertyKey.tcpRcvBuf).getValue();
    if (receiveBufferSize > 0) {
        sock.setReceiveBufferSize(receiveBufferSize);
    }

    int sendBufferSize = pset.getIntegerProperty(PropertyKey.tcpSndBuf).getValue();
    if (sendBufferSize > 0) {
        sock.setSendBufferSize(sendBufferSize);
    }

    int trafficClass = pset.getIntegerProperty(PropertyKey.tcpTrafficClass).getValue();
    if (trafficClass > 0) {
        sock.setTrafficClass(trafficClass);
    }
}
 
Example #13
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 #14
Source File: ExportControlled.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
private static KeyStoreConf getKeyStoreConf(PropertySet propertySet, PropertyKey keyStoreUrlPropertyKey, PropertyKey keyStorePasswordPropertyKey,
        PropertyKey keyStoreTypePropertyKey) {

    String keyStoreUrl = propertySet.getStringProperty(keyStoreUrlPropertyKey).getValue();
    String keyStorePassword = propertySet.getStringProperty(keyStorePasswordPropertyKey).getValue();
    String keyStoreType = propertySet.getStringProperty(keyStoreTypePropertyKey).getValue();

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

    return new KeyStoreConf(keyStoreUrl, keyStorePassword, keyStoreType);
}
 
Example #15
Source File: NamedPipeSocketFactory.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 portNumber /* ignored */, PropertySet props, int loginTimeout) throws IOException {
    String namedPipePath = props.getStringProperty(PropertyKey.PATH).getValue();

    if (namedPipePath == null) {
        namedPipePath = "\\\\.\\pipe\\MySQL";
    } else if (namedPipePath.length() == 0) {
        throw new SocketException(
                Messages.getString("NamedPipeSocketFactory.2") + PropertyKey.PATH.getCcAlias() + Messages.getString("NamedPipeSocketFactory.3"));
    }

    this.namedPipeSocket = new NamedPipeSocket(namedPipePath);

    return (T) this.namedPipeSocket;
}
 
Example #16
Source File: XProtocol.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void init(Session sess, SocketConnection socketConn, PropertySet propSet, TransactionEventHandler transactionManager) {
    this.socketConnection = socketConn;
    this.propertySet = propSet;
    this.messageBuilder = new XMessageBuilder();

    this.authProvider = new XAuthenticationProvider();
    this.authProvider.init(this, propSet, null);

    this.metadataCharacterSet = "latin1"; // TODO configure from server session
    this.fieldFactory = new FieldFactory(this.metadataCharacterSet);
    this.noticeFactory = new NoticeFactory();
}
 
Example #17
Source File: NativeProtocol.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void afterHandshake() {

    checkTransactionState();

    PropertySet pset = this.getPropertySet();

    //
    // Can't enable compression until after handshake
    //
    if (((this.serverSession.getCapabilities().getCapabilityFlags() & NativeServerSession.CLIENT_COMPRESS) != 0)
            && pset.getBooleanReadableProperty(PropertyDefinitions.PNAME_useCompression).getValue()
            && !(this.socketConnection.getMysqlInput().getUnderlyingStream() instanceof CompressedInputStream)) {
        this.useCompression = true;
        this.socketConnection.setMysqlInput(new CompressedInputStream(this.socketConnection.getMysqlInput(),
                pset.getBooleanReadableProperty(PropertyDefinitions.PNAME_traceProtocol), this.log));
        this.compressedPacketSender = new CompressedPacketSender(this.socketConnection.getMysqlOutput());
        this.packetSender = this.compressedPacketSender;
    }

    applyPacketDecorators(this.packetSender, this.packetReader);

    try {
        this.socketConnection.getSocketFactory().afterHandshake();
    } catch (IOException ioEx) {
        throw ExceptionFactory.createCommunicationsException(this.getPropertySet(), this.serverSession,
                this.getPacketSentTimeHolder().getLastPacketSentTime(), this.getPacketReceivedTimeHolder().getLastPacketReceivedTime(), ioEx,
                getExceptionInterceptor());
    }

    // listen for properties changes to allow decorators reconfiguration
    this.maintainTimeStats.addListener(this);
    pset.getBooleanReadableProperty(PropertyDefinitions.PNAME_traceProtocol).addListener(this);
    pset.getBooleanReadableProperty(PropertyDefinitions.PNAME_enablePacketDebug).addListener(this);
}
 
Example #18
Source File: XProtocol.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public void init(Session sess, SocketConnection socketConn, PropertySet propSet, TransactionEventHandler transactionManager) {
    this.socketConnection = socketConn;
    this.propertySet = propSet;
    this.messageBuilder = new XMessageBuilder();

    this.authProvider = new XAuthenticationProvider();
    this.authProvider.init(this, propSet, null);

    this.metadataCharacterSet = "latin1"; // TODO configure from server session
    this.fieldFactory = new FieldFactory(this.metadataCharacterSet);
    this.noticeFactory = new NoticeFactory();
}
 
Example #19
Source File: XProtocol.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static XProtocol getInstance(String host, int port, PropertySet propertySet) {

        SocketConnection socketConnection = propertySet.getBooleanReadableProperty(PropertyDefinitions.PNAME_useAsyncProtocol).getValue()
                ? new XAsyncSocketConnection() :
                // TODO: we should share SocketConnection unless there comes a time where they need to diverge
                new NativeSocketConnection();

        socketConnection.connect(host, port, propertySet, null, null, 0);

        XProtocol protocol = new XProtocol();
        protocol.init(null, socketConnection, propertySet, null);
        return protocol;
    }
 
Example #20
Source File: NativeProtocol.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterHandshake() {

    checkTransactionState();

    PropertySet pset = this.getPropertySet();

    //
    // Can't enable compression until after handshake
    //
    if (((this.serverSession.getCapabilities().getCapabilityFlags() & NativeServerSession.CLIENT_COMPRESS) != 0)
            && pset.getBooleanProperty(PropertyKey.useCompression).getValue()
            && !(this.socketConnection.getMysqlInput().getUnderlyingStream() instanceof CompressedInputStream)) {
        this.useCompression = true;
        this.socketConnection.setMysqlInput(
                new CompressedInputStream(this.socketConnection.getMysqlInput(), pset.getBooleanProperty(PropertyKey.traceProtocol), this.log));
        this.compressedPacketSender = new CompressedPacketSender(this.socketConnection.getMysqlOutput());
        this.packetSender = this.compressedPacketSender;
    }

    applyPacketDecorators(this.packetSender, this.packetReader);

    try {
        this.socketConnection.getSocketFactory().afterHandshake();
    } catch (IOException ioEx) {
        throw ExceptionFactory.createCommunicationsException(this.getPropertySet(), this.serverSession, this.getPacketSentTimeHolder(),
                this.getPacketReceivedTimeHolder(), ioEx, getExceptionInterceptor());
    }

    // listen for properties changes to allow decorators reconfiguration
    this.maintainTimeStats.addListener(this);
    pset.getBooleanProperty(PropertyKey.traceProtocol).addListener(this);
    pset.getBooleanProperty(PropertyKey.enablePacketDebug).addListener(this);
}
 
Example #21
Source File: ExportControlled.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Converts the socket being used in the given CoreIO to an SSLSocket by
 * performing the SSL/TLS handshake.
 * 
 * @param rawSocket
 *            original non-SSL socket
 * @param socketConnection
 *            the Protocol instance containing the socket to convert to an
 *            SSLSocket.
 * @param serverVersion
 *            ServerVersion object
 * @return SSL socket
 * @throws IOException
 *             if i/o exception occurs
 * @throws SSLParamsException
 *             if the handshake fails, or if this distribution of
 *             Connector/J doesn't contain the SSL crypto hooks needed to
 *             perform the handshake.
 * @throws FeatureNotAvailableException
 *             if TLS is not supported
 */
public static Socket performTlsHandshake(Socket rawSocket, SocketConnection socketConnection, ServerVersion serverVersion)
        throws IOException, SSLParamsException, FeatureNotAvailableException {

    PropertySet pset = socketConnection.getPropertySet();

    SslMode sslMode = pset.<SslMode> getEnumProperty(PropertyKey.sslMode).getValue();
    boolean verifyServerCert = sslMode == SslMode.VERIFY_CA || sslMode == SslMode.VERIFY_IDENTITY;

    KeyStoreConf trustStore = !verifyServerCert ? new KeyStoreConf() : getTrustStoreConf(pset, PropertyKey.trustCertificateKeyStoreUrl,
            PropertyKey.trustCertificateKeyStorePassword, PropertyKey.trustCertificateKeyStoreType, verifyServerCert && serverVersion == null);

    KeyStoreConf keyStore = getKeyStoreConf(pset, PropertyKey.clientCertificateKeyStoreUrl, PropertyKey.clientCertificateKeyStorePassword,
            PropertyKey.clientCertificateKeyStoreType);

    SSLSocketFactory socketFactory = getSSLContext(keyStore.keyStoreUrl, keyStore.keyStoreType, keyStore.keyStorePassword, trustStore.keyStoreUrl,
            trustStore.keyStoreType, trustStore.keyStorePassword, serverVersion != null, verifyServerCert,
            sslMode == PropertyDefinitions.SslMode.VERIFY_IDENTITY ? socketConnection.getHost() : null, socketConnection.getExceptionInterceptor())
                    .getSocketFactory();

    SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(rawSocket, socketConnection.getHost(), socketConnection.getPort(), true);

    sslSocket.setEnabledProtocols(getAllowedProtocols(pset, serverVersion, sslSocket.getSupportedProtocols()));

    String[] allowedCiphers = getAllowedCiphers(pset, serverVersion, sslSocket.getEnabledCipherSuites());
    if (allowedCiphers != null) {
        sslSocket.setEnabledCipherSuites(allowedCiphers);
    }

    sslSocket.startHandshake();

    return sslSocket;
}
 
Example #22
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 #23
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SessionImpl(HostInfo hostInfo) {
    PropertySet pset = new DefaultPropertySet();
    pset.initializeProperties(hostInfo.exposeAsProperties());
    this.session = new MysqlxSession(hostInfo, pset);
    this.defaultSchemaName = hostInfo.getDatabase();
    this.xbuilder = (XMessageBuilder) this.session.<XMessage> getMessageBuilder();
}
 
Example #24
Source File: SessionImpl.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public String getUri() {
    PropertySet pset = this.session.getPropertySet();

    StringBuilder sb = new StringBuilder(ConnectionUrl.Type.XDEVAPI_SESSION.getScheme());
    sb.append("//").append(this.session.getProcessHost()).append(":").append(this.session.getPort()).append("/").append(this.defaultSchemaName).append("?");

    boolean isFirstParam = true;

    for (PropertyKey propKey : PropertyDefinitions.PROPERTY_KEY_TO_PROPERTY_DEFINITION.keySet()) {
        RuntimeProperty<?> propToGet = pset.getProperty(propKey);
        if (propToGet.isExplicitlySet()) {
            String propValue = propToGet.getStringValue();
            Object defaultValue = propToGet.getPropertyDefinition().getDefaultValue();
            if (defaultValue == null && !StringUtils.isNullOrEmpty(propValue) || defaultValue != null && propValue == null
                    || defaultValue != null && propValue != null && !propValue.equals(defaultValue.toString())) {
                if (isFirstParam) {
                    isFirstParam = false;
                } else {
                    sb.append("&");
                }
                sb.append(propKey.getKeyName());
                sb.append("=");
                sb.append(propValue);
            }

            // TODO custom properties?
        }
    }

    // TODO modify for multi-host connections

    return sb.toString();

}
 
Example #25
Source File: SessionImpl.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param hostInfo
 *            {@link HostInfo} instance
 */
public SessionImpl(HostInfo hostInfo) {
    PropertySet pset = new DefaultPropertySet();
    pset.initializeProperties(hostInfo.exposeAsProperties());
    this.session = new MysqlxSession(hostInfo, pset);
    this.defaultSchemaName = hostInfo.getDatabase();
    this.xbuilder = (XMessageBuilder) this.session.<XMessage> getMessageBuilder();
}
 
Example #26
Source File: ExportControlled.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public static AsynchronousSocketChannel startTlsOnAsynchronousChannel(AsynchronousSocketChannel channel, SocketConnection socketConnection)
        throws SSLException {

    PropertySet propertySet = socketConnection.getPropertySet();

    SslMode sslMode = propertySet.<SslMode> getEnumProperty(PropertyKey.sslMode).getValue();

    boolean verifyServerCert = sslMode == SslMode.VERIFY_CA || sslMode == SslMode.VERIFY_IDENTITY;
    KeyStoreConf trustStore = !verifyServerCert ? new KeyStoreConf() : getTrustStoreConf(propertySet, PropertyKey.trustCertificateKeyStoreUrl,
            PropertyKey.trustCertificateKeyStorePassword, PropertyKey.trustCertificateKeyStoreType, true);

    KeyStoreConf keyStore = getKeyStoreConf(propertySet, PropertyKey.clientCertificateKeyStoreUrl, PropertyKey.clientCertificateKeyStorePassword,
            PropertyKey.clientCertificateKeyStoreType);

    SSLContext sslContext = ExportControlled.getSSLContext(keyStore.keyStoreUrl, keyStore.keyStoreType, keyStore.keyStorePassword, trustStore.keyStoreUrl,
            trustStore.keyStoreType, trustStore.keyStorePassword, false, verifyServerCert,
            sslMode == PropertyDefinitions.SslMode.VERIFY_IDENTITY ? socketConnection.getHost() : null, null);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);

    sslEngine.setEnabledProtocols(getAllowedProtocols(propertySet, null, sslEngine.getSupportedProtocols()));

    String[] allowedCiphers = getAllowedCiphers(propertySet, null, sslEngine.getEnabledCipherSuites());
    if (allowedCiphers != null) {
        sslEngine.setEnabledCipherSuites(allowedCiphers);
    }

    performTlsHandshake(sslEngine, channel);

    return new TlsAsynchronousSocketChannel(channel, sslEngine);
}
 
Example #27
Source File: CJCommunicationsException.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public void init(PropertySet propertySet, ServerSession serverSession, PacketSentTimeHolder packetSentTimeHolder,
        PacketReceivedTimeHolder packetReceivedTimeHolder) {
    this.exceptionMessage = ExceptionFactory.createLinkFailureMessageBasedOnHeuristics(propertySet, serverSession, packetSentTimeHolder,
            packetReceivedTimeHolder, getCause());
}
 
Example #28
Source File: NativeServerSession.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public NativeServerSession(PropertySet propertySet) {
    this.propertySet = propertySet;

    // preconfigure some server variables which are consulted before their initialization from server
    this.serverVariables.put("character_set_server", "utf8");
}
 
Example #29
Source File: NativeProtocol.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public static NativeProtocol getInstance(Session session, SocketConnection socketConnection, PropertySet propertySet, Log log,
        TransactionEventHandler transactionManager) {
    NativeProtocol protocol = new NativeProtocol(log);
    protocol.init(session, socketConnection, propertySet, transactionManager);
    return protocol;
}
 
Example #30
Source File: NativeProtocol.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void init(Session sess, SocketConnection phConnection, PropertySet propSet, TransactionEventHandler trManager) {

    this.session = sess;
    this.propertySet = propSet;

    this.socketConnection = phConnection;
    this.exceptionInterceptor = this.socketConnection.getExceptionInterceptor();

    this.transactionManager = trManager;

    this.maintainTimeStats = this.propertySet.getBooleanProperty(PropertyKey.maintainTimeStats);
    this.maxQuerySizeToLog = this.propertySet.getIntegerProperty(PropertyKey.maxQuerySizeToLog);
    this.useAutoSlowLog = this.propertySet.getBooleanProperty(PropertyKey.autoSlowLog).getValue();
    this.logSlowQueries = this.propertySet.getBooleanProperty(PropertyKey.logSlowQueries).getValue();
    this.maxAllowedPacket = this.propertySet.getIntegerProperty(PropertyKey.maxAllowedPacket);
    this.profileSQL = this.propertySet.getBooleanProperty(PropertyKey.profileSQL).getValue();
    this.autoGenerateTestcaseScript = this.propertySet.getBooleanProperty(PropertyKey.autoGenerateTestcaseScript).getValue();
    this.useServerPrepStmts = this.propertySet.getBooleanProperty(PropertyKey.useServerPrepStmts);

    this.reusablePacket = new NativePacketPayload(INITIAL_PACKET_SIZE);
    //this.sendPacket = new Buffer(INITIAL_PACKET_SIZE);

    this.packetSender = new SimplePacketSender(this.socketConnection.getMysqlOutput());
    this.packetReader = new SimplePacketReader(this.socketConnection, this.maxAllowedPacket);

    //this.needToGrabQueryFromPacket = (this.profileSQL || this.logSlowQueries || this.autoGenerateTestcaseScript);

    if (this.propertySet.getBooleanProperty(PropertyKey.useNanosForElapsedTime).getValue() && TimeUtil.nanoTimeAvailable()) {
        this.useNanosForElapsedTime = true;

        this.queryTimingUnits = Messages.getString("Nanoseconds");
    } else {
        this.queryTimingUnits = Messages.getString("Milliseconds");
    }

    if (this.propertySet.getBooleanProperty(PropertyKey.logSlowQueries).getValue()) {
        calculateSlowQueryThreshold();
    }

    this.authProvider = new NativeAuthenticationProvider();
    this.authProvider.init(this, this.getPropertySet(), this.socketConnection.getExceptionInterceptor());

    Map<Class<? extends ProtocolEntity>, ProtocolEntityReader<? extends ProtocolEntity, NativePacketPayload>> protocolEntityClassToTextReader = new HashMap<>();
    protocolEntityClassToTextReader.put(ColumnDefinition.class, new ColumnDefinitionReader(this));
    protocolEntityClassToTextReader.put(ResultsetRow.class, new ResultsetRowReader(this));
    protocolEntityClassToTextReader.put(Resultset.class, new TextResultsetReader(this));
    this.PROTOCOL_ENTITY_CLASS_TO_TEXT_READER = Collections.unmodifiableMap(protocolEntityClassToTextReader);

    Map<Class<? extends ProtocolEntity>, ProtocolEntityReader<? extends ProtocolEntity, NativePacketPayload>> protocolEntityClassToBinaryReader = new HashMap<>();
    protocolEntityClassToBinaryReader.put(ColumnDefinition.class, new ColumnDefinitionReader(this));
    protocolEntityClassToBinaryReader.put(Resultset.class, new BinaryResultsetReader(this));
    this.PROTOCOL_ENTITY_CLASS_TO_BINARY_READER = Collections.unmodifiableMap(protocolEntityClassToBinaryReader);

}