Java Code Examples for com.mysql.cj.conf.PropertySet

The following examples show how to use com.mysql.cj.conf.PropertySet. 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: quarkus   Source File: JDBCMySQLProcessor.java    License: 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 2
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 3
Source Project: lams   Source File: ExceptionFactory.java    License: 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 4
Source Project: lams   Source File: MysqlxSession.java    License: 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 5
Source Project: lams   Source File: SessionImpl.java    License: 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 6
Source Project: lams   Source File: CoreSession.java    License: 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 7
@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 8
Source Project: FoxTelem   Source File: XProtocol.java    License: 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 9
Source Project: FoxTelem   Source File: XProtocol.java    License: 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 10
Source Project: FoxTelem   Source File: ExceptionFactory.java    License: 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 11
/**
 * 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 12
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 13
Source Project: FoxTelem   Source File: ExportControlled.java    License: 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 14
@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 15
Source Project: FoxTelem   Source File: CoreSession.java    License: 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 16
Source Project: lams   Source File: XProtocol.java    License: 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 17
Source Project: lams   Source File: XProtocol.java    License: 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 18
Source Project: lams   Source File: NativeProtocol.java    License: 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 19
Source Project: lams   Source File: SessionImpl.java    License: 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 20
Source Project: FoxTelem   Source File: SessionImpl.java    License: 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 21
Source Project: FoxTelem   Source File: SessionImpl.java    License: 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 22
Source Project: FoxTelem   Source File: XProtocol.java    License: 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 23
Source Project: FoxTelem   Source File: NativeProtocol.java    License: 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 24
Source Project: FoxTelem   Source File: ExportControlled.java    License: 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 25
Source Project: FoxTelem   Source File: ExportControlled.java    License: 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 26
Source Project: FoxTelem   Source File: ExportControlled.java    License: 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 Project: lams   Source File: XAuthenticationProvider.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public void init(Protocol<XMessage> prot, PropertySet propertySet, ExceptionInterceptor exceptionInterceptor) {
    this.protocol = (XProtocol) prot;
}
 
Example 28
Source Project: lams   Source File: AsyncMessageReader.java    License: GNU General Public License v2.0 4 votes vote down vote up
public AsyncMessageReader(PropertySet propertySet, SocketConnection socketConnection) {
    this.propertySet = propertySet;
    this.sc = socketConnection;
}
 
Example 29
Source Project: lams   Source File: AsyncMessageReader.java    License: GNU General Public License v2.0 4 votes vote down vote up
public SyncReader(PropertySet propertySet, AsyncMessageReader rdr, Class<T> expectedClass) {
    this.asyncTimeout = propertySet.getIntegerReadableProperty(PropertyDefinitions.PNAME_asyncResponseTimeout);
    this.expectedClass = expectedClass;
    rdr.pushMessageListener(this);
}
 
Example 30
Source Project: lams   Source File: AbstractProtocol.java    License: GNU General Public License v2.0 4 votes vote down vote up
public PropertySet getPropertySet() {
    return this.propertySet;
}