diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginFactory.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginFactory.java index a6bb12047..f308c8c52 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginFactory.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginFactory.java @@ -13,7 +13,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * */ package com.amazon.awslabs.jdbc; diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginManager.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginManager.java index 584e2a73e..4630b5398 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginManager.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionPluginManager.java @@ -55,18 +55,19 @@ */ public class ConnectionPluginManager implements CanReleaseResources { - protected static final Map> pluginFactoriesByCode = - new HashMap>() { - { - put("executionTime", ExecutionTimeConnectionPluginFactory.class); - put("auroraHostList", AuroraHostListConnectionPluginFactory.class); - put("logQuery", LogQueryConnectionPluginFactory.class); - put("dataCache", DataCacheConnectionPluginFactory.class); - put("efm", HostMonitoringConnectionPluginFactory.class); - put("failover", FailoverConnectionPluginFactory.class); - put("iam", IamAuthConnectionPluginFactory.class); - } - }; + protected static final Map> + pluginFactoriesByCode = + new HashMap>() { + { + put("executionTime", ExecutionTimeConnectionPluginFactory.class); + put("auroraHostList", AuroraHostListConnectionPluginFactory.class); + put("logQuery", LogQueryConnectionPluginFactory.class); + put("dataCache", DataCacheConnectionPluginFactory.class); + put("efm", HostMonitoringConnectionPluginFactory.class); + put("failover", FailoverConnectionPluginFactory.class); + put("iam", IamAuthConnectionPluginFactory.class); + } + }; protected static final String DEFAULT_PLUGINS = ""; diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionProvider.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionProvider.java index 9fa0a9cbf..937211e7f 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionProvider.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ConnectionProvider.java @@ -23,9 +23,7 @@ import java.util.Properties; import org.checkerframework.checker.nullness.qual.NonNull; -/** - * Implement this interface in order to handle physical connection creation process. - */ +/** Implement this interface in order to handle physical connection creation process. */ public interface ConnectionProvider { /** @@ -33,7 +31,7 @@ public interface ConnectionProvider { * * @param protocol The connection protocol (example "jdbc:mysql://") * @param hostSpec The HostSpec containing the host-port information for the host to connect to - * @param props The Properties to use for the connection + * @param props The Properties to use for the connection * @return {@link Connection} resulting from the given connection information * @throws SQLException if an error occurs */ @@ -44,7 +42,7 @@ Connection connect( /** * Called once per connection that needs to be created. * - * @param url The connection URL + * @param url The connection URL * @param props The Properties to use for the connection * @return {@link Connection} resulting from the given connection information * @throws SQLException if an error occurs diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/DataSourceConnectionProvider.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/DataSourceConnectionProvider.java index d042427c7..cc735f4a2 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/DataSourceConnectionProvider.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/DataSourceConnectionProvider.java @@ -50,13 +50,14 @@ public DataSourceConnectionProvider(final DataSource dataSource) { this(dataSource, null, null, null, null, null, null); } - public DataSourceConnectionProvider(final @NonNull DataSource dataSource, - final @Nullable String serverPropertyName, - final @Nullable String portPropertyName, - final @Nullable String urlPropertyName, - final @Nullable String databasePropertyName, - final @Nullable String usernamePropertyName, - final @Nullable String passwordPropertyName) { + public DataSourceConnectionProvider( + final @NonNull DataSource dataSource, + final @Nullable String serverPropertyName, + final @Nullable String portPropertyName, + final @Nullable String urlPropertyName, + final @Nullable String databasePropertyName, + final @Nullable String usernamePropertyName, + final @Nullable String passwordPropertyName) { this.dataSource = dataSource; this.serverPropertyName = serverPropertyName; this.portPropertyName = portPropertyName; @@ -92,21 +93,26 @@ public Connection connect( copy.put(this.portPropertyName, hostSpec.getPort()); } - if (!isNullOrEmpty(this.databasePropertyName) && !isNullOrEmpty(props.getProperty(DATABASE_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.databasePropertyName) + && !isNullOrEmpty(props.getProperty(DATABASE_PROPERTY_NAME))) { copy.setProperty(this.databasePropertyName, props.getProperty(DATABASE_PROPERTY_NAME)); } - if (!isNullOrEmpty(this.userPropertyName) && !isNullOrEmpty(props.getProperty(USER_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.userPropertyName) + && !isNullOrEmpty(props.getProperty(USER_PROPERTY_NAME))) { copy.setProperty(this.userPropertyName, props.getProperty(USER_PROPERTY_NAME)); } - if (!isNullOrEmpty(this.passwordPropertyName) && !isNullOrEmpty(props.getProperty(PASSWORD_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.passwordPropertyName) + && !isNullOrEmpty(props.getProperty(PASSWORD_PROPERTY_NAME))) { copy.setProperty(this.passwordPropertyName, props.getProperty(PASSWORD_PROPERTY_NAME)); } - if (!isNullOrEmpty(this.urlPropertyName) && !isNullOrEmpty(props.getProperty(this.urlPropertyName))) { + if (!isNullOrEmpty(this.urlPropertyName) + && !isNullOrEmpty(props.getProperty(this.urlPropertyName))) { Properties urlProperties = PropertyUtils.copyProperties(copy); - // Remove the current url property to replace with a new url built from updated HostSpec and properties + // Remove the current url property to replace with a new url built from updated HostSpec and + // properties urlProperties.remove(this.urlPropertyName); copy.setProperty( @@ -134,22 +140,26 @@ public Connection connect( * @return {@link Connection} resulting from the given connection information * @throws SQLException if an error occurs */ - public Connection connect(final @NonNull String url, final @NonNull Properties props) throws SQLException { + public Connection connect(final @NonNull String url, final @NonNull Properties props) + throws SQLException { Properties copy = PropertyUtils.copyProperties(props); if (!isNullOrEmpty(this.urlPropertyName)) { copy.setProperty(this.urlPropertyName, url); } - if (!isNullOrEmpty(this.userPropertyName) && !isNullOrEmpty(props.getProperty(USER_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.userPropertyName) + && !isNullOrEmpty(props.getProperty(USER_PROPERTY_NAME))) { copy.put(this.userPropertyName, props.getProperty(USER_PROPERTY_NAME)); } - if (!isNullOrEmpty(this.passwordPropertyName) && !isNullOrEmpty(props.getProperty(PASSWORD_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.passwordPropertyName) + && !isNullOrEmpty(props.getProperty(PASSWORD_PROPERTY_NAME))) { copy.put(this.passwordPropertyName, props.getProperty(PASSWORD_PROPERTY_NAME)); } - if (!isNullOrEmpty(this.databasePropertyName) && !isNullOrEmpty(props.getProperty(DATABASE_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.databasePropertyName) + && !isNullOrEmpty(props.getProperty(DATABASE_PROPERTY_NAME))) { copy.put(this.databasePropertyName, props.getProperty(DATABASE_PROPERTY_NAME)); } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/DriverConnectionProvider.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/DriverConnectionProvider.java index c576a7a80..2f6ed9536 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/DriverConnectionProvider.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/DriverConnectionProvider.java @@ -29,8 +29,8 @@ import org.checkerframework.checker.nullness.qual.NonNull; /** - * This class is a basic implementation of {@link ConnectionProvider} interface. It creates and returns a connection - * provided by a target driver or a data source. + * This class is a basic implementation of {@link ConnectionProvider} interface. It creates and + * returns a connection provided by a target driver or a data source. */ public class DriverConnectionProvider implements ConnectionProvider { @@ -42,7 +42,8 @@ public DriverConnectionProvider(final java.sql.Driver driver) { this(driver, null, null); } - public DriverConnectionProvider(final java.sql.Driver driver, String userPropertyName, String passwordPropertyName) { + public DriverConnectionProvider( + final java.sql.Driver driver, String userPropertyName, String passwordPropertyName) { this.driver = driver; this.userPropertyName = userPropertyName; this.passwordPropertyName = passwordPropertyName; @@ -53,7 +54,7 @@ public DriverConnectionProvider(final java.sql.Driver driver, String userPropert * * @param protocol The connection protocol (example "jdbc:mysql://") * @param hostSpec The HostSpec containing the host-port information for the host to connect to - * @param props The Properties to use for the connection + * @param props The Properties to use for the connection * @return {@link Connection} resulting from the given connection information * @throws SQLException if an error occurs */ @@ -65,15 +66,19 @@ public Connection connect( throws SQLException { final String databaseName = - props.getProperty(DATABASE_PROPERTY_NAME) != null ? props.getProperty(DATABASE_PROPERTY_NAME) : ""; + props.getProperty(DATABASE_PROPERTY_NAME) != null + ? props.getProperty(DATABASE_PROPERTY_NAME) + : ""; final StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(protocol).append(hostSpec.getUrl()).append(databaseName); - if (!isNullOrEmpty(this.userPropertyName) && !isNullOrEmpty(props.getProperty(USER_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.userPropertyName) + && !isNullOrEmpty(props.getProperty(USER_PROPERTY_NAME))) { props.setProperty(this.userPropertyName, props.getProperty(USER_PROPERTY_NAME)); } - if (!isNullOrEmpty(this.passwordPropertyName) && !isNullOrEmpty(props.getProperty(PASSWORD_PROPERTY_NAME))) { + if (!isNullOrEmpty(this.passwordPropertyName) + && !isNullOrEmpty(props.getProperty(PASSWORD_PROPERTY_NAME))) { props.setProperty(this.passwordPropertyName, props.getProperty(PASSWORD_PROPERTY_NAME)); } @@ -83,7 +88,7 @@ public Connection connect( /** * Called once per connection that needs to be created. * - * @param url The connection URL + * @param url The connection URL * @param props The Properties to use for the connection * @return {@link Connection} resulting from the given connection information * @throws SQLException if an error occurs diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/HostListProviderService.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/HostListProviderService.java index 2568aeee6..4c8f8de96 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/HostListProviderService.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/HostListProviderService.java @@ -18,8 +18,6 @@ package com.amazon.awslabs.jdbc; -import com.amazon.awslabs.jdbc.HostListProvider; - public interface HostListProviderService { boolean isStaticHostListProvider(); diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginService.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginService.java index d06667422..539a6b569 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginService.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginService.java @@ -18,11 +18,6 @@ package com.amazon.awslabs.jdbc; -import com.amazon.awslabs.jdbc.ConnectionPlugin; -import com.amazon.awslabs.jdbc.HostAvailability; -import com.amazon.awslabs.jdbc.HostListProvider; -import com.amazon.awslabs.jdbc.HostSpec; -import com.amazon.awslabs.jdbc.NodeChangeOptions; import java.sql.Connection; import java.sql.SQLException; import java.util.EnumSet; @@ -33,7 +28,8 @@ import org.checkerframework.checker.nullness.qual.Nullable; /** - * Interface for retrieving the current active {@link Connection} and its {@link HostSpec}. + * Interface for retrieving the current active {@link Connection} and its {@link + * com.amazon.awslabs.jdbc.HostSpec}. */ public interface PluginService { diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginServiceImpl.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginServiceImpl.java index 31e094401..deddb7ce9 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginServiceImpl.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/PluginServiceImpl.java @@ -37,8 +37,8 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; -public class PluginServiceImpl implements PluginService, CanReleaseResources, HostListProviderService, - PluginManagerService { +public class PluginServiceImpl + implements PluginService, CanReleaseResources, HostListProviderService, PluginManagerService { private static final Logger LOGGER = Logger.getLogger(PluginServiceImpl.class.getName()); @@ -108,8 +108,8 @@ public synchronized EnumSet setCurrentConnection( } else { // update an existing connection - EnumSet changes = compare(this.currentConnection, this.currentHostSpec, - connection, hostSpec); + EnumSet changes = + compare(this.currentConnection, this.currentHostSpec, connection, hostSpec); if (!changes.isEmpty()) { @@ -119,8 +119,8 @@ public synchronized EnumSet setCurrentConnection( this.currentHostSpec = hostSpec; this.setInTransaction(false); - EnumSet pluginOpinions = this.pluginManager.notifyConnectionChanged( - changes, skipNotificationForThisPlugin); + EnumSet pluginOpinions = + this.pluginManager.notifyConnectionChanged(changes, skipNotificationForThisPlugin); boolean shouldCloseConnection = changes.contains(NodeChangeOptions.CONNECTION_OBJECT_CHANGED) @@ -192,20 +192,27 @@ public List getHosts() { } @Override - public void setAvailability(final @NonNull Set hostAliases, final @NonNull HostAvailability availability) { + public void setAvailability( + final @NonNull Set hostAliases, final @NonNull HostAvailability availability) { if (hostAliases.isEmpty()) { return; } - List hostsToChange = this.getHosts().stream() - .filter((host) -> hostAliases.contains(host.asAlias()) - || host.getAliases().stream().anyMatch((hostAlias) -> hostAliases.contains(hostAlias))) - .distinct() - .collect(Collectors.toList()); + List hostsToChange = + this.getHosts().stream() + .filter( + (host) -> + hostAliases.contains(host.asAlias()) + || host.getAliases().stream() + .anyMatch((hostAlias) -> hostAliases.contains(hostAlias))) + .distinct() + .collect(Collectors.toList()); if (hostsToChange.isEmpty()) { - LOGGER.log(Level.FINEST, String.format("Can't find any host by the following aliases: %s.", hostAliases)); + LOGGER.log( + Level.FINEST, + String.format("Can't find any host by the following aliases: %s.", hostAliases)); return; } @@ -236,7 +243,8 @@ public boolean isExplicitReadOnly() { @Override public boolean isReadOnly() { - return isExplicitReadOnly() || (this.currentHostSpec != null && this.currentHostSpec.getRole() != HostRole.WRITER); + return isExplicitReadOnly() + || (this.currentHostSpec != null && this.currentHostSpec.getRole() != HostRole.WRITER); } @Override @@ -259,7 +267,8 @@ public HostListProvider getHostListProvider() { if (this.hostListProvider == null) { synchronized (this) { if (this.hostListProvider == null) { - this.hostListProvider = new ConnectionStringHostListProvider(this.props, this.originalUrl); + this.hostListProvider = + new ConnectionStringHostListProvider(this.props, this.originalUrl); this.currentHostSpec = this.getCurrentHostSpec(); } } @@ -277,16 +286,18 @@ public void forceRefreshHostList() throws SQLException { setNodeList(this.hosts, this.getHostListProvider().forceRefresh()); } - void setNodeList(@Nullable final List oldHosts, - @Nullable final List newHosts) { + void setNodeList( + @Nullable final List oldHosts, @Nullable final List newHosts) { - Map oldHostMap = oldHosts == null - ? new HashMap<>() - : oldHosts.stream().collect(Collectors.toMap(HostSpec::getUrl, (value) -> value)); + Map oldHostMap = + oldHosts == null + ? new HashMap<>() + : oldHosts.stream().collect(Collectors.toMap(HostSpec::getUrl, (value) -> value)); - Map newHostMap = newHosts == null - ? new HashMap<>() - : newHosts.stream().collect(Collectors.toMap(HostSpec::getUrl, (value) -> value)); + Map newHostMap = + newHosts == null + ? new HashMap<>() + : newHosts.stream().collect(Collectors.toMap(HostSpec::getUrl, (value) -> value)); Map> changes = new HashMap<>(); @@ -297,8 +308,8 @@ void setNodeList(@Nullable final List oldHosts, changes.put(entry.getKey(), EnumSet.of(NodeChangeOptions.NODE_DELETED)); } else { // host maybe changed - EnumSet hostChanges = compare(null, entry.getValue(), null, - correspondingNewHost); + EnumSet hostChanges = + compare(null, entry.getValue(), null, correspondingNewHost); if (!hostChanges.isEmpty()) { changes.put(entry.getKey(), hostChanges); } @@ -330,7 +341,8 @@ public void setHostListProvider(HostListProvider hostListProvider) { @Override public Connection connect(HostSpec hostSpec, Properties props) throws SQLException { - return this.pluginManager.connect(this.driverProtocol, hostSpec, props, this.currentConnection == null); + return this.pluginManager.connect( + this.driverProtocol, hostSpec, props, this.currentConnection == null); } @Override diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/PropertyDefinition.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/PropertyDefinition.java index 8d7e79a47..b2bf07953 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/PropertyDefinition.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/PropertyDefinition.java @@ -39,12 +39,12 @@ public class PropertyDefinition { public static final ProxyDriverProperty ENABLE_CLUSTER_AWARE_FAILOVER = new ProxyDriverProperty( - "enableClusterAwareFailover", "true", - "Enable/disable cluster-aware failover logic"); + "enableClusterAwareFailover", "true", "Enable/disable cluster-aware failover logic"); public static final ProxyDriverProperty LOG_UNCLOSED_CONNECTIONS = new ProxyDriverProperty( - "proxyDriverLogUnclosedConnections", "false", + "proxyDriverLogUnclosedConnections", + "false", "Allows the driver to track a point in the code where connection has been opened and never closed after"); public static final ProxyDriverProperty LOGGER_LEVEL = @@ -54,7 +54,7 @@ public class PropertyDefinition { "Logger level of the driver", false, new String[] { - "OFF", "SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST", "ALL" + "OFF", "SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST", "ALL" }); public static final ProxyDriverProperty PLUGINS = @@ -62,18 +62,19 @@ public class PropertyDefinition { "proxyDriverPlugins", null, "Comma separated list of connection plugin codes"); public static final ProxyDriverProperty PROFILE_NAME = - new ProxyDriverProperty( - "proxyDriverProfileName", null, "Driver configuration profile name"); + new ProxyDriverProperty("proxyDriverProfileName", null, "Driver configuration profile name"); public static final ProxyDriverProperty USE_AWS_IAM = new ProxyDriverProperty( "useAwsIam", "false", "Set to true to use AWS IAM database authentication"); - public static final ProxyDriverProperty CLUSTER_ID = new ProxyDriverProperty( - "clusterId", "", - "A unique identifier for the cluster. " - + "Connections with the same cluster id share a cluster topology cache. " - + "If unspecified, a cluster id is automatically created for AWS RDS clusters."); + public static final ProxyDriverProperty CLUSTER_ID = + new ProxyDriverProperty( + "clusterId", + "", + "A unique identifier for the cluster. " + + "Connections with the same cluster id share a cluster topology cache. " + + "If unspecified, a cluster id is automatically created for AWS RDS clusters."); private static final Map PROPS_BY_NAME = new HashMap(); diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ds/ProxyDriverDataSource.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ds/ProxyDriverDataSource.java index 5a249ca6a..2e0f9e97f 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/ds/ProxyDriverDataSource.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/ds/ProxyDriverDataSource.java @@ -94,13 +94,15 @@ public Connection getConnection(String username, String password) throws SQLExce if (!isNullOrEmpty(this.targetDataSourceClassName)) { final DataSource targetDataSource = createTargetDataSource(); - if (!isNullOrEmpty(this.databasePropertyName) && !isNullOrEmpty(props.getProperty(this.databasePropertyName))) { + if (!isNullOrEmpty(this.databasePropertyName) + && !isNullOrEmpty(props.getProperty(this.databasePropertyName))) { props.put(DATABASE_PROPERTY_NAME, props.getProperty(this.databasePropertyName)); } // If the url is set explicitly through setJdbcUrl or the connection properties. if (!isNullOrEmpty(this.jdbcUrl) - || (!isNullOrEmpty(this.urlPropertyName) && !isNullOrEmpty(props.getProperty(this.urlPropertyName)))) { + || (!isNullOrEmpty(this.urlPropertyName) + && !isNullOrEmpty(props.getProperty(this.urlPropertyName)))) { setJdbcUrlOrUrlProperty(props); setDatabasePropertyFromUrl(props); if (isNullOrEmpty(this.user) || isNullOrEmpty(this.password)) { @@ -108,15 +110,16 @@ public Connection getConnection(String username, String password) throws SQLExce } } else { - this.jdbcUrl = buildUrl( - this.jdbcProtocol, - null, - this.serverPropertyName, - this.portPropertyName, - this.databasePropertyName, - this.userPropertyName, - this.passwordPropertyName, - props); + this.jdbcUrl = + buildUrl( + this.jdbcProtocol, + null, + this.serverPropertyName, + this.portPropertyName, + this.databasePropertyName, + this.userPropertyName, + this.passwordPropertyName, + props); } if (isNullOrEmpty(this.jdbcUrl)) { @@ -152,9 +155,7 @@ public Connection getConnection(String username, String password) throws SQLExce props, this.jdbcUrl, new DriverConnectionProvider( - targetDriver, - this.userPropertyName, - this.passwordPropertyName)); + targetDriver, this.userPropertyName, this.passwordPropertyName)); } } @@ -305,7 +306,8 @@ private void setCredentialProperties(Properties props) { props.setProperty(USER_PROPERTY_NAME, this.user); // If username was provided in targetDataSourceProperties and a userPropertyName is set. - } else if (!isNullOrEmpty(this.userPropertyName) && !isNullOrEmpty(props.getProperty(this.userPropertyName))) { + } else if (!isNullOrEmpty(this.userPropertyName) + && !isNullOrEmpty(props.getProperty(this.userPropertyName))) { props.setProperty(USER_PROPERTY_NAME, props.getProperty(this.userPropertyName)); this.user = props.getProperty(this.userPropertyName); } @@ -336,13 +338,15 @@ private void setDatabasePropertyFromUrl(Properties props) { } private void setCredentialPropertiesFromUrl(Properties props) { - final String userFromUrl = ConnectionUrlParser.parseUserFromUrl(this.jdbcUrl, this.userPropertyName); + final String userFromUrl = + ConnectionUrlParser.parseUserFromUrl(this.jdbcUrl, this.userPropertyName); if (isNullOrEmpty(this.user) && !isNullOrEmpty(userFromUrl)) { props.setProperty(USER_PROPERTY_NAME, userFromUrl); this.user = userFromUrl; } - final String passwordFromUrl = ConnectionUrlParser.parsePasswordFromUrl(this.jdbcUrl, this.passwordPropertyName); + final String passwordFromUrl = + ConnectionUrlParser.parsePasswordFromUrl(this.jdbcUrl, this.passwordPropertyName); if (isNullOrEmpty(this.password) && !isNullOrEmpty(passwordFromUrl)) { props.setProperty(PASSWORD_PROPERTY_NAME, passwordFromUrl); this.password = passwordFromUrl; @@ -352,11 +356,13 @@ private void setCredentialPropertiesFromUrl(Properties props) { private void setJdbcUrlOrUrlProperty(Properties props) { // If the jdbc url wasn't set, use the url property if it exists. if (isNullOrEmpty(this.jdbcUrl) - && (!isNullOrEmpty(this.urlPropertyName) && !isNullOrEmpty(props.getProperty(this.urlPropertyName)))) { + && (!isNullOrEmpty(this.urlPropertyName) + && !isNullOrEmpty(props.getProperty(this.urlPropertyName)))) { this.jdbcUrl = props.getProperty(this.urlPropertyName); // If the jdbc url and the url property have both been set, use the provided jdbc url. - } else if ((!isNullOrEmpty(this.urlPropertyName) && !isNullOrEmpty(props.getProperty(this.urlPropertyName)))) { + } else if ((!isNullOrEmpty(this.urlPropertyName) + && !isNullOrEmpty(props.getProperty(this.urlPropertyName)))) { props.setProperty(this.urlPropertyName, this.jdbcUrl); } } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProvider.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProvider.java index a1d47e1ea..bfff592b0 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProvider.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProvider.java @@ -111,9 +111,11 @@ public AuroraHostListProvider( this.originalUrl = originalUrl; this.clusterId = UUID.randomUUID().toString(); this.refreshRateInMilliseconds = CLUSTER_TOPOLOGY_REFRESH_RATE_MS.getInteger(properties); - this.clusterInstanceTemplate = PropertyDefinition.CLUSTER_INSTANCE_HOST_PATTERN.get(this.properties) == null - ? new HostSpec(rdsHelper.getRdsInstanceHostPattern(originalUrl)) - : new HostSpec(PropertyDefinition.CLUSTER_INSTANCE_HOST_PATTERN.getString(this.properties)); + this.clusterInstanceTemplate = + PropertyDefinition.CLUSTER_INSTANCE_HOST_PATTERN.get(this.properties) == null + ? new HostSpec(rdsHelper.getRdsInstanceHostPattern(originalUrl)) + : new HostSpec( + PropertyDefinition.CLUSTER_INSTANCE_HOST_PATTERN.getString(this.properties)); validateHostPatternSetting(this.clusterInstanceTemplate.getHost()); this.rdsUrlType = rdsHelper.identifyRdsType(originalUrl); @@ -154,7 +156,8 @@ public AuroraHostListProvider( * @return a list of hosts that describes cluster topology. A writer is always at position 0. * Returns an empty list if isn't available or is invalid (doesn't contain a writer). */ - public List getTopology(final Connection conn, final boolean forceUpdate) throws SQLException { + public List getTopology(final Connection conn, final boolean forceUpdate) + throws SQLException { final HostSpec hostSpec = this.pluginService.getCurrentHostSpec(); if (rdsUrlType.isRdsCluster()) { @@ -272,9 +275,10 @@ private HostSpec createHost(final ResultSet resultSet, final boolean isWriter) String hostName = resultSet.getString(FIELD_SERVER_ID); hostName = hostName == null ? "?" : hostName; final String endpoint = getHostEndpoint(hostName); - final int port = this.clusterInstanceTemplate.isPortSpecified() - ? this.clusterInstanceTemplate.getPort() - : this.pluginService.getCurrentHostSpec().getPort(); + final int port = + this.clusterInstanceTemplate.isPortSpecified() + ? this.clusterInstanceTemplate.getPort() + : this.pluginService.getCurrentHostSpec().getPort(); final HostSpec hostSpec = new HostSpec(endpoint, port, isWriter ? HostRole.WRITER : HostRole.READER); @@ -420,7 +424,8 @@ public HostSpec getHostByName(Connection conn) { instanceName = resultSet.getString(instanceNameCol); } ClusterTopologyInfo clusterTopologyInfo = topologyCache.get(this.clusterId); - return instanceNameToHost(instanceName, clusterTopologyInfo == null ? null : clusterTopologyInfo.hosts); + return instanceNameToHost( + instanceName, clusterTopologyInfo == null ? null : clusterTopologyInfo.hosts); } catch (SQLException e) { return null; } @@ -439,18 +444,14 @@ private HostSpec instanceNameToHost(String name, List hosts) { return null; } - /** - * Clear topology cache for all clusters. - */ + /** Clear topology cache for all clusters. */ public void clearAll() { synchronized (cacheLock) { topologyCache.clear(); } } - /** - * Clear topology cache for the current cluster. - */ + /** Clear topology cache for the current cluster. */ public void clear() { synchronized (cacheLock) { topologyCache.remove(this.clusterId); @@ -461,14 +462,15 @@ public void clear() { public List refresh() throws SQLException { Connection currentConnection = this.pluginService.getCurrentConnection(); if (currentConnection == null) { - currentConnection = this.pluginService.connect(this.pluginService.getCurrentHostSpec(), this.properties); - this.pluginService.setCurrentConnection(currentConnection, this.pluginService.getCurrentHostSpec()); + currentConnection = + this.pluginService.connect(this.pluginService.getCurrentHostSpec(), this.properties); + this.pluginService.setCurrentConnection( + currentConnection, this.pluginService.getCurrentHostSpec()); } final ClusterTopologyInfo clusterTopologyInfo = topologyCache.get(this.clusterId); hostList = getTopology( - currentConnection, - clusterTopologyInfo != null && refreshNeeded(clusterTopologyInfo)); + currentConnection, clusterTopologyInfo != null && refreshNeeded(clusterTopologyInfo)); for (HostSpec hostSpec : hostList) { this.pluginService.setAvailability(hostSpec.getAliases(), hostSpec.getAvailability()); } @@ -479,8 +481,10 @@ public List refresh() throws SQLException { public List forceRefresh() throws SQLException { Connection currentConnection = this.pluginService.getCurrentConnection(); if (currentConnection == null) { - currentConnection = this.pluginService.connect(this.pluginService.getCurrentHostSpec(), this.properties); - this.pluginService.setCurrentConnection(currentConnection, this.pluginService.getCurrentHostSpec()); + currentConnection = + this.pluginService.connect(this.pluginService.getCurrentHostSpec(), this.properties); + this.pluginService.setCurrentConnection( + currentConnection, this.pluginService.getCurrentHostSpec()); } hostList = getTopology(currentConnection, true); for (HostSpec hostSpec : hostList) { @@ -506,7 +510,8 @@ private void validateHostPatternSetting(String hostPattern) { final RdsUrlType rdsUrlType = this.rdsHelper.identifyRdsType(hostPattern); if (rdsUrlType == RdsUrlType.RDS_PROXY) { // "An RDS Proxy url can't be used as the 'clusterInstanceHostPattern' configuration setting." - final String message = Messages.get("AuroraHostListProvider.clusterInstanceHostPatternNotSupportedForRDSProxy"); + final String message = + Messages.get("AuroraHostListProvider.clusterInstanceHostPatternNotSupportedForRDSProxy"); LOGGER.severe(message); throw new RuntimeException(message); } @@ -521,9 +526,7 @@ private void validateHostPatternSetting(String hostPattern) { } } - /** - * Class that holds the topology and additional information about the topology. - */ + /** Class that holds the topology and additional information about the topology. */ static class ClusterTopologyInfo { public Set downHosts; diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/DynamicHostListProvider.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/DynamicHostListProvider.java index 8b3f937fe..124c03c7c 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/DynamicHostListProvider.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/hostlistprovider/DynamicHostListProvider.java @@ -18,7 +18,9 @@ package com.amazon.awslabs.jdbc.hostlistprovider; -// A marker interface for providers that can fetch a host list, and it changes depending on database status -// A good example of such provider would be DB cluster provider (Aurora DB clusters, patroni DB clusters, etc.) +// A marker interface for providers that can fetch a host list, and it changes depending on database +// status +// A good example of such provider would be DB cluster provider (Aurora DB clusters, patroni DB +// clusters, etc.) // where cluster topology (nodes, their roles, their statuses) changes over time. -public interface DynamicHostListProvider { } +public interface DynamicHostListProvider {} diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/AuroraHostListConnectionPlugin.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/AuroraHostListConnectionPlugin.java index e9296d6ba..39b6462cd 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/AuroraHostListConnectionPlugin.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/AuroraHostListConnectionPlugin.java @@ -32,8 +32,8 @@ public class AuroraHostListConnectionPlugin extends AbstractConnectionPlugin { - private static final Set subscribedMethods = Collections.unmodifiableSet(new HashSet<>( - Collections.singletonList("initHostProvider"))); + private static final Set subscribedMethods = + Collections.unmodifiableSet(new HashSet<>(Collections.singletonList("initHostProvider"))); private final PluginService pluginService; public AuroraHostListConnectionPlugin(PluginService pluginService, Properties properties) { @@ -51,7 +51,8 @@ public void initHostProvider( String initialUrl, Properties props, HostListProviderService hostListProviderService, - JdbcCallable initHostProviderFunc) throws SQLException { + JdbcCallable initHostProviderFunc) + throws SQLException { final HostListProvider provider = hostListProviderService.getHostListProvider(); if (provider == null) { initHostProviderFunc.call(); @@ -62,7 +63,8 @@ public void initHostProvider( hostListProviderService.setHostListProvider( new AuroraHostListProvider(driverProtocol, pluginService, props, initialUrl)); } else if (!(provider instanceof AuroraHostListProvider)) { - throw new SQLException(Messages.get("Failover.invalidHostListProvider", new Object[] {provider})); + throw new SQLException( + Messages.get("Failover.invalidHostListProvider", new Object[] {provider})); } initHostProviderFunc.call(); } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DataCacheConnectionPlugin.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DataCacheConnectionPlugin.java index 2d5222629..ff2bab0a0 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DataCacheConnectionPlugin.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DataCacheConnectionPlugin.java @@ -57,14 +57,22 @@ public class DataCacheConnectionPlugin extends AbstractConnectionPlugin { private static final Logger LOGGER = Logger.getLogger(DataCacheConnectionPlugin.class.getName()); - private static final Set subscribedMethods = Collections.unmodifiableSet(new HashSet<>( - Arrays.asList("Statement.executeQuery", "Statement.execute", - "PreparedStatement.execute", "PreparedStatement.executeQuery", - "CallableStatement.execute", "CallableStatement.executeQuery"))); - - protected static final ProxyDriverProperty DATA_CACHE_TRIGGER_CONDITION = new ProxyDriverProperty( - "dataCacheTriggerCondition", "false", - "A regular expression that, if it's matched, allows the plugin to cache SQL results."); + private static final Set subscribedMethods = + Collections.unmodifiableSet( + new HashSet<>( + Arrays.asList( + "Statement.executeQuery", + "Statement.execute", + "PreparedStatement.execute", + "PreparedStatement.executeQuery", + "CallableStatement.execute", + "CallableStatement.executeQuery"))); + + protected static final ProxyDriverProperty DATA_CACHE_TRIGGER_CONDITION = + new ProxyDriverProperty( + "dataCacheTriggerCondition", + "false", + "A regular expression that, if it's matched, allows the plugin to cache SQL results."); protected static final Map dataCache = new ConcurrentHashMap<>(); @@ -84,10 +92,17 @@ public Set getSubscribedMethods() { } @Override - public T execute(Class resultClass, Class exceptionClass, Object methodInvokeOn, - String methodName, JdbcCallable jdbcMethodFunc, Object[] jdbcMethodArgs) throws E { - - if (StringUtils.isNullOrEmpty(this.dataCacheTriggerCondition) || resultClass != ResultSet.class) { + public T execute( + Class resultClass, + Class exceptionClass, + Object methodInvokeOn, + String methodName, + JdbcCallable jdbcMethodFunc, + Object[] jdbcMethodArgs) + throws E { + + if (StringUtils.isNullOrEmpty(this.dataCacheTriggerCondition) + || resultClass != ResultSet.class) { return jdbcMethodFunc.call(); } @@ -99,7 +114,10 @@ public T execute(Class resultClass, Class excepti result = dataCache.get(sql); if (result == null) { needToCache = true; - LOGGER.log(Level.FINEST, "[{0}] Query results will be cached: {1}", new Object[]{methodName, sql}); + LOGGER.log( + Level.FINEST, + "[{0}] Query results will be cached: {1}", + new Object[] {methodName, sql}); } else { try { result.beforeFirst(); @@ -713,17 +731,20 @@ public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException } @Override - public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException { + public void updateAsciiStream(String columnLabel, InputStream x, int length) + throws SQLException { throw new UnsupportedOperationException(); } @Override - public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException { + public void updateBinaryStream(String columnLabel, InputStream x, int length) + throws SQLException { throw new UnsupportedOperationException(); } @Override - public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { + public void updateCharacterStream(String columnLabel, Reader reader, int length) + throws SQLException { throw new UnsupportedOperationException(); } @@ -1018,7 +1039,8 @@ public void updateNCharacterStream(int columnIndex, Reader x, long length) throw } @Override - public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { + public void updateNCharacterStream(String columnLabel, Reader reader, long length) + throws SQLException { throw new UnsupportedOperationException(); } @@ -1028,7 +1050,8 @@ public void updateAsciiStream(int columnIndex, InputStream x, long length) throw } @Override - public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { + public void updateBinaryStream(int columnIndex, InputStream x, long length) + throws SQLException { throw new UnsupportedOperationException(); } @@ -1038,27 +1061,32 @@ public void updateCharacterStream(int columnIndex, Reader x, long length) throws } @Override - public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { + public void updateAsciiStream(String columnLabel, InputStream x, long length) + throws SQLException { throw new UnsupportedOperationException(); } @Override - public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { + public void updateBinaryStream(String columnLabel, InputStream x, long length) + throws SQLException { throw new UnsupportedOperationException(); } @Override - public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { + public void updateCharacterStream(String columnLabel, Reader reader, long length) + throws SQLException { throw new UnsupportedOperationException(); } @Override - public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { + public void updateBlob(int columnIndex, InputStream inputStream, long length) + throws SQLException { throw new UnsupportedOperationException(); } @Override - public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { + public void updateBlob(String columnLabel, InputStream inputStream, long length) + throws SQLException { throw new UnsupportedOperationException(); } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPlugin.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPlugin.java index 9d25394a7..53d223930 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPlugin.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPlugin.java @@ -49,9 +49,9 @@ */ public final class DefaultConnectionPlugin implements ConnectionPlugin { - private static final Logger LOGGER = - Logger.getLogger(DefaultConnectionPlugin.class.getName()); - private static final Set subscribedMethods = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("*"))); + private static final Logger LOGGER = Logger.getLogger(DefaultConnectionPlugin.class.getName()); + private static final Set subscribedMethods = + Collections.unmodifiableSet(new HashSet<>(Arrays.asList("*"))); private final ConnectionProvider connectionProvider; private final PluginService pluginService; @@ -157,7 +157,8 @@ public void notifyNodeListChanged(Map> change public boolean doesOpenTransaction(String statement) { statement = statement.toUpperCase(); - statement = statement.replaceAll("START(?:\\s*/\\*(.*?)\\*/\\s*)TRANSACTION", "START TRANSACTION"); + statement = + statement.replaceAll("START(?:\\s*/\\*(.*?)\\*/\\s*)TRANSACTION", "START TRANSACTION"); return statement.startsWith("BEGIN") || statement.startsWith("START TRANSACTION"); } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPlugin.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPlugin.java index 06770c811..91eee5b51 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPlugin.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPlugin.java @@ -49,17 +49,16 @@ public class IamAuthConnectionPlugin extends AbstractConnectionPlugin { public static final int PG_PORT = 5342; public static final int MYSQL_PORT = 3306; - protected static final ProxyDriverProperty SPECIFIED_PORT = new ProxyDriverProperty( - "iamDefaultPort", null, - "Overrides default port that is used to generate IAM token"); + protected static final ProxyDriverProperty SPECIFIED_PORT = + new ProxyDriverProperty( + "iamDefaultPort", null, "Overrides default port that is used to generate IAM token"); - protected static final ProxyDriverProperty SPECIFIED_REGION = new ProxyDriverProperty( - "iamRegion", null, - "Overrides AWS region that is used to generate IAM token"); + protected static final ProxyDriverProperty SPECIFIED_REGION = + new ProxyDriverProperty( + "iamRegion", null, "Overrides AWS region that is used to generate IAM token"); - protected static final ProxyDriverProperty SPECIFIED_EXPIRATION = new ProxyDriverProperty( - "iamExpiration", null, - "IAM token cache expiration in seconds"); + protected static final ProxyDriverProperty SPECIFIED_EXPIRATION = + new ProxyDriverProperty("iamExpiration", null, "IAM token cache expiration in seconds"); @Override public Set getSubscribedMethods() { @@ -68,19 +67,20 @@ public Set getSubscribedMethods() { @Override public Connection connect( - final String driverProtocol, - final HostSpec hostSpec, - final Properties props, - final boolean isInitialConnection, - final JdbcCallable connectFunc) - throws SQLException { + final String driverProtocol, + final HostSpec hostSpec, + final Properties props, + final boolean isInitialConnection, + final JdbcCallable connectFunc) + throws SQLException { final String host = hostSpec.getHost(); int port = hostSpec.getPort(); if (!hostSpec.isPortSpecified()) { if (StringUtils.isNullOrEmpty(SPECIFIED_PORT.get(props))) { - if (!driverProtocol.startsWith("jdbc:postgresql:") && !driverProtocol.startsWith("jdbc:mysql:")) { + if (!driverProtocol.startsWith("jdbc:postgresql:") + && !driverProtocol.startsWith("jdbc:mysql:")) { throw new RuntimeException("Port is required"); } else if (driverProtocol.startsWith("jdbc:mysql:")) { port = MYSQL_PORT; @@ -90,8 +90,11 @@ public Connection connect( } else { port = SPECIFIED_PORT.getInteger(props); if (port <= 0) { - throw new IllegalArgumentException("Port number: " + port + " is not valid. " - + "Port number should be greater than zero."); + throw new IllegalArgumentException( + "Port number: " + + port + + " is not valid. " + + "Port number should be greater than zero."); } } } @@ -110,50 +113,43 @@ public Connection connect( tokenExpirationSec = SPECIFIED_EXPIRATION.getInteger(props); } - final String cacheKey = getCacheKey( - props.getProperty(ConnectionPropertyNames.USER_PROPERTY_NAME), - host, - port, - region); + final String cacheKey = + getCacheKey( + props.getProperty(ConnectionPropertyNames.USER_PROPERTY_NAME), host, port, region); final TokenInfo tokenInfo = tokenCache.get(cacheKey); if (tokenInfo != null && !tokenInfo.isExpired()) { LOGGER.log(Level.FINEST, "use cached IAM token = " + tokenInfo.getToken()); props.setProperty(ConnectionPropertyNames.PASSWORD_PROPERTY_NAME, tokenInfo.getToken()); } else { - final String token = generateAuthenticationToken(props.getProperty(ConnectionPropertyNames.USER_PROPERTY_NAME), - hostSpec.getHost(), port, region); + final String token = + generateAuthenticationToken( + props.getProperty(ConnectionPropertyNames.USER_PROPERTY_NAME), + hostSpec.getHost(), + port, + region); LOGGER.log(Level.FINEST, "generated new IAM token = " + token); props.setProperty(ConnectionPropertyNames.PASSWORD_PROPERTY_NAME, token); tokenCache.put( - cacheKey, - new TokenInfo(token, Instant.now().plus(tokenExpirationSec, ChronoUnit.SECONDS))); + cacheKey, + new TokenInfo(token, Instant.now().plus(tokenExpirationSec, ChronoUnit.SECONDS))); } return connectFunc.call(); } String generateAuthenticationToken( - final String user, - final String hostname, - final int port, - final Region region) { - final RdsUtilities utilities = RdsUtilities.builder() + final String user, final String hostname, final int port, final Region region) { + final RdsUtilities utilities = + RdsUtilities.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(region) .build(); - return utilities.generateAuthenticationToken((builder) -> - builder - .hostname(hostname) - .port(port) - .username(user) - ); + return utilities.generateAuthenticationToken( + (builder) -> builder.hostname(hostname).port(port).username(user)); } private String getCacheKey( - final String user, - final String hostname, - final int port, - final Region region) { + final String user, final String hostname, final int port, final Region region) { return String.format("%s:%s:%d:%s", region, hostname, port, user); } @@ -165,33 +161,36 @@ static void clearCache() { private Region getRdsRegion(final String hostname) throws SQLException { // Check Hostname final Pattern auroraDnsPattern = - Pattern.compile( - "(.+)\\.(proxy-|cluster-|cluster-ro-|cluster-custom-)?[a-zA-Z0-9]+" - + "\\.([a-zA-Z0-9\\-]+)\\.rds\\.amazonaws\\.com", - Pattern.CASE_INSENSITIVE); + Pattern.compile( + "(.+)\\.(proxy-|cluster-|cluster-ro-|cluster-custom-)?[a-zA-Z0-9]+" + + "\\.([a-zA-Z0-9\\-]+)\\.rds\\.amazonaws\\.com", + Pattern.CASE_INSENSITIVE); final Matcher matcher = auroraDnsPattern.matcher(hostname); if (!matcher.find()) { // Does not match Amazon's Hostname, throw exception - final String exceptionMessage = String.format("Unsupported AWS hostname '%s'. " - + "Amazon domain name in format *.AWS-Region.rds.amazonaws.com is expected", hostname); + final String exceptionMessage = + String.format( + "Unsupported AWS hostname '%s'. " + + "Amazon domain name in format *.AWS-Region.rds.amazonaws.com is expected", + hostname); LOGGER.log(Level.FINEST, exceptionMessage); - throw new SQLException( - (exceptionMessage)); + throw new SQLException((exceptionMessage)); } // Get Region final String rdsRegion = matcher.group(3); // Check Region - final Optional regionOptional = Region.regions().stream() - .filter(r -> r.id().equalsIgnoreCase(rdsRegion)) - .findFirst(); + final Optional regionOptional = + Region.regions().stream().filter(r -> r.id().equalsIgnoreCase(rdsRegion)).findFirst(); if (!regionOptional.isPresent()) { - final String exceptionMessage = String.format("Unsupported AWS region '%s'. " - + "For supported regions, please read " - + "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html\n", + final String exceptionMessage = + String.format( + "Unsupported AWS region '%s'. " + + "For supported regions, please read " + + "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html\n", rdsRegion); LOGGER.log(Level.FINEST, exceptionMessage); diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/efm/HostMonitoringConnectionPlugin.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/efm/HostMonitoringConnectionPlugin.java index 09caf6d59..49953a237 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/efm/HostMonitoringConnectionPlugin.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/efm/HostMonitoringConnectionPlugin.java @@ -143,7 +143,8 @@ public T execute( } final int failureDetectionTimeMillis = FAILURE_DETECTION_TIME.getInteger(this.properties); - final int failureDetectionIntervalMillis = FAILURE_DETECTION_INTERVAL.getInteger(this.properties); + final int failureDetectionIntervalMillis = + FAILURE_DETECTION_INTERVAL.getInteger(this.properties); final int failureDetectionCount = FAILURE_DETECTION_COUNT.getInteger(this.properties); initMonitorService(); diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandler.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandler.java index 55d40ae09..a5d7429a6 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandler.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandler.java @@ -59,8 +59,8 @@ public class ClusterAwareReaderFailoverHandler implements ReaderFailoverHandler Logger.getLogger(ClusterAwareReaderFailoverHandler.class.getName()); protected static final int DEFAULT_FAILOVER_TIMEOUT = 60000; // 60 sec protected static final int DEFAULT_READER_CONNECT_TIMEOUT = 30000; // 30 sec - public static final ReaderFailoverResult FAILED_READER_FAILOVER_RESULT = new ReaderFailoverResult(null, - FailoverConnectionPlugin.NO_CONNECTION_INDEX, false); + public static final ReaderFailoverResult FAILED_READER_FAILOVER_RESULT = + new ReaderFailoverResult(null, FailoverConnectionPlugin.NO_CONNECTION_INDEX, false); protected Properties initialConnectionProps; protected int maxFailoverTimeoutMs; protected int timeoutMs; @@ -144,30 +144,29 @@ public ReaderFailoverResult failover(List hosts, HostSpec currentHost) } private Future submitInternalFailoverTask( - List hosts, - HostSpec currentHost, - ExecutorService executor) { - Future future = executor.submit(() -> { - ReaderFailoverResult result; - while (true) { - result = failoverInternal(hosts, currentHost); - if (result != null && result.isConnected()) { - break; - } - - TimeUnit.SECONDS.sleep(1); - } - return result; - }); + List hosts, HostSpec currentHost, ExecutorService executor) { + Future future = + executor.submit( + () -> { + ReaderFailoverResult result; + while (true) { + result = failoverInternal(hosts, currentHost); + if (result != null && result.isConnected()) { + break; + } + + TimeUnit.SECONDS.sleep(1); + } + return result; + }); executor.shutdown(); return future; } private ReaderFailoverResult getInternalFailoverResult( - ExecutorService executor, - Future future) throws SQLException { - ReaderFailoverResult defaultResult = new ReaderFailoverResult( - null, FailoverConnectionPlugin.NO_CONNECTION_INDEX, false); + ExecutorService executor, Future future) throws SQLException { + ReaderFailoverResult defaultResult = + new ReaderFailoverResult(null, FailoverConnectionPlugin.NO_CONNECTION_INDEX, false); try { ReaderFailoverResult result = future.get(this.maxFailoverTimeoutMs, TimeUnit.MILLISECONDS); return result == null ? defaultResult : result; @@ -186,9 +185,7 @@ private ReaderFailoverResult getInternalFailoverResult( } } - protected ReaderFailoverResult failoverInternal( - List hosts, - HostSpec currentHost) + protected ReaderFailoverResult failoverInternal(List hosts, HostSpec currentHost) throws SQLException { this.hostListProvider.addToDownHostList(currentHost); Set downHosts = hostListProvider.getDownHosts(); @@ -200,18 +197,12 @@ public List getHostTuplesByPriority(List hosts, Set List hostGroup = new ArrayList<>(); addActiveReaders(hostGroup, hosts, downHosts); HostSpec writerHost = hosts.get(FailoverConnectionPlugin.WRITER_CONNECTION_INDEX); - hostGroup.add( - new HostTuple( - writerHost, - FailoverConnectionPlugin.WRITER_CONNECTION_INDEX)); + hostGroup.add(new HostTuple(writerHost, FailoverConnectionPlugin.WRITER_CONNECTION_INDEX)); addDownHosts(hostGroup, hosts, downHosts); return hostGroup; } - private void addActiveReaders( - List list, - List hosts, - Set downHosts) { + private void addActiveReaders(List list, List hosts, Set downHosts) { List activeReaders = new ArrayList<>(); for (int i = FailoverConnectionPlugin.WRITER_CONNECTION_INDEX + 1; i < hosts.size(); i++) { HostSpec host = hosts.get(i); @@ -223,10 +214,7 @@ private void addActiveReaders( list.addAll(activeReaders); } - private void addDownHosts( - List list, - List hosts, - Set downHosts) { + private void addDownHosts(List list, List hosts, Set downHosts) { List downHostList = new ArrayList<>(); for (int i = 0; i < hosts.size(); i++) { HostSpec host = hosts.get(i); @@ -246,10 +234,10 @@ private void addDownHosts( * @return {@link ReaderFailoverResult} The results of this process. */ @Override - public ReaderFailoverResult getReaderConnection(List hostList) - throws SQLException { + public ReaderFailoverResult getReaderConnection(List hostList) throws SQLException { if (Utils.isNullOrEmpty(hostList)) { - LOGGER.fine(Messages.get("ClusterAwareReaderFailover.6", new Object[] {"getReaderConnection"})); + LOGGER.fine( + Messages.get("ClusterAwareReaderFailover.6", new Object[] {"getReaderConnection"})); return FAILED_READER_FAILOVER_RESULT; } @@ -258,19 +246,14 @@ public ReaderFailoverResult getReaderConnection(List hostList) return getConnectionFromHostGroup(tuples); } - public List getReaderTuplesByPriority( - List hostList, - Set downHosts) { + public List getReaderTuplesByPriority(List hostList, Set downHosts) { List tuples = new ArrayList<>(); addActiveReaders(tuples, hostList, downHosts); addDownReaders(tuples, hostList, downHosts); return tuples; } - private void addDownReaders( - List list, - List hosts, - Set downHosts) { + private void addDownReaders(List list, List hosts, Set downHosts) { List downReaders = new ArrayList<>(); for (int i = FailoverConnectionPlugin.WRITER_CONNECTION_INDEX + 1; i < hosts.size(); i++) { HostSpec host = hosts.get(i); @@ -285,12 +268,14 @@ private void addDownReaders( private ReaderFailoverResult getConnectionFromHostGroup(List hostGroup) throws SQLException { ExecutorService executor = Executors.newFixedThreadPool(2); - CompletionService completionService = new ExecutorCompletionService<>(executor); + CompletionService completionService = + new ExecutorCompletionService<>(executor); try { for (int i = 0; i < hostGroup.size(); i += 2) { // submit connection attempt tasks in batches of 2 - ReaderFailoverResult result = getResultFromNextTaskBatch(hostGroup, executor, completionService, i); + ReaderFailoverResult result = + getResultFromNextTaskBatch(hostGroup, executor, completionService, i); if (result.isConnected() || result.getException() != null) { return result; } @@ -303,10 +288,7 @@ private ReaderFailoverResult getConnectionFromHostGroup(List hostGrou } } - return new ReaderFailoverResult( - null, - FailoverConnectionPlugin.NO_CONNECTION_INDEX, - false); + return new ReaderFailoverResult(null, FailoverConnectionPlugin.NO_CONNECTION_INDEX, false); } finally { executor.shutdownNow(); } @@ -316,7 +298,8 @@ private ReaderFailoverResult getResultFromNextTaskBatch( List hostGroup, ExecutorService executor, CompletionService completionService, - int i) throws SQLException { + int i) + throws SQLException { ReaderFailoverResult result; int numTasks = i + 1 < hostGroup.size() ? 2 : 1; completionService.submit(new ConnectionAttemptTask(hostGroup.get(i))); @@ -329,8 +312,7 @@ private ReaderFailoverResult getResultFromNextTaskBatch( executor.shutdownNow(); LOGGER.fine( Messages.get( - "ClusterAwareReaderFailoverHandler.2", - new Object[] {result.getConnectionIndex()})); + "ClusterAwareReaderFailoverHandler.2", new Object[] {result.getConnectionIndex()})); return result; } if (result.getException() != null) { @@ -338,10 +320,7 @@ private ReaderFailoverResult getResultFromNextTaskBatch( return result; } } - return new ReaderFailoverResult( - null, - FailoverConnectionPlugin.NO_CONNECTION_INDEX, - false); + return new ReaderFailoverResult(null, FailoverConnectionPlugin.NO_CONNECTION_INDEX, false); } private ReaderFailoverResult getNextResult(CompletionService service) @@ -358,10 +337,7 @@ private ReaderFailoverResult getNextResult(CompletionService currentTopology) - throws SQLException { + public WriterFailoverResult failover(List currentTopology) throws SQLException { if (Utils.isNullOrEmpty(currentTopology)) { LOGGER.severe(Messages.get("ClusterAwareWriterFailoverHandler.7")); return DEFAULT_RESULT; } ExecutorService executorService = Executors.newFixedThreadPool(2); - CompletionService completionService = new ExecutorCompletionService<>(executorService); + CompletionService completionService = + new ExecutorCompletionService<>(executorService); submitTasks(currentTopology, executorService, completionService); try { @@ -135,23 +129,22 @@ public WriterFailoverResult failover(List currentTopology) } private void submitTasks( - List currentTopology, ExecutorService executorService, + List currentTopology, + ExecutorService executorService, CompletionService completionService) { HostSpec writerHost = currentTopology.get(WRITER_CONNECTION_INDEX); this.hostListProvider.addToDownHostList(writerHost); completionService.submit(new ReconnectToWriterHandler(writerHost)); - completionService.submit(new WaitForNewWriterHandler( - currentTopology, - writerHost)); + completionService.submit(new WaitForNewWriterHandler(currentTopology, writerHost)); executorService.shutdown(); } private WriterFailoverResult getNextResult( - ExecutorService executorService, - CompletionService completionService) throws SQLException { + ExecutorService executorService, CompletionService completionService) + throws SQLException { try { - Future firstCompleted = completionService.poll( - this.maxFailoverTimeoutMs, TimeUnit.MILLISECONDS); + Future firstCompleted = + completionService.poll(this.maxFailoverTimeoutMs, TimeUnit.MILLISECONDS); if (firstCompleted == null) { // The task was unsuccessful and we have timed out return DEFAULT_RESULT; @@ -180,35 +173,26 @@ private void logTaskSuccess(WriterFailoverResult result) { List topology = result.getTopology(); if (Utils.isNullOrEmpty(topology)) { String taskName = result.getTaskName() == null ? "None" : result.getTaskName(); - LOGGER.severe(Messages.get( - "ClusterAwareWriterFailoverHandler.5", - new Object[] {taskName})); + LOGGER.severe(Messages.get("ClusterAwareWriterFailoverHandler.5", new Object[] {taskName})); return; } String newWriterHost = topology.get(WRITER_CONNECTION_INDEX).getUrl(); if (result.isNewHost()) { - LOGGER.fine(Messages.get( - "ClusterAwareWriterFailoverHandler.4", - new Object[] {newWriterHost})); + LOGGER.fine( + Messages.get("ClusterAwareWriterFailoverHandler.4", new Object[] {newWriterHost})); } else { - LOGGER.fine(Messages.get( - "ClusterAwareWriterFailoverHandler.2", - new Object[] {newWriterHost})); + LOGGER.fine( + Messages.get("ClusterAwareWriterFailoverHandler.2", new Object[] {newWriterHost})); } } private SQLException createInterruptedException(InterruptedException e) { // "Thread was interrupted" - return new SQLException( - Messages.get("ClusterAwareWriterFailoverHandler.1"), - "70100", - e); + return new SQLException(Messages.get("ClusterAwareWriterFailoverHandler.1"), "70100", e); } - /** - * Internal class responsible for re-connecting to the current writer (aka TaskA). - */ + /** Internal class responsible for re-connecting to the current writer (aka TaskA). */ private class ReconnectToWriterHandler implements Callable { private final HostSpec originalWriterHost; @@ -240,7 +224,8 @@ public WriterFailoverResult call() { } catch (SQLException exception) { // Propagate exceptions that are not caused by network errors. if (!SqlState.isConnectionError(exception)) { - LOGGER.finer(Messages.get("ClusterAwareWriterFailoverHandler.16", new Object[] {exception})); + LOGGER.finer( + Messages.get("ClusterAwareWriterFailoverHandler.16", new Object[] {exception})); return new WriterFailoverResult(false, false, null, null, "TaskA", exception); } } @@ -252,10 +237,12 @@ public WriterFailoverResult call() { success = isCurrentHostWriter(latestTopology); hostListProvider.removeFromDownHostList(this.originalWriterHost); - return new WriterFailoverResult(success, false, latestTopology, success ? conn : null, "TaskA"); + return new WriterFailoverResult( + success, false, latestTopology, success ? conn : null, "TaskA"); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); - return new WriterFailoverResult(success, false, latestTopology, success ? conn : null, "TaskA"); + return new WriterFailoverResult( + success, false, latestTopology, success ? conn : null, "TaskA"); } catch (Exception ex) { LOGGER.severe(ex.getMessage()); return new WriterFailoverResult(false, false, null, null, "TaskA"); @@ -295,9 +282,7 @@ private class WaitForNewWriterHandler implements Callable private HostSpec currentReaderHost; private Connection currentReaderConnection; - public WaitForNewWriterHandler( - List currentTopology, - HostSpec currentHost) { + public WaitForNewWriterHandler(List currentTopology, HostSpec currentHost) { this.currentTopology = currentTopology; this.originalWriterHost = currentHost; } @@ -315,18 +300,13 @@ public WriterFailoverResult call() { } } return new WriterFailoverResult( - true, - true, - this.currentTopology, - this.currentConnection, - "TaskB"); + true, true, this.currentTopology, this.currentConnection, "TaskB"); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); return new WriterFailoverResult(false, false, null, null, "TaskB"); } catch (Exception ex) { - LOGGER.severe(Messages.get( - "ClusterAwareWriterFailoverHandler.15", - new Object[] {ex.getMessage()})); + LOGGER.severe( + Messages.get("ClusterAwareWriterFailoverHandler.15", new Object[] {ex.getMessage()})); throw ex; } finally { performFinalCleanup(); @@ -336,15 +316,17 @@ public WriterFailoverResult call() { private void connectToReader() throws InterruptedException { while (true) { try { - ReaderFailoverResult connResult = readerFailoverHandler.getReaderConnection(this.currentTopology); + ReaderFailoverResult connResult = + readerFailoverHandler.getReaderConnection(this.currentTopology); if (isValidReaderConnection(connResult)) { this.currentReaderConnection = connResult.getConnection(); this.currentReaderHost = this.currentTopology.get(connResult.getConnectionIndex()); LOGGER.fine( Messages.get( "ClusterAwareWriterFailoverHandler.11", - new Object[] {connResult.getConnectionIndex(), - this.currentReaderHost.getUrl()})); + new Object[] { + connResult.getConnectionIndex(), this.currentReaderHost.getUrl() + })); break; } } catch (SQLException e) { @@ -409,8 +391,7 @@ private boolean connectToWriter(HostSpec writerCandidate) { try { LOGGER.fine( Messages.get( - "ClusterAwareWriterFailoverHandler.14", - new Object[] {writerCandidate.getUrl()})); + "ClusterAwareWriterFailoverHandler.14", new Object[] {writerCandidate.getUrl()})); if (isSame(writerCandidate, this.currentReaderHost)) { this.currentConnection = this.currentReaderConnection; @@ -427,9 +408,7 @@ private boolean connectToWriter(HostSpec writerCandidate) { } } - /** - * Close the reader connection if not done so already, and mark the relevant fields as null. - */ + /** Close the reader connection if not done so already, and mark the relevant fields as null. */ private void closeReaderConnection() { try { if (this.currentReaderConnection != null && !this.currentReaderConnection.isClosed()) { diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPlugin.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPlugin.java index 461cd0c30..955091388 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPlugin.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPlugin.java @@ -268,8 +268,10 @@ void initHostProvider( HostListProviderService hostListProviderService, JdbcCallable initHostProviderFunc, Supplier hostListProviderSupplier, - Function readerFailoverHandlerSupplier, - Function writerFailoverHandlerSupplier) + Function + readerFailoverHandlerSupplier, + Function + writerFailoverHandlerSupplier) throws SQLException { if (!this.enableFailoverSetting) { return; @@ -289,7 +291,8 @@ void initHostProvider( private AuroraHostListProvider getHostListProvider() throws SQLException { final HostListProvider provider = this.pluginService.getHostListProvider(); if (!(provider instanceof AuroraHostListProvider)) { - throw new SQLException(Messages.get("Failover.invalidHostListProvider", new Object[] {provider})); + throw new SQLException( + Messages.get("Failover.invalidHostListProvider", new Object[] {provider})); } return (AuroraHostListProvider) provider; @@ -321,10 +324,12 @@ public void notifyNodeListChanged(Map> change LOGGER.fine(Messages.get("Failover.invalidNode", new Object[] {currentHost})); } - private boolean isNodeStillValid(final String node, Map> changes) { + private boolean isNodeStillValid( + final String node, Map> changes) { if (changes.containsKey(node)) { EnumSet options = changes.get(node); - return !options.contains(NodeChangeOptions.NODE_DELETED) && !options.contains(NodeChangeOptions.WENT_DOWN); + return !options.contains(NodeChangeOptions.NODE_DELETED) + && !options.contains(NodeChangeOptions.WENT_DOWN); } return false; } @@ -345,7 +350,8 @@ public boolean isFailoverEnabled() { } private void initSettings() { - this.enableFailoverSetting = PropertyDefinition.ENABLE_CLUSTER_AWARE_FAILOVER.getBoolean(this.properties); + this.enableFailoverSetting = + PropertyDefinition.ENABLE_CLUSTER_AWARE_FAILOVER.getBoolean(this.properties); this.failoverTimeoutMsSetting = FAILOVER_TIMEOUT_MS.getInteger(this.properties); this.failoverClusterTopologyRefreshRateMsSetting = FAILOVER_CLUSTER_TOPOLOGY_REFRESH_RATE_MS.getInteger(this.properties); @@ -354,8 +360,9 @@ private void initSettings() { this.failoverReaderConnectTimeoutMsSetting = FAILOVER_READER_CONNECT_TIMEOUT_MS.getInteger(this.properties); - this.autoReconnectSetting = AUTO_RECONNECT.getBoolean(this.properties) - || AUTO_RECONNECT_FOR_POOLS.getBoolean(this.properties); + this.autoReconnectSetting = + AUTO_RECONNECT.getBoolean(this.properties) + || AUTO_RECONNECT_FOR_POOLS.getBoolean(this.properties); } private void invalidInvocationOnClosedConnection() throws SQLException { @@ -564,10 +571,8 @@ private void switchCurrentConnectionTo(int hostIndex, Connection connection) thr * @param readOnly The new read-only status. * @throws SQLException if an error occurs */ - protected void syncSessionState( - Connection source, - Connection target, - boolean readOnly) throws SQLException { + protected void syncSessionState(Connection source, Connection target, boolean readOnly) + throws SQLException { if (target != null) { target.setReadOnly(readOnly); } @@ -603,13 +608,12 @@ private Connection createConnectionForHostIndex(int hostIndex) throws SQLExcepti } private void dealWithOriginalException( - Throwable originalException, - Throwable wrapperException, - Class exceptionClass) throws E { + Throwable originalException, Throwable wrapperException, Class exceptionClass) throws E { Throwable exceptionToThrow = wrapperException; if (originalException != null) { LOGGER.finer( - String.format("%s:%s", Messages.get("Failover.failoverEnabled"), originalException.getMessage())); + String.format( + "%s:%s", Messages.get("Failover.failoverEnabled"), originalException.getMessage())); if (this.lastExceptionDealtWith != originalException && shouldExceptionTriggerConnectionSwitch(originalException)) { invalidateCurrentConnection(); @@ -646,8 +650,7 @@ protected Connection createConnectionForHost(HostSpec baseHostSpec) throws SQLEx } protected void dealWithIllegalStateException( - IllegalStateException e, - Class exceptionClass) throws E { + IllegalStateException e, Class exceptionClass) throws E { dealWithOriginalException(e.getCause(), e, exceptionClass); } @@ -672,7 +675,8 @@ protected synchronized void failover(final HostSpec failedHost) throws SQLExcept // restarting transaction." final String errorMessage = Messages.get("Failover.transactionResolutionUnknownError"); LOGGER.severe(errorMessage); - throw new SQLException(errorMessage, SqlState.CONNECTION_FAILURE_DURING_TRANSACTION.getState()); + throw new SQLException( + errorMessage, SqlState.CONNECTION_FAILURE_DURING_TRANSACTION.getState()); } else { // "The active SQL connection has changed due to a connection failure. Please re-configure // session state if required." @@ -690,7 +694,8 @@ protected void failoverReader(final HostSpec failedHostSpec) throws SQLException if (failedHostSpec != null && failedHostSpec.getAvailability() == HostAvailability.AVAILABLE) { failedHost = failedHostSpec; } - ReaderFailoverResult result = readerFailoverHandler.failover(this.pluginService.getHosts(), failedHost); + ReaderFailoverResult result = + readerFailoverHandler.failover(this.pluginService.getHosts(), failedHost); if (result != null) { final SQLException exception = result.getException(); @@ -718,7 +723,8 @@ protected void failoverReader(final HostSpec failedHostSpec) throws SQLException protected void failoverWriter() throws SQLException { LOGGER.fine(Messages.get("Failover.startWriterFailover")); final Set oldAliases = this.pluginService.getCurrentHostSpec().getAliases(); - WriterFailoverResult failoverResult = this.writerFailoverHandler.failover(this.pluginService.getHosts()); + WriterFailoverResult failoverResult = + this.writerFailoverHandler.failover(this.pluginService.getHosts()); if (failoverResult != null) { final SQLException exception = failoverResult.getException(); if (exception != null) { @@ -846,7 +852,8 @@ private boolean canDirectExecute(String methodName) { * @param exception The exception that occurred while invoking the given method * @return an exception indicating the failure that occurred while invoking the given method */ - private E wrapExceptionIfNeeded(Class exceptionClass, Throwable exception) { + private E wrapExceptionIfNeeded( + Class exceptionClass, Throwable exception) { if (exceptionClass.isAssignableFrom(exception.getClass())) { return exceptionClass.cast(exception); } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ReaderFailoverResult.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ReaderFailoverResult.java index 80999f3ed..183ab964d 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ReaderFailoverResult.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/ReaderFailoverResult.java @@ -21,10 +21,7 @@ import java.sql.Connection; import java.sql.SQLException; -/** - * This class holds results of Reader Failover Process. - */ - +/** This class holds results of Reader Failover Process. */ public class ReaderFailoverResult { private final Connection newConnection; @@ -32,9 +29,7 @@ public class ReaderFailoverResult { private final boolean isConnected; private final SQLException exception; - /** - * ReaderFailoverResult constructor. - */ + /** ReaderFailoverResult constructor. */ public ReaderFailoverResult( Connection newConnection, int newConnectionIndex, boolean isConnected) { this(newConnection, newConnectionIndex, isConnected, null); @@ -54,7 +49,8 @@ public ReaderFailoverResult( /** * Get new connection to a host. * - * @return {@link Connection} New connection to a host. Returns null if no connection is established. + * @return {@link Connection} New connection to a host. Returns null if no connection is + * established. */ public Connection getConnection() { return newConnection; @@ -63,7 +59,8 @@ public Connection getConnection() { /** * Get index of newly connected host. * - * @return Index of connected host in topology Returns -1 (NO_CONNECTION_INDEX) if no connection is established. + * @return Index of connected host in topology Returns -1 (NO_CONNECTION_INDEX) if no connection + * is established. */ public int getConnectionIndex() { return newConnectionIndex; diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/WriterFailoverResult.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/WriterFailoverResult.java index ad38a5555..79f82990d 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/WriterFailoverResult.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/plugin/failover/WriterFailoverResult.java @@ -23,9 +23,7 @@ import java.sql.SQLException; import java.util.List; -/** - * This class holds results of Writer Failover Process. - */ +/** This class holds results of Writer Failover Process. */ public class WriterFailoverResult { private final boolean isConnected; @@ -35,9 +33,7 @@ public class WriterFailoverResult { private final String taskName; private final SQLException exception; - /** - * WriterFailoverResult constructor. - */ + /** WriterFailoverResult constructor. */ public WriterFailoverResult( boolean isConnected, boolean isNewHost, diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlBuilder.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlBuilder.java index f9e95b239..a1520a6fe 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlBuilder.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlBuilder.java @@ -33,16 +33,19 @@ public class ConnectionUrlBuilder { // Builds a connection URL of the generic format: "protocol//[hosts][/database][?properties]" - public static String buildUrl(String jdbcProtocol, - HostSpec hostSpec, - String serverPropertyName, - String portPropertyName, - String databasePropertyName, - String userPropertyName, - String passwordPropertyName, - Properties props) throws SQLException { + public static String buildUrl( + String jdbcProtocol, + HostSpec hostSpec, + String serverPropertyName, + String portPropertyName, + String databasePropertyName, + String userPropertyName, + String passwordPropertyName, + Properties props) + throws SQLException { if (isNullOrEmpty(jdbcProtocol) - || ((isNullOrEmpty(serverPropertyName) || isNullOrEmpty(props.getProperty(serverPropertyName))) + || ((isNullOrEmpty(serverPropertyName) + || isNullOrEmpty(props.getProperty(serverPropertyName))) && hostSpec == null)) { throw new SQLException("Missing JDBC protocol and/or host name. Could not construct URL."); } @@ -89,7 +92,8 @@ public static String buildUrl(String jdbcProtocol, final String propertyValue = copy.getProperty(propertyName); if (propertyName.equals(USER_PROPERTY_NAME) && !isNullOrEmpty(userPropertyName)) { propertyName = userPropertyName; - } else if (propertyName.equals(PASSWORD_PROPERTY_NAME) && !isNullOrEmpty(passwordPropertyName)) { + } else if (propertyName.equals(PASSWORD_PROPERTY_NAME) + && !isNullOrEmpty(passwordPropertyName)) { propertyName = passwordPropertyName; } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParser.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParser.java index 6555c66dc..373e2813d 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParser.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParser.java @@ -32,7 +32,8 @@ public class ConnectionUrlParser { static final String HOST_PORT_SEPARATOR = ":"; static final Pattern CONNECTION_STRING_PATTERN = Pattern.compile( - "(?[\\w(\\-\\w)?\\+:%]+)\\s*" // Driver protocol. "word1:word2:..." or "word1-word2:word3:..." + "(?[\\w(\\-\\w)?\\+:%]+)\\s*" // Driver protocol. "word1:word2:..." or + // "word1-word2:word3:..." + "(?://(?[^/?#]*))?\\s*" // Optional list of host(s) starting with // and // follows by any char except "/", "?" or "#" + "(?:[/?#].*)?"); // Anything starting with either "/", "?" or "#" @@ -46,15 +47,15 @@ public List getHostsFromConnectionUrl(final String initialConnection) } final String hosts = matcher.group("hosts") == null ? null : matcher.group("hosts").trim(); if (hosts != null) { - Arrays - .stream(hosts.split(HOSTS_SEPARATOR)) - .forEach(hostString -> { - final HostSpec host = parseHostPortPair(hostString); - if (host.getHost().isEmpty()) { - return; - } - hostsList.add(host); - }); + Arrays.stream(hosts.split(HOSTS_SEPARATOR)) + .forEach( + hostString -> { + final HostSpec host = parseHostPortPair(hostString); + if (host.getHost().isEmpty()) { + return; + } + hostsList.add(host); + }); } return hostsList; diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/PropertyUtils.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/PropertyUtils.java index 9db97de85..acb596b9c 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/PropertyUtils.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/PropertyUtils.java @@ -78,7 +78,9 @@ public static void setPropertyOnTarget( if (writeMethod == null) { LOGGER.log( Level.FINEST, - String.format("Set method for property '%s' does not exist on target %s", propName, target.getClass())); + String.format( + "Set method for property '%s' does not exist on target %s", + propName, target.getClass())); return; } @@ -96,7 +98,9 @@ public static void setPropertyOnTarget( writeMethod.invoke(target, propValue); } } catch (Exception e) { - LOGGER.log(Level.WARNING, String.format("Failed to set property %s on target %s", propName, target.getClass())); + LOGGER.log( + Level.WARNING, + String.format("Failed to set property %s on target %s", propName, target.getClass())); } } diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/RdsUtils.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/RdsUtils.java index 755ffa714..500024866 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/RdsUtils.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/RdsUtils.java @@ -76,7 +76,6 @@ public boolean isRdsDns(String host) { public boolean isRdsProxyDns(String host) { if (StringUtils.isNullOrEmpty(host)) { return false; - } return AURORA_PROXY_DNS_PATTERN.matcher(host).find(); } @@ -134,7 +133,8 @@ public boolean isIPv4(final String ip) { } public boolean isIPv6(final String ip) { - return !StringUtils.isNullOrEmpty(ip) && IP_V6.matcher(ip).matches() || IP_V6_COMPRESSED.matcher(ip).matches(); + return !StringUtils.isNullOrEmpty(ip) && IP_V6.matcher(ip).matches() + || IP_V6_COMPRESSED.matcher(ip).matches(); } public boolean isDnsPatternValid(String pattern) { diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/StringUtils.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/StringUtils.java index ee2069157..ee2c3d8e0 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/StringUtils.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/util/StringUtils.java @@ -67,8 +67,8 @@ public static boolean isNullOrEmpty(@Nullable String s) { * Splits stringToSplit into a list, using the given delimiter. * * @param stringToSplit the string to split - * @param delimiter the string to split on - * @param trim should the split strings be whitespace trimmed? + * @param delimiter the string to split on + * @param trim should the split strings be whitespace trimmed? * @return the list of strings, split by delimiter * @throws IllegalArgumentException if an error occurs */ diff --git a/wrapper/src/main/java/com/amazon/awslabs/jdbc/wrapper/ConnectionWrapper.java b/wrapper/src/main/java/com/amazon/awslabs/jdbc/wrapper/ConnectionWrapper.java index 1b40dbe4d..eebb99f79 100644 --- a/wrapper/src/main/java/com/amazon/awslabs/jdbc/wrapper/ConnectionWrapper.java +++ b/wrapper/src/main/java/com/amazon/awslabs/jdbc/wrapper/ConnectionWrapper.java @@ -80,12 +80,14 @@ public ConnectionWrapper( this.targetDriverProtocol = getProtocol(url); ConnectionPluginManager pluginManager = new ConnectionPluginManager(connectionProvider); - PluginServiceImpl pluginService = new PluginServiceImpl(pluginManager, props, url, this.targetDriverProtocol); + PluginServiceImpl pluginService = + new PluginServiceImpl(pluginManager, props, url, this.targetDriverProtocol); init(props, pluginManager, pluginService, pluginService, pluginService); if (PropertyDefinition.LOG_UNCLOSED_CONNECTIONS.getBoolean(props)) { - this.openConnectionStacktrace = new Throwable("Unclosed connection was instantiated at this point:"); + this.openConnectionStacktrace = + new Throwable("Unclosed connection was instantiated at this point:"); } } @@ -102,7 +104,12 @@ public ConnectionWrapper( throw new IllegalArgumentException("url"); } - init(props, connectionPluginManager, pluginService, hostListProviderService, pluginManagerService); + init( + props, + connectionPluginManager, + pluginService, + hostListProviderService, + pluginManagerService); } protected void init( @@ -110,7 +117,8 @@ protected void init( ConnectionPluginManager connectionPluginManager, PluginService pluginService, HostListProviderService hostListProviderService, - PluginManagerService pluginManagerService) throws SQLException { + PluginManagerService pluginManagerService) + throws SQLException { this.pluginManager = connectionPluginManager; this.pluginService = pluginService; this.hostListProviderService = hostListProviderService; @@ -820,7 +828,10 @@ protected void finalize() throws Throwable { try { if (this.openConnectionStacktrace != null) { - LOGGER.log(Level.WARNING, "Finalizing a connection that was never closed.", this.openConnectionStacktrace); + LOGGER.log( + Level.WARNING, + "Finalizing a connection that was never closed.", + this.openConnectionStacktrace); this.openConnectionStacktrace = null; } diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/PluginServiceImplTests.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/PluginServiceImplTests.java index 66a31bf38..fe74151f0 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/PluginServiceImplTests.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/PluginServiceImplTests.java @@ -31,15 +31,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.amazon.awslabs.jdbc.ConnectionPlugin; -import com.amazon.awslabs.jdbc.ConnectionPluginManager; -import com.amazon.awslabs.jdbc.HostAvailability; -import com.amazon.awslabs.jdbc.HostListProvider; -import com.amazon.awslabs.jdbc.HostRole; -import com.amazon.awslabs.jdbc.HostSpec; -import com.amazon.awslabs.jdbc.NodeChangeOptions; -import com.amazon.awslabs.jdbc.OldConnectionSuggestedAction; -import com.amazon.awslabs.jdbc.PluginServiceImpl; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; @@ -164,7 +155,7 @@ public void testOldConnectionMixedSuggestion() throws SQLException { @Test public void testChangesNewConnectionNewHostNewPortNewRoleNewAvailability() throws SQLException { when(pluginManager.notifyConnectionChanged( - argumentChanges.capture(), argumentSkipPlugin.capture())) + argumentChanges.capture(), argumentSkipPlugin.capture())) .thenReturn(EnumSet.of(OldConnectionSuggestedAction.NO_OPINION)); PluginServiceImpl target = @@ -192,7 +183,7 @@ public void testChangesNewConnectionNewHostNewPortNewRoleNewAvailability() throw @Test public void testChangesNewConnectionNewRoleNewAvailability() throws SQLException { when(pluginManager.notifyConnectionChanged( - argumentChanges.capture(), argumentSkipPlugin.capture())) + argumentChanges.capture(), argumentSkipPlugin.capture())) .thenReturn(EnumSet.of(OldConnectionSuggestedAction.NO_OPINION)); PluginServiceImpl target = @@ -219,7 +210,7 @@ public void testChangesNewConnectionNewRoleNewAvailability() throws SQLException @Test public void testChangesNewConnection() throws SQLException { when(pluginManager.notifyConnectionChanged( - argumentChanges.capture(), argumentSkipPlugin.capture())) + argumentChanges.capture(), argumentSkipPlugin.capture())) .thenReturn(EnumSet.of(OldConnectionSuggestedAction.NO_OPINION)); PluginServiceImpl target = @@ -245,8 +236,8 @@ public void testChangesNewConnection() throws SQLException { @Test public void testChangesNoChanges() throws SQLException { - when(pluginManager.notifyConnectionChanged(any(), any())).thenReturn( - EnumSet.of(OldConnectionSuggestedAction.NO_OPINION)); + when(pluginManager.notifyConnectionChanged(any(), any())) + .thenReturn(EnumSet.of(OldConnectionSuggestedAction.NO_OPINION)); PluginServiceImpl target = spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); @@ -267,8 +258,8 @@ public void testSetNodeListAdded() throws SQLException { when(hostListProvider.refresh()).thenReturn(Collections.singletonList(new HostSpec("hostA"))); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); target.hosts = new ArrayList<>(); target.hostListProvider = hostListProvider; @@ -291,8 +282,8 @@ public void testSetNodeListDeleted() throws SQLException { when(hostListProvider.refresh()).thenReturn(Collections.singletonList(new HostSpec("hostB"))); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); target.hosts = Arrays.asList(new HostSpec("hostA"), new HostSpec("hostB")); target.hostListProvider = hostListProvider; @@ -313,12 +304,14 @@ public void testSetNodeListDeleted() throws SQLException { public void testSetNodeListChanged() throws SQLException { doNothing().when(pluginManager).notifyNodeListChanged(argumentChangesMap.capture()); - when(hostListProvider.refresh()).thenReturn( - Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER))); + when(hostListProvider.refresh()) + .thenReturn( + Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER))); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); - target.hosts = Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.WRITER)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + target.hosts = + Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.WRITER)); target.hostListProvider = hostListProvider; target.refreshHostList(); @@ -339,12 +332,14 @@ public void testSetNodeListChanged() throws SQLException { public void testSetNodeListNoChanges() throws SQLException { doNothing().when(pluginManager).notifyNodeListChanged(any()); - when(hostListProvider.refresh()).thenReturn( - Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER))); + when(hostListProvider.refresh()) + .thenReturn( + Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER))); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); - target.hosts = Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + target.hosts = + Collections.singletonList(new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER)); target.hostListProvider = hostListProvider; target.refreshHostList(); @@ -358,10 +353,11 @@ public void testSetNodeListNoChanges() throws SQLException { public void testNodeAvailabilityNotChanged() { doNothing().when(pluginManager).notifyNodeListChanged(argumentChangesMap.capture()); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); - target.hosts = Collections.singletonList( - new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.AVAILABLE)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + target.hosts = + Collections.singletonList( + new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.AVAILABLE)); Set aliases = new HashSet<>(); aliases.add("hostA"); @@ -376,10 +372,11 @@ public void testNodeAvailabilityNotChanged() { public void testNodeAvailabilityChanged_WentDown() { doNothing().when(pluginManager).notifyNodeListChanged(argumentChangesMap.capture()); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); - target.hosts = Collections.singletonList( - new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.AVAILABLE)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + target.hosts = + Collections.singletonList( + new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.AVAILABLE)); Set aliases = new HashSet<>(); aliases.add("hostA"); @@ -401,10 +398,12 @@ public void testNodeAvailabilityChanged_WentDown() { public void testNodeAvailabilityChanged_WentUp() { doNothing().when(pluginManager).notifyNodeListChanged(argumentChangesMap.capture()); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); - target.hosts = Collections.singletonList( - new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + target.hosts = + Collections.singletonList( + new HostSpec( + "hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE)); Set aliases = new HashSet<>(); aliases.add("hostA"); @@ -426,15 +425,17 @@ public void testNodeAvailabilityChanged_WentUp() { public void testNodeAvailabilityChanged_WentUp_ByAlias() { doNothing().when(pluginManager).notifyNodeListChanged(argumentChangesMap.capture()); - final HostSpec hostA = new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); + final HostSpec hostA = + new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); hostA.addAlias("ip-10-10-10-10"); hostA.addAlias("hostA.custom.domain.com"); - final HostSpec hostB = new HostSpec("hostB", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); + final HostSpec hostB = + new HostSpec("hostB", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); hostB.addAlias("ip-10-10-10-10"); hostB.addAlias("hostB.custom.domain.com"); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); target.hosts = Arrays.asList(hostA, hostB); @@ -458,15 +459,17 @@ public void testNodeAvailabilityChanged_WentUp_ByAlias() { public void testNodeAvailabilityChanged_WentUp_MultipleHostsByAlias() { doNothing().when(pluginManager).notifyNodeListChanged(argumentChangesMap.capture()); - final HostSpec hostA = new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); + final HostSpec hostA = + new HostSpec("hostA", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); hostA.addAlias("ip-10-10-10-10"); hostA.addAlias("hostA.custom.domain.com"); - final HostSpec hostB = new HostSpec("hostB", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); + final HostSpec hostB = + new HostSpec("hostB", HostSpec.NO_PORT, HostRole.READER, HostAvailability.NOT_AVAILABLE); hostB.addAlias("ip-10-10-10-10"); hostB.addAlias("hostB.custom.domain.com"); - PluginServiceImpl target = spy( - new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); + PluginServiceImpl target = + spy(new PluginServiceImpl(pluginManager, PROPERTIES, URL, DRIVER_PROTOCOL)); target.hosts = Arrays.asList(hostA, hostB); diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProviderTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProviderTest.java index b0b12687b..f7a6a44d6 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProviderTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/hostlistprovider/AuroraHostListProviderTest.java @@ -73,7 +73,8 @@ class AuroraHostListProviderTest { void setUp() throws SQLException { closeable = MockitoAnnotations.openMocks(this); when(mockPluginService.getCurrentConnection()).thenReturn(mockConnection); - when(mockPluginService.connect(any(HostSpec.class), any(Properties.class))).thenReturn(mockConnection); + when(mockPluginService.connect(any(HostSpec.class), any(Properties.class))) + .thenReturn(mockConnection); when(mockPluginService.getCurrentHostSpec()).thenReturn(currentHostSpec); when(mockConnection.createStatement()).thenReturn(mockStatement); when(mockStatement.executeQuery(queryCaptor.capture())).thenReturn(mockResultSet); @@ -87,11 +88,13 @@ void tearDown() throws Exception { @Test void testGetTopology_returnCachedTopology() throws SQLException { - auroraHostListProvider = Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); + auroraHostListProvider = + Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); final Instant lastUpdated = Instant.now(); final List expected = hosts; - final ClusterTopologyInfo info = new ClusterTopologyInfo(expected, new HashSet<>(), lastUpdated, false); + final ClusterTopologyInfo info = + new ClusterTopologyInfo(expected, new HashSet<>(), lastUpdated, false); AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, info); final List result = auroraHostListProvider.getTopology(mockConnection, false); @@ -102,14 +105,17 @@ void testGetTopology_returnCachedTopology() throws SQLException { @Test void testGetTopology_withForceUpdate_returnsUpdatedTopology() throws SQLException { - auroraHostListProvider = Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); + auroraHostListProvider = + Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); final Instant lastUpdated = Instant.now(); - final ClusterTopologyInfo oldTopology = new ClusterTopologyInfo(hosts, new HashSet<>(), lastUpdated, false); + final ClusterTopologyInfo oldTopology = + new ClusterTopologyInfo(hosts, new HashSet<>(), lastUpdated, false); AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, oldTopology); final List newHosts = Collections.singletonList(new HostSpec("newHost")); - final ClusterTopologyInfo newTopology = new ClusterTopologyInfo(newHosts, new HashSet<>(), lastUpdated, false); + final ClusterTopologyInfo newTopology = + new ClusterTopologyInfo(newHosts, new HashSet<>(), lastUpdated, false); doReturn(newTopology).when(auroraHostListProvider).queryForTopology(mockConnection); final List result = auroraHostListProvider.getTopology(mockConnection, true); @@ -120,16 +126,17 @@ void testGetTopology_withForceUpdate_returnsUpdatedTopology() throws SQLExceptio @Test void testGetTopology_withoutForceUpdate_returnsEmptyHostList() throws SQLException { - auroraHostListProvider = Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); + auroraHostListProvider = + Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); final Instant lastUpdated = Instant.now(); final List expected = hosts; - final ClusterTopologyInfo oldTopology = new ClusterTopologyInfo(expected, new HashSet<>(), - lastUpdated, false); + final ClusterTopologyInfo oldTopology = + new ClusterTopologyInfo(expected, new HashSet<>(), lastUpdated, false); AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, oldTopology); - final ClusterTopologyInfo newTopology = new ClusterTopologyInfo(new ArrayList<>(), new HashSet<>(), lastUpdated, - false); + final ClusterTopologyInfo newTopology = + new ClusterTopologyInfo(new ArrayList<>(), new HashSet<>(), lastUpdated, false); doReturn(newTopology).when(auroraHostListProvider).queryForTopology(mockConnection); final List result = auroraHostListProvider.getTopology(mockConnection, false); @@ -140,12 +147,13 @@ void testGetTopology_withoutForceUpdate_returnsEmptyHostList() throws SQLExcepti @Test void testGetTopology_withForceUpdate_returnsEmptyHostList() throws SQLException { - auroraHostListProvider = Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); + auroraHostListProvider = + Mockito.spy(new AuroraHostListProvider("", mockPluginService, new Properties(), "url")); auroraHostListProvider.clear(); final Instant lastUpdated = Instant.now(); - final ClusterTopologyInfo newTopology = new ClusterTopologyInfo(new ArrayList<>(), new HashSet<>(), lastUpdated, - false); + final ClusterTopologyInfo newTopology = + new ClusterTopologyInfo(new ArrayList<>(), new HashSet<>(), lastUpdated, false); doReturn(newTopology).when(auroraHostListProvider).queryForTopology(mockConnection); final List result = auroraHostListProvider.getTopology(mockConnection, true); @@ -157,13 +165,15 @@ void testGetTopology_withForceUpdate_returnsEmptyHostList() throws SQLException @Test void testQueryForTopology_withDifferentDriverProtocol() throws SQLException { final List expectedMySQL = Collections.singletonList(new HostSpec("mysql", 1234)); - final List expectedPostgres = Collections.singletonList(new HostSpec("postgresql", 1234)); + final List expectedPostgres = + Collections.singletonList(new HostSpec("postgresql", 1234)); when(mockResultSet.next()).thenReturn(true, false); - when(mockResultSet.getString(eq(AuroraHostListProvider.FIELD_SESSION_ID))).thenReturn( - AuroraHostListProvider.WRITER_SESSION_ID); + when(mockResultSet.getString(eq(AuroraHostListProvider.FIELD_SESSION_ID))) + .thenReturn(AuroraHostListProvider.WRITER_SESSION_ID); when(mockResultSet.getString(eq(AuroraHostListProvider.FIELD_SERVER_ID))).thenReturn("mysql"); - auroraHostListProvider = new AuroraHostListProvider("mysql", mockPluginService, new Properties(), "url"); + auroraHostListProvider = + new AuroraHostListProvider("mysql", mockPluginService, new Properties(), "url"); ClusterTopologyInfo result = auroraHostListProvider.queryForTopology(mockConnection); String query = queryCaptor.getValue(); @@ -171,8 +181,10 @@ void testQueryForTopology_withDifferentDriverProtocol() throws SQLException { assertEquals(AuroraHostListProvider.MYSQL_RETRIEVE_TOPOLOGY_SQL, query); when(mockResultSet.next()).thenReturn(true, false); - when(mockResultSet.getString(eq(AuroraHostListProvider.FIELD_SERVER_ID))).thenReturn("postgresql"); - auroraHostListProvider = new AuroraHostListProvider("postgresql", mockPluginService, new Properties(), "url"); + when(mockResultSet.getString(eq(AuroraHostListProvider.FIELD_SERVER_ID))) + .thenReturn("postgresql"); + auroraHostListProvider = + new AuroraHostListProvider("postgresql", mockPluginService, new Properties(), "url"); result = auroraHostListProvider.queryForTopology(mockConnection); query = queryCaptor.getValue(); assertEquals(expectedPostgres, result.hosts); @@ -181,21 +193,25 @@ void testQueryForTopology_withDifferentDriverProtocol() throws SQLException { @Test void testQueryForTopology_queryResultsInException() throws SQLException { - auroraHostListProvider = new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); + auroraHostListProvider = + new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); when(mockStatement.executeQuery(anyString())).thenThrow(new SQLSyntaxErrorException()); - assertDoesNotThrow(() -> { - ClusterTopologyInfo result = auroraHostListProvider.queryForTopology(mockConnection); - assertEquals(new ArrayList<>(), result.hosts); - }); + assertDoesNotThrow( + () -> { + ClusterTopologyInfo result = auroraHostListProvider.queryForTopology(mockConnection); + assertEquals(new ArrayList<>(), result.hosts); + }); } @Test void testGetCachedTopology_returnCachedTopology() { - auroraHostListProvider = new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); + auroraHostListProvider = + new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); final Instant lastUpdated = Instant.now(); final List expected = hosts; - final ClusterTopologyInfo info = new ClusterTopologyInfo(expected, new HashSet<>(), lastUpdated, false); + final ClusterTopologyInfo info = + new ClusterTopologyInfo(expected, new HashSet<>(), lastUpdated, false); AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, info); final List result = auroraHostListProvider.getCachedTopology(); @@ -204,14 +220,17 @@ void testGetCachedTopology_returnCachedTopology() { @Test void testGetCachedTopology_returnNull() { - auroraHostListProvider = new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); + auroraHostListProvider = + new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); // Test getCachedTopology with empty topology. assertNull(auroraHostListProvider.getCachedTopology()); auroraHostListProvider.clear(); - auroraHostListProvider = new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); + auroraHostListProvider = + new AuroraHostListProvider("", mockPluginService, new Properties(), "url"); final Instant lastUpdated = Instant.now().minus(1, ChronoUnit.DAYS); - final ClusterTopologyInfo info = new ClusterTopologyInfo(hosts, new HashSet<>(), lastUpdated, false); + final ClusterTopologyInfo info = + new ClusterTopologyInfo(hosts, new HashSet<>(), lastUpdated, false); AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, info); // Test getCachedTopology with expired cache. assertNull(auroraHostListProvider.getCachedTopology()); diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPluginTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPluginTest.java index c66d86d0e..a25510f26 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPluginTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/DefaultConnectionPluginTest.java @@ -86,8 +86,7 @@ private static Stream openTransactionQueries() { Arguments.of("START/* COMMENT */TRANSACTION;", true), Arguments.of("START /* COMMENT */ TRANSACTION;", true), Arguments.of("START /*COMMENT*/TRANSACTION;", true), - Arguments.of("commit", false) - ); + Arguments.of("commit", false)); } private static Stream closeTransactionQueries() { @@ -95,8 +94,7 @@ private static Stream closeTransactionQueries() { Arguments.of("rollback;", true), Arguments.of("commit;", true), Arguments.of("end", true), - Arguments.of("abort;", true) - ); + Arguments.of("abort;", true)); } private static Stream multiStatementQueries() { @@ -105,7 +103,6 @@ private static Stream multiStatementQueries() { Arguments.of(null, new ArrayList()), Arguments.of(" ", new ArrayList()), Arguments.of("some \t \r \n query;", Collections.singletonList("some query")), - Arguments.of("some\t\t\r\n query;query2", Arrays.asList("some query", "query2")) - ); + Arguments.of("some\t\t\r\n query;query2", Arrays.asList("some query", "query2"))); } } diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPluginTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPluginTest.java index 0b9858425..8368fbfde 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPluginTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/IamAuthConnectionPluginTest.java @@ -47,16 +47,24 @@ class IamAuthConnectionPluginTest { private static final String TEST_TOKEN = "testToken"; private static final int DEFAULT_PG_PORT = 5342; private static final int DEFAULT_MYSQL_PORT = 3306; - private static final String PG_CACHE_KEY = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" - + String.valueOf(DEFAULT_PG_PORT) + ":postgresqlUser"; - private static final String MYSQL_CACHE_KEY = "us-east-2:mysql.testdb.us-east-2.rds.amazonaws.com:" - + String.valueOf(DEFAULT_MYSQL_PORT) + ":mysqlUser"; + private static final String PG_CACHE_KEY = + "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + + String.valueOf(DEFAULT_PG_PORT) + + ":postgresqlUser"; + private static final String MYSQL_CACHE_KEY = + "us-east-2:mysql.testdb.us-east-2.rds.amazonaws.com:" + + String.valueOf(DEFAULT_MYSQL_PORT) + + ":mysqlUser"; private static final String PG_DRIVER_PROTOCOL = "jdbc:postgresql:"; private static final String MYSQL_DRIVER_PROTOCOL = "jdbc:mysql:"; - private static final HostSpec PG_HOST_SPEC = new HostSpec("pg.testdb.us-east-2.rds.amazonaws.com"); - private static final HostSpec PG_HOST_SPEC_WITH_PORT = new HostSpec("pg.testdb.us-east-2.rds.amazonaws.com", 1234); - private static final HostSpec PG_HOST_SPEC_WITH_REGION = new HostSpec("pg.testdb.us-west-1.rds.amazonaws.com"); - private static final HostSpec MYSQL_HOST_SPEC = new HostSpec("mysql.testdb.us-east-2.rds.amazonaws.com"); + private static final HostSpec PG_HOST_SPEC = + new HostSpec("pg.testdb.us-east-2.rds.amazonaws.com"); + private static final HostSpec PG_HOST_SPEC_WITH_PORT = + new HostSpec("pg.testdb.us-east-2.rds.amazonaws.com", 1234); + private static final HostSpec PG_HOST_SPEC_WITH_REGION = + new HostSpec("pg.testdb.us-west-1.rds.amazonaws.com"); + private static final HostSpec MYSQL_HOST_SPEC = + new HostSpec("mysql.testdb.us-east-2.rds.amazonaws.com"); private Properties props; @Mock JdbcCallable mockLambda; @@ -84,7 +92,8 @@ public static void registerDrivers() throws SQLException { @Test public void testPostgresConnectValidTokenInCache() throws SQLException { - IamAuthConnectionPlugin.tokenCache.put(PG_CACHE_KEY, + IamAuthConnectionPlugin.tokenCache.put( + PG_CACHE_KEY, new IamAuthConnectionPlugin.TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000))); testTokenSetInProps(PG_DRIVER_PROTOCOL, PG_HOST_SPEC); @@ -94,7 +103,8 @@ public void testPostgresConnectValidTokenInCache() throws SQLException { public void testMySqlConnectValidTokenInCache() throws SQLException { props.setProperty(ConnectionPropertyNames.USER_PROPERTY_NAME, "mysqlUser"); props.setProperty(ConnectionPropertyNames.PASSWORD_PROPERTY_NAME, "mysqlPassword"); - IamAuthConnectionPlugin.tokenCache.put(MYSQL_CACHE_KEY, + IamAuthConnectionPlugin.tokenCache.put( + MYSQL_CACHE_KEY, new IamAuthConnectionPlugin.TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000))); testTokenSetInProps(MYSQL_DRIVER_PROTOCOL, MYSQL_HOST_SPEC); @@ -105,16 +115,22 @@ public void testPostgresConnectWithInvalidPort() { props.setProperty("iamDefaultPort", "0"); final IamAuthConnectionPlugin targetPlugin = new IamAuthConnectionPlugin(); - final IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { - targetPlugin.connect(PG_DRIVER_PROTOCOL, PG_HOST_SPEC, props, true, mockLambda); - }); + final IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + targetPlugin.connect(PG_DRIVER_PROTOCOL, PG_HOST_SPEC, props, true, mockLambda); + }); - assertEquals("Port number: 0 is not valid. Port number should be greater than zero.", exception.getMessage()); + assertEquals( + "Port number: 0 is not valid. Port number should be greater than zero.", + exception.getMessage()); } @Test public void testConnectExpiredTokenInCache() throws SQLException { - IamAuthConnectionPlugin.tokenCache.put(PG_CACHE_KEY, + IamAuthConnectionPlugin.tokenCache.put( + PG_CACHE_KEY, new IamAuthConnectionPlugin.TokenInfo(TEST_TOKEN, Instant.now().minusMillis(300000))); testGenerateToken(PG_DRIVER_PROTOCOL, PG_HOST_SPEC); @@ -127,8 +143,10 @@ public void testConnectEmptyCache() throws SQLException { @Test public void testConnectWithSpecifiedPort() throws SQLException { - final String cacheKeyWithNewPort = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:1234:" + "postgresqlUser"; - IamAuthConnectionPlugin.tokenCache.put(cacheKeyWithNewPort, + final String cacheKeyWithNewPort = + "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:1234:" + "postgresqlUser"; + IamAuthConnectionPlugin.tokenCache.put( + cacheKeyWithNewPort, new IamAuthConnectionPlugin.TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000))); testTokenSetInProps(PG_DRIVER_PROTOCOL, PG_HOST_SPEC_WITH_PORT); @@ -137,32 +155,41 @@ public void testConnectWithSpecifiedPort() throws SQLException { @Test public void testConnectWithSpecifiedRegion() throws SQLException { final String cacheKeyWithNewRegion = - "us-west-1:pg.testdb.us-west-1.rds.amazonaws.com:" + String.valueOf(DEFAULT_PG_PORT) + ":" + "postgresqlUser"; + "us-west-1:pg.testdb.us-west-1.rds.amazonaws.com:" + + String.valueOf(DEFAULT_PG_PORT) + + ":" + + "postgresqlUser"; props.setProperty("iamRegion", "us-west-1"); - IamAuthConnectionPlugin.tokenCache.put(cacheKeyWithNewRegion, + IamAuthConnectionPlugin.tokenCache.put( + cacheKeyWithNewRegion, new IamAuthConnectionPlugin.TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000))); testTokenSetInProps(PG_DRIVER_PROTOCOL, PG_HOST_SPEC_WITH_REGION); } - public void testTokenSetInProps(final String protocol, final HostSpec hostSpec) throws SQLException { + public void testTokenSetInProps(final String protocol, final HostSpec hostSpec) + throws SQLException { IamAuthConnectionPlugin targetPlugin = new IamAuthConnectionPlugin(); doThrow(new SQLException()).when(mockLambda).call(); - assertThrows(SQLException.class, () -> { - targetPlugin.connect(protocol, hostSpec, props, true, mockLambda); - }); + assertThrows( + SQLException.class, + () -> { + targetPlugin.connect(protocol, hostSpec, props, true, mockLambda); + }); verify(mockLambda, times(1)).call(); assertEquals(TEST_TOKEN, props.getProperty(ConnectionPropertyNames.PASSWORD_PROPERTY_NAME)); } - private void testGenerateToken(final String protocol, final HostSpec hostSpec) throws SQLException { + private void testGenerateToken(final String protocol, final HostSpec hostSpec) + throws SQLException { final IamAuthConnectionPlugin targetPlugin = new IamAuthConnectionPlugin(); final IamAuthConnectionPlugin spyPlugin = Mockito.spy(targetPlugin); - doReturn(GENERATED_TOKEN).when(spyPlugin) + doReturn(GENERATED_TOKEN) + .when(spyPlugin) .generateAuthenticationToken( props.getProperty(ConnectionPropertyNames.USER_PROPERTY_NAME), hostSpec.getHost(), @@ -170,12 +197,15 @@ private void testGenerateToken(final String protocol, final HostSpec hostSpec) t Region.US_EAST_2); doThrow(new SQLException()).when(mockLambda).call(); - assertThrows(SQLException.class, () -> { - spyPlugin.connect(protocol, hostSpec, props, true, mockLambda); - }); + assertThrows( + SQLException.class, + () -> { + spyPlugin.connect(protocol, hostSpec, props, true, mockLambda); + }); verify(mockLambda, times(1)).call(); - assertEquals(GENERATED_TOKEN, props.getProperty(ConnectionPropertyNames.PASSWORD_PROPERTY_NAME)); + assertEquals( + GENERATED_TOKEN, props.getProperty(ConnectionPropertyNames.PASSWORD_PROPERTY_NAME)); assertEquals(GENERATED_TOKEN, IamAuthConnectionPlugin.tokenCache.get(PG_CACHE_KEY).getToken()); } } diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/efm/MonitorConnectionContextTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/efm/MonitorConnectionContextTest.java index caec6a34f..03ff44502 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/efm/MonitorConnectionContextTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/efm/MonitorConnectionContextTest.java @@ -18,7 +18,6 @@ package com.amazon.awslabs.jdbc.plugin.efm; -import com.amazon.awslabs.jdbc.plugin.efm.MonitorConnectionContext; import java.util.Collections; import java.util.HashSet; import java.util.Set; diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandlerTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandlerTest.java index 5cb488ddb..8fcdcb21d 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandlerTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareReaderFailoverHandlerTest.java @@ -59,14 +59,14 @@ class ClusterAwareReaderFailoverHandlerTest { private AutoCloseable closeable; private final Properties properties = new Properties(); - private final List defaultHosts = Arrays.asList( - new HostSpec("writer", 1234, HostRole.WRITER), - new HostSpec("reader1", 1234, HostRole.READER), - new HostSpec("reader2", 1234, HostRole.READER), - new HostSpec("reader3", 1234, HostRole.READER), - new HostSpec("reader4", 1234, HostRole.READER), - new HostSpec("reader5", 1234, HostRole.READER) - ); + private final List defaultHosts = + Arrays.asList( + new HostSpec("writer", 1234, HostRole.WRITER), + new HostSpec("reader1", 1234, HostRole.READER), + new HostSpec("reader2", 1234, HostRole.READER), + new HostSpec("reader3", 1234, HostRole.READER), + new HostSpec("reader4", 1234, HostRole.READER), + new HostSpec("reader5", 1234, HostRole.READER)); @BeforeEach void setUp() { @@ -105,10 +105,7 @@ public void testFailover() throws SQLException { when(mockHostListProvider.getDownHosts()).thenReturn(downHosts); final ReaderFailoverHandler target = - new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties); + new ClusterAwareReaderFailoverHandler(mockHostListProvider, mockPluginService, properties); final ReaderFailoverResult result = target.failover(hosts, hosts.get(currentHostIndex)); assertTrue(result.isConnected()); @@ -133,10 +130,12 @@ public void testFailover_timeout() throws SQLException { final int currentHostIndex = 2; for (HostSpec host : hosts) { when(mockPluginService.connect(host, properties)) - .thenAnswer((Answer) invocation -> { - Thread.sleep(20000); - return mockConnection; - }); + .thenAnswer( + (Answer) + invocation -> { + Thread.sleep(20000); + return mockConnection; + }); } final Set downHosts = new HashSet<>(); @@ -148,44 +147,30 @@ public void testFailover_timeout() throws SQLException { final ReaderFailoverHandler target = new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties, - 5000, - 30000); - final ReaderFailoverResult result = - target.failover(hosts, hosts.get(currentHostIndex)); + mockHostListProvider, mockPluginService, properties, 5000, 30000); + final ReaderFailoverResult result = target.failover(hosts, hosts.get(currentHostIndex)); assertFalse(result.isConnected()); assertNull(result.getConnection()); - assertEquals( - FailoverConnectionPlugin.NO_CONNECTION_INDEX, - result.getConnectionIndex()); + assertEquals(FailoverConnectionPlugin.NO_CONNECTION_INDEX, result.getConnectionIndex()); } @Test public void testFailover_nullOrEmptyHostList() throws SQLException { final ClusterAwareReaderFailoverHandler target = - new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties); + new ClusterAwareReaderFailoverHandler(mockHostListProvider, mockPluginService, properties); final HostSpec currentHost = new HostSpec("writer", 1234); ReaderFailoverResult result = target.failover(null, currentHost); assertFalse(result.isConnected()); assertNull(result.getConnection()); - assertEquals( - FailoverConnectionPlugin.NO_CONNECTION_INDEX, - result.getConnectionIndex()); + assertEquals(FailoverConnectionPlugin.NO_CONNECTION_INDEX, result.getConnectionIndex()); final List hosts = new ArrayList<>(); result = target.failover(hosts, currentHost); assertFalse(result.isConnected()); assertNull(result.getConnection()); - assertEquals( - FailoverConnectionPlugin.NO_CONNECTION_INDEX, - result.getConnectionIndex()); + assertEquals(FailoverConnectionPlugin.NO_CONNECTION_INDEX, result.getConnectionIndex()); } @Test @@ -194,7 +179,8 @@ public void testGetReader_connectionSuccess() throws SQLException { // first connection attempt to return succeeds, second attempt cancelled // expected test result: successful connection for host at index 2 when(mockHostListProvider.getDownHosts()).thenReturn(new HashSet<>()); - final List hosts = defaultHosts.subList(0, 3); // 2 connection attempts (writer not attempted) + final List hosts = + defaultHosts.subList(0, 3); // 2 connection attempts (writer not attempted) final HostSpec slowHost = hosts.get(1); final HostSpec fastHost = hosts.get(2); when(mockPluginService.connect(slowHost, properties)) @@ -207,10 +193,7 @@ public void testGetReader_connectionSuccess() throws SQLException { when(mockPluginService.connect(eq(fastHost), eq(properties))).thenReturn(mockConnection); final ReaderFailoverHandler target = - new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties); + new ClusterAwareReaderFailoverHandler(mockHostListProvider, mockPluginService, properties); final ReaderFailoverResult result = target.getReaderConnection(hosts); assertTrue(result.isConnected()); @@ -227,29 +210,25 @@ public void testGetReader_connectionFailure() throws SQLException { // first connection attempt to return fails // expected test result: failure to get reader when(mockHostListProvider.getDownHosts()).thenReturn(new HashSet<>()); - final List hosts = defaultHosts.subList(0, 4); // 3 connection attempts (writer not attempted) - when(mockPluginService.connect(any(), eq(properties))).thenThrow(new SQLException("exception", "08S01", null)); + final List hosts = + defaultHosts.subList(0, 4); // 3 connection attempts (writer not attempted) + when(mockPluginService.connect(any(), eq(properties))) + .thenThrow(new SQLException("exception", "08S01", null)); final int currentHostIndex = 2; final ReaderFailoverHandler target = - new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties); + new ClusterAwareReaderFailoverHandler(mockHostListProvider, mockPluginService, properties); final ReaderFailoverResult result = target.getReaderConnection(hosts); assertFalse(result.isConnected()); assertNull(result.getConnection()); - assertEquals( - FailoverConnectionPlugin.NO_CONNECTION_INDEX, - result.getConnectionIndex()); + assertEquals(FailoverConnectionPlugin.NO_CONNECTION_INDEX, result.getConnectionIndex()); final HostSpec currentHost = hosts.get(currentHostIndex); verify(mockHostListProvider, atLeastOnce()).addToDownHostList(eq(currentHost)); verify(mockHostListProvider, never()) - .addToDownHostList( - eq(hosts.get(FailoverConnectionPlugin.WRITER_CONNECTION_INDEX))); + .addToDownHostList(eq(hosts.get(FailoverConnectionPlugin.WRITER_CONNECTION_INDEX))); } @Test @@ -258,7 +237,8 @@ public void testGetReader_connectionAttemptsTimeout() throws SQLException { // first connection attempt to return times out // expected test result: failure to get reader when(mockHostListProvider.getDownHosts()).thenReturn(new HashSet<>()); - final List hosts = defaultHosts.subList(0, 3); // 2 connection attempts (writer not attempted) + final List hosts = + defaultHosts.subList(0, 3); // 2 connection attempts (writer not attempted) when(mockPluginService.connect(any(), eq(properties))) .thenAnswer( (Answer) @@ -273,18 +253,12 @@ public void testGetReader_connectionAttemptsTimeout() throws SQLException { final ClusterAwareReaderFailoverHandler target = new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties, - 60000, - 1000); + mockHostListProvider, mockPluginService, properties, 60000, 1000); final ReaderFailoverResult result = target.getReaderConnection(hosts); assertFalse(result.isConnected()); assertNull(result.getConnection()); - assertEquals( - FailoverConnectionPlugin.NO_CONNECTION_INDEX, - result.getConnectionIndex()); + assertEquals(FailoverConnectionPlugin.NO_CONNECTION_INDEX, result.getConnectionIndex()); verify(mockHostListProvider, never()).addToDownHostList(any()); } @@ -300,10 +274,7 @@ public void testGetHostTuplesByPriority() { } final ClusterAwareReaderFailoverHandler target = - new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties); + new ClusterAwareReaderFailoverHandler(mockHostListProvider, mockPluginService, properties); final List tuplesByPriority = target.getHostTuplesByPriority(originalHosts, downHosts); @@ -349,10 +320,7 @@ public void testGetReaderTuplesByPriority() { } final ClusterAwareReaderFailoverHandler target = - new ClusterAwareReaderFailoverHandler( - mockHostListProvider, - mockPluginService, - properties); + new ClusterAwareReaderFailoverHandler(mockHostListProvider, mockPluginService, properties); final List readerTuples = target.getReaderTuplesByPriority(originalHosts, downHosts); diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareWriterFailoverHandlerTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareWriterFailoverHandlerTest.java index 1028d8bd9..63e527c3e 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareWriterFailoverHandlerTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/ClusterAwareWriterFailoverHandlerTest.java @@ -90,7 +90,8 @@ public void testReconnectToWriter_taskBReaderException() throws SQLException { when(mockHostListProvider.getTopology(any(Connection.class), eq(true))).thenReturn(topology); - when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList())).thenThrow(SQLException.class); + when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList())) + .thenThrow(SQLException.class); final ClusterAwareWriterFailoverHandler target = new ClusterAwareWriterFailoverHandler( @@ -126,7 +127,8 @@ public void testReconnectToWriter_SlowReaderA() throws SQLException { when(mockPluginService.connect(refEq(readerB), eq(properties))).thenThrow(SQLException.class); when(mockHostListProvider.getTopology(eq(mockWriterConnection), eq(true))).thenReturn(topology); - when(mockHostListProvider.getTopology(eq(mockReaderAConnection), eq(true))).thenReturn(newTopology); + when(mockHostListProvider.getTopology(eq(mockReaderAConnection), eq(true))) + .thenReturn(newTopology); when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList())) .thenAnswer( @@ -216,12 +218,16 @@ public void testConnectToReaderA_SlowWriter() throws SQLException { Thread.sleep(5000); return mockWriterConnection; }); - when(mockPluginService.connect(refEq(readerA), eq(properties))).thenReturn(mockReaderAConnection); - when(mockPluginService.connect(refEq(readerB), eq(properties))).thenReturn(mockReaderBConnection); - when(mockPluginService.connect(refEq(newWriterHost), eq(properties))).thenReturn(mockNewWriterConnection); + when(mockPluginService.connect(refEq(readerA), eq(properties))) + .thenReturn(mockReaderAConnection); + when(mockPluginService.connect(refEq(readerB), eq(properties))) + .thenReturn(mockReaderBConnection); + when(mockPluginService.connect(refEq(newWriterHost), eq(properties))) + .thenReturn(mockNewWriterConnection); when(mockHostListProvider.getTopology(eq(mockWriterConnection), eq(true))).thenReturn(topology); - when(mockHostListProvider.getTopology(eq(mockReaderAConnection), eq(true))).thenReturn(newTopology); + when(mockHostListProvider.getTopology(eq(mockReaderAConnection), eq(true))) + .thenReturn(newTopology); when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList())) .thenReturn(new ReaderFailoverResult(mockReaderAConnection, 1, true)); @@ -257,8 +263,10 @@ public void testConnectToReaderA_SlowWriter() throws SQLException { @Test public void testConnectToReaderA_taskADefers() throws SQLException { when(mockPluginService.connect(writer, properties)).thenReturn(mockConnection); - when(mockPluginService.connect(refEq(readerA), eq(properties))).thenReturn(mockReaderAConnection); - when(mockPluginService.connect(refEq(readerB), eq(properties))).thenReturn(mockReaderBConnection); + when(mockPluginService.connect(refEq(readerA), eq(properties))) + .thenReturn(mockReaderAConnection); + when(mockPluginService.connect(refEq(readerB), eq(properties))) + .thenReturn(mockReaderBConnection); when(mockPluginService.connect(refEq(newWriterHost), eq(properties))) .thenAnswer( (Answer) @@ -312,8 +320,10 @@ public void testFailedToConnect_failoverTimeout() throws SQLException { Thread.sleep(30000); return mockWriterConnection; }); - when(mockPluginService.connect(refEq(readerA), eq(properties))).thenReturn(mockReaderAConnection); - when(mockPluginService.connect(refEq(readerB), eq(properties))).thenReturn(mockReaderBConnection); + when(mockPluginService.connect(refEq(readerA), eq(properties))) + .thenReturn(mockReaderAConnection); + when(mockPluginService.connect(refEq(readerB), eq(properties))) + .thenReturn(mockReaderBConnection); when(mockPluginService.connect(refEq(newWriterHost), eq(properties))) .thenAnswer( (Answer) @@ -356,11 +366,14 @@ public void testFailedToConnect_failoverTimeout() throws SQLException { */ @Test public void testFailedToConnect_taskAException_taskBWriterException() throws SQLException { - when(mockPluginService.connect(refEq(writer), eq(properties))).thenThrow( - new SQLException("exception", "08S01", null)); - when(mockPluginService.connect(refEq(readerA), eq(properties))).thenReturn(mockReaderAConnection); - when(mockPluginService.connect(refEq(readerB), eq(properties))).thenReturn(mockReaderBConnection); - when(mockPluginService.connect(refEq(newWriterHost), eq(properties))).thenThrow(SQLException.class); + when(mockPluginService.connect(refEq(writer), eq(properties))) + .thenThrow(new SQLException("exception", "08S01", null)); + when(mockPluginService.connect(refEq(readerA), eq(properties))) + .thenReturn(mockReaderAConnection); + when(mockPluginService.connect(refEq(readerB), eq(properties))) + .thenReturn(mockReaderBConnection); + when(mockPluginService.connect(refEq(newWriterHost), eq(properties))) + .thenThrow(SQLException.class); when(mockHostListProvider.getTopology(any(Connection.class), any(Boolean.class))) .thenReturn(newTopology); diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPluginTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPluginTest.java index 51860a278..0d6e2c432 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPluginTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/plugin/failover/FailoverConnectionPluginTest.java @@ -154,15 +154,18 @@ void test_initHostProvider_withDynamicHostListProvider() { initializePlugin(); - assertThrows(SQLException.class, () -> plugin.initHostProvider( - "driverProtocol", - "initialUrl", - properties, - mockHostListProviderService, - mockInitHostProviderFunc, - () -> mockHostListProvider, - (mockHostListProvider) -> mockReaderFailoverHandler, - (mockHostListProvider) -> mockWriterFailoverHandler)); + assertThrows( + SQLException.class, + () -> + plugin.initHostProvider( + "driverProtocol", + "initialUrl", + properties, + mockHostListProviderService, + mockInitHostProviderFunc, + () -> mockHostListProvider, + (mockHostListProvider) -> mockReaderFailoverHandler, + (mockHostListProvider) -> mockWriterFailoverHandler)); verify(mockHostListProviderService).isStaticHostListProvider(); } @@ -189,7 +192,8 @@ void test_notifyNodeListChanged_withValidConnectionNotInTopology() { plugin.notifyNodeListChanged(changes); when(mockHostSpec.getUrl()).thenReturn("cluster-url"); - when(mockHostSpec.getAliases()).thenReturn(new HashSet<>(Collections.singletonList("instance"))); + when(mockHostSpec.getAliases()) + .thenReturn(new HashSet<>(Collections.singletonList("instance"))); verify(mockPluginService).getCurrentHostSpec(); verify(mockHostSpec).getAliases(); @@ -273,8 +277,10 @@ void test_failover_failoverReader() throws SQLException { doNothing().when(spyPlugin).failoverWriter(); when(spyPlugin.shouldPerformWriterFailover()).thenReturn(true); - SQLException exception = assertThrows(SQLException.class, () -> spyPlugin.failover(mockHostSpec)); - assertEquals(SqlState.CONNECTION_FAILURE_DURING_TRANSACTION.getState(), exception.getSQLState()); + SQLException exception = + assertThrows(SQLException.class, () -> spyPlugin.failover(mockHostSpec)); + assertEquals( + SqlState.CONNECTION_FAILURE_DURING_TRANSACTION.getState(), exception.getSQLState()); verify(spyPlugin).failoverWriter(); } @@ -287,7 +293,8 @@ void test_failover_failoverWriter() throws SQLException { doNothing().when(spyPlugin).failoverReader(eq(mockHostSpec)); when(spyPlugin.shouldPerformWriterFailover()).thenReturn(false); - SQLException exception = assertThrows(SQLException.class, () -> spyPlugin.failover(mockHostSpec)); + SQLException exception = + assertThrows(SQLException.class, () -> spyPlugin.failover(mockHostSpec)); assertEquals(SqlState.COMMUNICATION_LINK_CHANGED.getState(), exception.getSQLState()); verify(spyPlugin).failoverReader(eq(mockHostSpec)); } @@ -443,7 +450,8 @@ void test_invalidateCurrentConnection_inTransaction() throws SQLException { when(mockHostSpec.getPort()).thenReturn(123); when(mockHostSpec.getRole()).thenReturn(HostRole.READER); - final HostSpec expectedHostSpec = new HostSpec("host", 123, HostRole.READER, HostAvailability.NOT_AVAILABLE); + final HostSpec expectedHostSpec = + new HostSpec("host", 123, HostRole.READER, HostAvailability.NOT_AVAILABLE); initializePlugin(); plugin.invalidateCurrentConnection(); @@ -453,7 +461,8 @@ void test_invalidateCurrentConnection_inTransaction() throws SQLException { doThrow(new SQLException()).when(mockConnection).rollback(); assertDoesNotThrow(() -> plugin.invalidateCurrentConnection()); - verify(mockPluginService, times(2)).setCurrentConnection(eq(mockConnection), hostSpecArgumentCaptor.capture()); + verify(mockPluginService, times(2)) + .setCurrentConnection(eq(mockConnection), hostSpecArgumentCaptor.capture()); assertEquals(expectedHostSpec, hostSpecArgumentCaptor.getValue()); } @@ -463,13 +472,15 @@ void test_invalidateCurrentConnection_notInTransaction() throws SQLException { when(mockHostSpec.getHost()).thenReturn("host"); when(mockHostSpec.getPort()).thenReturn(123); when(mockHostSpec.getRole()).thenReturn(HostRole.READER); - final HostSpec expectedHostSpec = new HostSpec("host", 123, HostRole.READER, HostAvailability.NOT_AVAILABLE); + final HostSpec expectedHostSpec = + new HostSpec("host", 123, HostRole.READER, HostAvailability.NOT_AVAILABLE); initializePlugin(); plugin.invalidateCurrentConnection(); verify(mockPluginService).isInTransaction(); - verify(mockPluginService).setCurrentConnection(eq(mockConnection), hostSpecArgumentCaptor.capture()); + verify(mockPluginService) + .setCurrentConnection(eq(mockConnection), hostSpecArgumentCaptor.capture()); assertEquals(expectedHostSpec, hostSpecArgumentCaptor.getValue()); } @@ -480,7 +491,8 @@ void test_invalidateCurrentConnection_withOpenConnection() throws SQLException { when(mockHostSpec.getHost()).thenReturn("host"); when(mockHostSpec.getPort()).thenReturn(123); when(mockHostSpec.getRole()).thenReturn(HostRole.READER); - final HostSpec expectedHostSpec = new HostSpec("host", 123, HostRole.READER, HostAvailability.NOT_AVAILABLE); + final HostSpec expectedHostSpec = + new HostSpec("host", 123, HostRole.READER, HostAvailability.NOT_AVAILABLE); initializePlugin(); plugin.invalidateCurrentConnection(); @@ -490,7 +502,8 @@ void test_invalidateCurrentConnection_withOpenConnection() throws SQLException { verify(mockConnection, times(2)).isClosed(); verify(mockConnection, times(2)).close(); - verify(mockPluginService, times(2)).setCurrentConnection(eq(mockConnection), hostSpecArgumentCaptor.capture()); + verify(mockPluginService, times(2)) + .setCurrentConnection(eq(mockConnection), hostSpecArgumentCaptor.capture()); assertEquals(expectedHostSpec, hostSpecArgumentCaptor.getValue()); } @@ -530,13 +543,16 @@ void test_execute_withInvalidHostListProvider() { when(mockPluginService.getHostListProvider()).thenReturn(new FooHostListProvider()); initializePlugin(); - assertThrows(SQLException.class, () -> plugin.execute( - ResultSet.class, + assertThrows( SQLException.class, - MONITOR_METHOD_INVOKE_ON, - MONITOR_METHOD_NAME, - mockSqlFunction, - EMPTY_ARGS)); + () -> + plugin.execute( + ResultSet.class, + SQLException.class, + MONITOR_METHOD_INVOKE_ON, + MONITOR_METHOD_NAME, + mockSqlFunction, + EMPTY_ARGS)); } private void initializePlugin() { diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParserTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParserTest.java index 89639aa6c..48aec3fa8 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParserTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/ConnectionUrlParserTest.java @@ -33,7 +33,8 @@ class ConnectionUrlParserTest { @ParameterizedTest @MethodSource("testGetHostsFromConnectionUrlArguments") - void testGetHostsFromConnectionUrl_returnCorrectHostList(String testUrl, List expected) { + void testGetHostsFromConnectionUrl_returnCorrectHostList( + String testUrl, List expected) { final ConnectionUrlParser parser = new ConnectionUrlParser(); final List results = parser.getHostsFromConnectionUrl(testUrl); @@ -48,14 +49,17 @@ private static Stream testGetHostsFromConnectionUrlArguments() { Arguments.of("protocol//", new ArrayList()), Arguments.of("bar/", new ArrayList()), Arguments.of("invalid-hosts?", new ArrayList()), - Arguments.of("jdbc//host:3303/db?param=1", Collections.singletonList(new HostSpec("host", 3303))), - Arguments.of("protocol//host2:3303", Collections.singletonList(new HostSpec("host2", 3303))), + Arguments.of( + "jdbc//host:3303/db?param=1", Collections.singletonList(new HostSpec("host", 3303))), + Arguments.of( + "protocol//host2:3303", Collections.singletonList(new HostSpec("host2", 3303))), Arguments.of("foo//host:3303/?#", Collections.singletonList(new HostSpec("host", 3303))), - Arguments.of("jdbc:mysql:replication://host:badInt?param=", + Arguments.of( + "jdbc:mysql:replication://host:badInt?param=", Collections.singletonList(new HostSpec("host"))), - Arguments.of("jdbc:driver:test://source,replica1:3303,host/test", - Arrays.asList(new HostSpec("source"), new HostSpec("replica1", 3303), - new HostSpec("host"))) - ); + Arguments.of( + "jdbc:driver:test://source,replica1:3303,host/test", + Arrays.asList( + new HostSpec("source"), new HostSpec("replica1", 3303), new HostSpec("host")))); } } diff --git a/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/WrapperUtilsTest.java b/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/WrapperUtilsTest.java index 2824451b8..4d63d3a65 100644 --- a/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/WrapperUtilsTest.java +++ b/wrapper/src/test/java/com/amazon/awslabs/jdbc/util/WrapperUtilsTest.java @@ -48,30 +48,39 @@ private void init() { final ReentrantLock testLock = new ReentrantLock(); closeable = MockitoAnnotations.openMocks(this); - doAnswer(invocation -> { - pluginManagerLock.lock(); - return null; - }).when(pluginManager).lock(); - doAnswer(invocation -> { - pluginManagerLock.unlock(); - return null; - }).when(pluginManager).unlock(); - - doAnswer(invocation -> { - boolean lockIsFree = testLock.tryLock(); - if (!lockIsFree) { - fail("Lock is in use, should not be attempting to fetch it right now"); - } - Thread.sleep(3000); - testLock.unlock(); - return 1; - }).when(pluginManager).execute( - any(Class.class), - any(Class.class), - any(Object.class), - any(String.class), - any(JdbcCallable.class), - any(Object[].class)); + doAnswer( + invocation -> { + pluginManagerLock.lock(); + return null; + }) + .when(pluginManager) + .lock(); + doAnswer( + invocation -> { + pluginManagerLock.unlock(); + return null; + }) + .when(pluginManager) + .unlock(); + + doAnswer( + invocation -> { + boolean lockIsFree = testLock.tryLock(); + if (!lockIsFree) { + fail("Lock is in use, should not be attempting to fetch it right now"); + } + Thread.sleep(3000); + testLock.unlock(); + return 1; + }) + .when(pluginManager) + .execute( + any(Class.class), + any(Class.class), + any(Object.class), + any(String.class), + any(JdbcCallable.class), + any(Object[].class)); } @AfterEach @@ -81,22 +90,13 @@ void cleanUp() throws Exception { Integer callExecuteWithPlugins() { return WrapperUtils.executeWithPlugins( - Integer.class, - pluginManager, - object, - "methodName", - () -> 1); + Integer.class, pluginManager, object, "methodName", () -> 1); } Integer callExecuteWithPluginsWithException() { try { return WrapperUtils.executeWithPlugins( - Integer.class, - SQLException.class, - pluginManager, - object, - "methodName", - () -> 1); + Integer.class, SQLException.class, pluginManager, object, "methodName", () -> 1); } catch (SQLException e) { fail(); } diff --git a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresBaseTest.java b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresBaseTest.java index c39f6ce0b..52b117843 100644 --- a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresBaseTest.java +++ b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresBaseTest.java @@ -57,10 +57,14 @@ public abstract class AuroraPostgresBaseTest { - protected static final String AURORA_POSTGRES_USERNAME = System.getenv("AURORA_POSTGRES_USERNAME"); - protected static final String AURORA_POSTGRES_PASSWORD = System.getenv("AURORA_POSTGRES_PASSWORD"); + protected static final String AURORA_POSTGRES_USERNAME = + System.getenv("AURORA_POSTGRES_USERNAME"); + protected static final String AURORA_POSTGRES_PASSWORD = + System.getenv("AURORA_POSTGRES_PASSWORD"); protected static final String AURORA_POSTGRES_DB = - !StringUtils.isNullOrEmpty(System.getenv("AURORA_POSTGRES_DB")) ? System.getenv("AURORA_POSTGRES_DB") : "test"; + !StringUtils.isNullOrEmpty(System.getenv("AURORA_POSTGRES_DB")) + ? System.getenv("AURORA_POSTGRES_DB") + : "test"; protected static final String QUERY_FOR_INSTANCE = "SELECT aurora_db_instance_identifier()"; @@ -89,8 +93,10 @@ public abstract class AuroraPostgresBaseTest { ? System.getenv("AURORA_POSTGRES_DB_REGION") : "us-east-1"; - protected static final int AURORA_POSTGRES_PORT = Integer.parseInt(System.getenv("AURORA_POSTGRES_PORT")); - protected static final int POSTGRES_PROXY_PORT = Integer.parseInt(System.getenv("POSTGRES_PROXY_PORT")); + protected static final int AURORA_POSTGRES_PORT = + Integer.parseInt(System.getenv("AURORA_POSTGRES_PORT")); + protected static final int POSTGRES_PROXY_PORT = + Integer.parseInt(System.getenv("POSTGRES_PROXY_PORT")); protected static final String TOXIPROXY_INSTANCE_1_NETWORK_ALIAS = System.getenv("TOXIPROXY_INSTANCE_1_NETWORK_ALIAS"); @@ -162,24 +168,35 @@ public static void setUp() throws IOException, SQLException { toxiproxyReadOnlyCluster = new ToxiproxyClient(TOXIPROXY_RO_CLUSTER_NETWORK_ALIAS, TOXIPROXY_CONTROL_PORT); - proxyInstance_1 = getProxy(toxiproxyClientInstance_1, POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT); - proxyInstance_2 = getProxy(toxiproxyClientInstance_2, POSTGRES_INSTANCE_2_URL, AURORA_POSTGRES_PORT); - proxyInstance_3 = getProxy(toxiproxyClientInstance_3, POSTGRES_INSTANCE_3_URL, AURORA_POSTGRES_PORT); - proxyInstance_4 = getProxy(toxiproxyClientInstance_4, POSTGRES_INSTANCE_4_URL, AURORA_POSTGRES_PORT); - proxyInstance_5 = getProxy(toxiproxyClientInstance_5, POSTGRES_INSTANCE_5_URL, AURORA_POSTGRES_PORT); + proxyInstance_1 = + getProxy(toxiproxyClientInstance_1, POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT); + proxyInstance_2 = + getProxy(toxiproxyClientInstance_2, POSTGRES_INSTANCE_2_URL, AURORA_POSTGRES_PORT); + proxyInstance_3 = + getProxy(toxiproxyClientInstance_3, POSTGRES_INSTANCE_3_URL, AURORA_POSTGRES_PORT); + proxyInstance_4 = + getProxy(toxiproxyClientInstance_4, POSTGRES_INSTANCE_4_URL, AURORA_POSTGRES_PORT); + proxyInstance_5 = + getProxy(toxiproxyClientInstance_5, POSTGRES_INSTANCE_5_URL, AURORA_POSTGRES_PORT); proxyCluster = getProxy(toxiproxyCluster, POSTGRES_CLUSTER_URL, AURORA_POSTGRES_PORT); - proxyReadOnlyCluster = getProxy(toxiproxyReadOnlyCluster, POSTGRES_RO_CLUSTER_URL, AURORA_POSTGRES_PORT); + proxyReadOnlyCluster = + getProxy(toxiproxyReadOnlyCluster, POSTGRES_RO_CLUSTER_URL, AURORA_POSTGRES_PORT); proxyMap.put( - POSTGRES_INSTANCE_1_URL.substring(0, POSTGRES_INSTANCE_1_URL.indexOf('.')), proxyInstance_1); + POSTGRES_INSTANCE_1_URL.substring(0, POSTGRES_INSTANCE_1_URL.indexOf('.')), + proxyInstance_1); proxyMap.put( - POSTGRES_INSTANCE_2_URL.substring(0, POSTGRES_INSTANCE_2_URL.indexOf('.')), proxyInstance_2); + POSTGRES_INSTANCE_2_URL.substring(0, POSTGRES_INSTANCE_2_URL.indexOf('.')), + proxyInstance_2); proxyMap.put( - POSTGRES_INSTANCE_3_URL.substring(0, POSTGRES_INSTANCE_3_URL.indexOf('.')), proxyInstance_3); + POSTGRES_INSTANCE_3_URL.substring(0, POSTGRES_INSTANCE_3_URL.indexOf('.')), + proxyInstance_3); proxyMap.put( - POSTGRES_INSTANCE_4_URL.substring(0, POSTGRES_INSTANCE_4_URL.indexOf('.')), proxyInstance_4); + POSTGRES_INSTANCE_4_URL.substring(0, POSTGRES_INSTANCE_4_URL.indexOf('.')), + proxyInstance_4); proxyMap.put( - POSTGRES_INSTANCE_5_URL.substring(0, POSTGRES_INSTANCE_5_URL.indexOf('.')), proxyInstance_5); + POSTGRES_INSTANCE_5_URL.substring(0, POSTGRES_INSTANCE_5_URL.indexOf('.')), + proxyInstance_5); proxyMap.put(POSTGRES_CLUSTER_URL, proxyCluster); proxyMap.put(POSTGRES_RO_CLUSTER_URL, proxyReadOnlyCluster); @@ -282,7 +299,12 @@ protected List getTopologyEndpoints() throws SQLException { DB_CONN_STR_SUFFIX.startsWith(".") ? DB_CONN_STR_SUFFIX.substring(1) : DB_CONN_STR_SUFFIX; final String url = - DB_CONN_STR_PREFIX + POSTGRES_INSTANCE_1_URL + ":" + AURORA_POSTGRES_PORT + "/" + AURORA_POSTGRES_DB; + DB_CONN_STR_PREFIX + + POSTGRES_INSTANCE_1_URL + + ":" + + AURORA_POSTGRES_PORT + + "/" + + AURORA_POSTGRES_DB; return this.containerHelper.getAuroraInstanceEndpoints( url, AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD, dbConnHostBase); } @@ -291,8 +313,14 @@ protected List getTopologyEndpoints() throws SQLException { // Writer instance goes first. protected List getTopologyIds() throws SQLException { final String url = - DB_CONN_STR_PREFIX + POSTGRES_INSTANCE_1_URL + ":" + AURORA_POSTGRES_PORT + "/" + AURORA_POSTGRES_DB; - return this.containerHelper.getAuroraInstanceIds(url, AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD); + DB_CONN_STR_PREFIX + + POSTGRES_INSTANCE_1_URL + + ":" + + AURORA_POSTGRES_PORT + + "/" + + AURORA_POSTGRES_DB; + return this.containerHelper.getAuroraInstanceIds( + url, AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD); } /* Helper functions. */ @@ -322,8 +350,12 @@ protected void assertFirstQueryThrows(Connection connection, String expectedSQLE } protected void assertFirstQueryThrows(Statement stmt, String expectedSQLErrorCode) { - final SQLException exception = assertThrows(SQLException.class, () -> executeInstanceIdQuery(stmt)); - assertEquals(expectedSQLErrorCode, exception.getSQLState(), "Unexpected SQL Exception: " + exception.getMessage()); + final SQLException exception = + assertThrows(SQLException.class, () -> executeInstanceIdQuery(stmt)); + assertEquals( + expectedSQLErrorCode, + exception.getSQLState(), + "Unexpected SQL Exception: " + exception.getMessage()); } protected Connection createPooledConnectionWithInstanceId(String instanceID) throws SQLException { @@ -365,7 +397,8 @@ protected DBClusterMember getMatchedDBClusterMember(String instanceId) { protected String getDBClusterWriterInstanceId() { final List matchedMemberList = getDBClusterMemberList().stream() - .filter(DBClusterMember::isClusterWriter).collect(Collectors.toList()); + .filter(DBClusterMember::isClusterWriter) + .collect(Collectors.toList()); if (matchedMemberList.isEmpty()) { throw new RuntimeException(NO_WRITER_AVAILABLE); } @@ -418,7 +451,8 @@ protected void makeSureInstancesUp(String[] instances, boolean finalCheck) if (finalCheck) { assertTrue( remainingInstances.isEmpty(), - "The following instances are still down: \n" + String.join("\n", remainingInstances.keySet())); + "The following instances are still down: \n" + + String.join("\n", remainingInstances.keySet())); } } } diff --git a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresDataSourceTest.java b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresDataSourceTest.java index 38e3f5c83..f3a7bd69f 100644 --- a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresDataSourceTest.java +++ b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresDataSourceTest.java @@ -153,9 +153,7 @@ public void testConnectionWithDataSourceClassNameMissingUser() { targetDataSourceProps.setProperty("databaseName", AURORA_POSTGRES_DB); ds.setTargetDataSourceProperties(targetDataSourceProps); - assertThrows( - PSQLException.class, - () -> ds.getConnection("", AURORA_POSTGRES_PASSWORD)); + assertThrows(PSQLException.class, () -> ds.getConnection("", AURORA_POSTGRES_PASSWORD)); } @Test @@ -173,9 +171,7 @@ public void testConnectionWithDataSourceClassNameMissingPassword() { targetDataSourceProps.setProperty("databaseName", AURORA_POSTGRES_DB); ds.setTargetDataSourceProperties(targetDataSourceProps); - assertThrows( - PSQLException.class, - () -> ds.getConnection(AURORA_POSTGRES_USERNAME, "")); + assertThrows(PSQLException.class, () -> ds.getConnection(AURORA_POSTGRES_USERNAME, "")); } @Test @@ -233,10 +229,14 @@ public void testConnectionWithDataSourceClassNameUsingUrlWithCredentials() throw ds.setJdbcUrl( DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL - + ":" + AURORA_POSTGRES_PORT + "/" + + ":" + + AURORA_POSTGRES_PORT + + "/" + AURORA_POSTGRES_DB - + "?user=" + AURORA_POSTGRES_USERNAME - + "&password=" + AURORA_POSTGRES_PASSWORD); + + "?user=" + + AURORA_POSTGRES_USERNAME + + "&password=" + + AURORA_POSTGRES_PASSWORD); Connection conn = ds.getConnection(); @@ -259,7 +259,13 @@ public void testConnectionWithDataSourceClassNameUsingUrlWithPort() throws SQLEx ds.setTargetDataSourceClassName("org.postgresql.ds.PGSimpleDataSource"); - ds.setJdbcUrl(DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL + ":" + AURORA_POSTGRES_PORT + "/" + AURORA_POSTGRES_DB); + ds.setJdbcUrl( + DB_CONN_STR_PREFIX + + POSTGRES_CLUSTER_URL + + ":" + + AURORA_POSTGRES_PORT + + "/" + + AURORA_POSTGRES_DB); Connection conn = ds.getConnection(AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD); @@ -334,7 +340,13 @@ public void testConnectionWithUrl() throws SQLException { ds.setUserPropertyName("user"); ds.setPasswordPropertyName("password"); ds.setPortPropertyName("port"); - ds.setJdbcUrl(DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL + ":" + AURORA_POSTGRES_PORT + "/" + AURORA_POSTGRES_DB); + ds.setJdbcUrl( + DB_CONN_STR_PREFIX + + POSTGRES_CLUSTER_URL + + ":" + + AURORA_POSTGRES_PORT + + "/" + + AURORA_POSTGRES_DB); Connection conn = ds.getConnection(AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD); @@ -354,10 +366,14 @@ public void testConnectionWithUrlWithCredentials() throws SQLException { ds.setJdbcUrl( DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL - + ":" + AURORA_POSTGRES_PORT + "/" + + ":" + + AURORA_POSTGRES_PORT + + "/" + AURORA_POSTGRES_DB - + "?user=" + AURORA_POSTGRES_USERNAME - + "&password=" + AURORA_POSTGRES_PASSWORD); + + "?user=" + + AURORA_POSTGRES_USERNAME + + "&password=" + + AURORA_POSTGRES_PASSWORD); Connection conn = ds.getConnection(); @@ -405,9 +421,7 @@ public void testConnectionWithUrlMissingUser() { ds.setPortPropertyName("port"); ds.setJdbcUrl(DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL + ":" + AURORA_POSTGRES_PORT + "/"); - assertThrows( - PSQLException.class, - () -> ds.getConnection("", AURORA_POSTGRES_PASSWORD)); + assertThrows(PSQLException.class, () -> ds.getConnection("", AURORA_POSTGRES_PASSWORD)); } @Test @@ -418,15 +432,19 @@ public void testConnectionWithUrlMissingPassword() { ds.setPortPropertyName("port"); ds.setJdbcUrl(DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL + ":" + AURORA_POSTGRES_PORT + "/"); - assertThrows( - PSQLException.class, - () -> ds.getConnection(AURORA_POSTGRES_USERNAME, "")); + assertThrows(PSQLException.class, () -> ds.getConnection(AURORA_POSTGRES_USERNAME, "")); } @Test public void testConnectionWithUrlMissingPropertyNames() { ProxyDriverDataSource ds = new ProxyDriverDataSource(); - ds.setJdbcUrl(DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL + ":" + AURORA_POSTGRES_PORT + "/" + AURORA_POSTGRES_DB); + ds.setJdbcUrl( + DB_CONN_STR_PREFIX + + POSTGRES_CLUSTER_URL + + ":" + + AURORA_POSTGRES_PORT + + "/" + + AURORA_POSTGRES_DB); assertThrows( PSQLException.class, diff --git a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresFailoverTest.java b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresFailoverTest.java index 6b184d973..0ec5db260 100644 --- a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresFailoverTest.java +++ b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresFailoverTest.java @@ -37,8 +37,8 @@ public class AuroraPostgresFailoverTest extends AuroraPostgresBaseTest { /* Writer connection failover tests. */ /** - * Current writer dies, a reader instance is nominated to be a new writer, failover to the new writer. Driver failover - * occurs when executing a method against the connection + * Current writer dies, a reader instance is nominated to be a new writer, failover to the new + * writer. Driver failover occurs when executing a method against the connection */ @Test public void test_failFromWriterToNewWriter_failOnConnectionInvocation() @@ -46,8 +46,8 @@ public void test_failFromWriterToNewWriter_failOnConnectionInvocation() final String initialWriterId = instanceIDs[0]; try (final Connection conn = - connectToInstance(initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, - initDefaultProps())) { + connectToInstance( + initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, initDefaultProps())) { // Crash Instance1 and nominate a new writer failoverClusterAndWaitUntilWriterChanged(initialWriterId); @@ -62,9 +62,9 @@ public void test_failFromWriterToNewWriter_failOnConnectionInvocation() } /** - * Current writer dies, a reader instance is nominated to be a new writer, failover to the new writer Driver failover - * occurs when executing a method against an object bound to the connection (eg a Statement object created by the - * connection). + * Current writer dies, a reader instance is nominated to be a new writer, failover to the new + * writer Driver failover occurs when executing a method against an object bound to the connection + * (eg a Statement object created by the connection). */ @Test public void test_failFromWriterToNewWriter_failOnConnectionBoundObjectInvocation() @@ -72,8 +72,9 @@ public void test_failFromWriterToNewWriter_failOnConnectionBoundObjectInvocation final String initialWriterId = instanceIDs[0]; - try (final Connection conn = connectToInstance(initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, - initDefaultProps())) { + try (final Connection conn = + connectToInstance( + initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, initDefaultProps())) { final Statement stmt = conn.createStatement(); // Crash Instance1 and nominate a new writer @@ -90,8 +91,8 @@ public void test_failFromWriterToNewWriter_failOnConnectionBoundObjectInvocation } /** - * Current reader dies, no other reader instance, failover to writer, then writer dies, failover to another available - * reader instance. + * Current reader dies, no other reader instance, failover to writer, then writer dies, failover + * to another available reader instance. */ @Test public void test_failFromReaderToWriterToAnyAvailableInstance() @@ -108,8 +109,9 @@ public void test_failFromReaderToWriterToAnyAvailableInstance() // Connect to Instance2 which is the only reader that is up. final String instanceId = instanceIDs[1]; - try (final Connection conn = connectToInstance(instanceId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, - POSTGRES_PROXY_PORT)) { + try (final Connection conn = + connectToInstance( + instanceId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)) { // Crash Instance2 Proxy instanceProxy = proxyMap.get(instanceId); containerHelper.disableConnectivity(instanceProxy); @@ -144,17 +146,16 @@ public void test_failFromReaderToWriterToAnyAvailableInstance() /* Failure when within a transaction tests. */ - /** - * Writer fails within a transaction. Open transaction with setAutoCommit(false) - */ + /** Writer fails within a transaction. Open transaction with setAutoCommit(false) */ @Test public void test_writerFailWithinTransaction_setAutoCommitFalse() throws SQLException, InterruptedException { final String initialWriterId = instanceIDs[0]; - try (final Connection conn = connectToInstance(initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, - initDefaultProps())) { + try (final Connection conn = + connectToInstance( + initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, initDefaultProps())) { final Statement testStmt1 = conn.createStatement(); testStmt1.executeUpdate("DROP TABLE IF EXISTS test3_2"); testStmt1.executeUpdate( @@ -170,7 +171,8 @@ public void test_writerFailWithinTransaction_setAutoCommitFalse() final SQLException exception = assertThrows( SQLException.class, - () -> testStmt2.executeUpdate("INSERT INTO test3_2 VALUES (2, 'test field string 2')")); + () -> + testStmt2.executeUpdate("INSERT INTO test3_2 VALUES (2, 'test field string 2')")); assertEquals("08007", exception.getSQLState()); // Attempt to query the instance id. @@ -193,17 +195,16 @@ public void test_writerFailWithinTransaction_setAutoCommitFalse() } } - /** - * Writer fails within a transaction. Open transaction with "START TRANSACTION". - */ + /** Writer fails within a transaction. Open transaction with "START TRANSACTION". */ @Test public void test_writerFailWithinTransaction_startTransaction() throws SQLException, InterruptedException { final String initialWriterId = instanceIDs[0]; - try (final Connection conn = connectToInstance(initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, - initDefaultProps())) { + try (final Connection conn = + connectToInstance( + initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, initDefaultProps())) { final Statement testStmt1 = conn.createStatement(); testStmt1.executeUpdate("DROP TABLE IF EXISTS test3_3"); testStmt1.executeUpdate( @@ -219,7 +220,8 @@ public void test_writerFailWithinTransaction_startTransaction() final SQLException exception = assertThrows( SQLException.class, - () -> testStmt2.executeUpdate("INSERT INTO test3_3 VALUES (2, 'test field string 2')")); + () -> + testStmt2.executeUpdate("INSERT INTO test3_3 VALUES (2, 'test field string 2')")); assertEquals("08007", exception.getSQLState()); // Attempt to query the instance id. @@ -242,16 +244,15 @@ public void test_writerFailWithinTransaction_startTransaction() } } - /** - * Writer fails within NO transaction. - */ + /** Writer fails within NO transaction. */ @Test public void test_writerFailWithNoTransaction() throws SQLException, InterruptedException { final String initialWriterId = instanceIDs[0]; - try (final Connection conn = connectToInstance(initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, - initDefaultProps())) { + try (final Connection conn = + connectToInstance( + initialWriterId + DB_CONN_STR_SUFFIX, AURORA_POSTGRES_PORT, initDefaultProps())) { final Statement testStmt1 = conn.createStatement(); testStmt1.executeUpdate("DROP TABLE IF EXISTS test3_4"); testStmt1.executeUpdate( @@ -265,7 +266,8 @@ public void test_writerFailWithNoTransaction() throws SQLException, InterruptedE final SQLException exception = assertThrows( SQLException.class, - () -> testStmt2.executeUpdate("INSERT INTO test3_4 VALUES (2, 'test field string 2')")); + () -> + testStmt2.executeUpdate("INSERT INTO test3_4 VALUES (2, 'test field string 2')")); assertEquals("08S02", exception.getSQLState()); // Attempt to query the instance id. @@ -294,12 +296,11 @@ public void test_writerFailWithNoTransaction() throws SQLException, InterruptedE /* Pooled connection tests. */ - /** - * Writer connection failover within the connection pool. - */ + /** Writer connection failover within the connection pool. */ @Test @Disabled // TODO: enable test once datasource is supported - public void test_pooledWriterConnection_BasicFailover() throws SQLException, InterruptedException { + public void test_pooledWriterConnection_BasicFailover() + throws SQLException, InterruptedException { final String initialWriterId = instanceIDs[0]; final String nominatedWriterId = instanceIDs[1]; @@ -332,16 +333,16 @@ public void test_takeOverConnectionProperties() throws SQLException, Interrupted final Properties props = initDefaultProps(); props.setProperty("defaultRowFetchSize", String.valueOf(newRowFetchSize)); - // Establish the topology cache so that we can later assert that testConnection does not inherit properties from + // Establish the topology cache so that we can later assert that testConnection does not inherit + // properties from // establishCacheConnection either before or after failover final String url = DB_CONN_STR_PREFIX + POSTGRES_CLUSTER_URL + "/" + AURORA_POSTGRES_DB; - final Connection establishCacheConnection = DriverManager.getConnection( - url, - props); + final Connection establishCacheConnection = DriverManager.getConnection(url, props); establishCacheConnection.close(); props.setProperty("defaultRowFetchSize", String.valueOf(newRowFetchSize)); - try (final Connection conn = connectToInstance(POSTGRES_CLUSTER_URL, AURORA_POSTGRES_PORT, props)) { + try (final Connection conn = + connectToInstance(POSTGRES_CLUSTER_URL, AURORA_POSTGRES_PORT, props)) { // Verify that connection accepts multi-statement sql final Statement testStmt1 = conn.createStatement(); assertEquals(newRowFetchSize, testStmt1.getFetchSize()); @@ -368,7 +369,8 @@ private void failoverCluster() throws InterruptedException { waitUntilClusterHasRightState(); while (true) { try { - rdsClient.failoverDBCluster((builder) -> builder.dbClusterIdentifier(DB_CLUSTER_IDENTIFIER)); + rdsClient.failoverDBCluster( + (builder) -> builder.dbClusterIdentifier(DB_CLUSTER_IDENTIFIER)); break; } catch (final Exception e) { TimeUnit.MILLISECONDS.sleep(1000); @@ -377,8 +379,7 @@ private void failoverCluster() throws InterruptedException { } private void failoverClusterToATargetAndWaitUntilWriterChanged( - String clusterWriterId, - String targetInstanceId) throws InterruptedException { + String clusterWriterId, String targetInstanceId) throws InterruptedException { failoverClusterWithATargetInstance(targetInstanceId); waitUntilWriterInstanceChanged(clusterWriterId); } @@ -390,8 +391,10 @@ private void failoverClusterWithATargetInstance(String targetInstanceId) while (true) { try { rdsClient.failoverDBCluster( - (builder) -> builder.dbClusterIdentifier(DB_CLUSTER_IDENTIFIER) - .targetDBInstanceIdentifier(targetInstanceId)); + (builder) -> + builder + .dbClusterIdentifier(DB_CLUSTER_IDENTIFIER) + .targetDBInstanceIdentifier(targetInstanceId)); break; } catch (final Exception e) { TimeUnit.MILLISECONDS.sleep(1000); diff --git a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresIntegrationTest.java b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresIntegrationTest.java index 18f0168dd..a0fe6272d 100644 --- a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresIntegrationTest.java +++ b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresIntegrationTest.java @@ -47,66 +47,64 @@ public class AuroraPostgresIntegrationTest extends AuroraPostgresBaseTest { protected String currReader; protected static String buildConnectionString( - String connStringPrefix, - String host, - String port, - String databaseName) { + String connStringPrefix, String host, String port, String databaseName) { return connStringPrefix + host + ":" + port + "/" + databaseName; } private static Stream testParameters() { return Stream.of( // missing username - Arguments.of(buildConnectionString( - DB_CONN_STR_PREFIX, - POSTGRES_INSTANCE_1_URL, - String.valueOf(AURORA_POSTGRES_PORT), - AURORA_POSTGRES_DB), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, + POSTGRES_INSTANCE_1_URL, + String.valueOf(AURORA_POSTGRES_PORT), + AURORA_POSTGRES_DB), "", AURORA_POSTGRES_PASSWORD), // missing password - Arguments.of(buildConnectionString( - DB_CONN_STR_PREFIX, - POSTGRES_INSTANCE_1_URL, - String.valueOf(AURORA_POSTGRES_PORT), - AURORA_POSTGRES_DB), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, + POSTGRES_INSTANCE_1_URL, + String.valueOf(AURORA_POSTGRES_PORT), + AURORA_POSTGRES_DB), AURORA_POSTGRES_USERNAME, ""), // missing connection prefix - Arguments.of(buildConnectionString( - "", - POSTGRES_INSTANCE_1_URL, - String.valueOf(AURORA_POSTGRES_PORT), - AURORA_POSTGRES_DB), + Arguments.of( + buildConnectionString( + "", + POSTGRES_INSTANCE_1_URL, + String.valueOf(AURORA_POSTGRES_PORT), + AURORA_POSTGRES_DB), AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD), // missing port - Arguments.of(buildConnectionString( - DB_CONN_STR_PREFIX, - POSTGRES_INSTANCE_1_URL, - "", - AURORA_POSTGRES_DB), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, POSTGRES_INSTANCE_1_URL, "", AURORA_POSTGRES_DB), AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD), // incorrect database name - Arguments.of(buildConnectionString(DB_CONN_STR_PREFIX, - POSTGRES_INSTANCE_1_URL, - String.valueOf(AURORA_POSTGRES_PORT), - "failedDatabaseNameTest"), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, + POSTGRES_INSTANCE_1_URL, + String.valueOf(AURORA_POSTGRES_PORT), + "failedDatabaseNameTest"), AURORA_POSTGRES_USERNAME, - AURORA_POSTGRES_PASSWORD) - ); + AURORA_POSTGRES_PASSWORD)); } private static Stream generateConnectionString() { return Stream.of( - Arguments.of(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT), - Arguments.of(POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT), - Arguments.of(POSTGRES_CLUSTER_URL, AURORA_POSTGRES_PORT), - Arguments.of(POSTGRES_CLUSTER_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT), - Arguments.of(POSTGRES_RO_CLUSTER_URL, AURORA_POSTGRES_PORT), - Arguments.of(POSTGRES_RO_CLUSTER_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT) - ); + Arguments.of(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT), + Arguments.of(POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT), + Arguments.of(POSTGRES_CLUSTER_URL, AURORA_POSTGRES_PORT), + Arguments.of(POSTGRES_CLUSTER_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT), + Arguments.of(POSTGRES_RO_CLUSTER_URL, AURORA_POSTGRES_PORT), + Arguments.of(POSTGRES_RO_CLUSTER_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)); } @ParameterizedTest(name = "test_ConnectionString") @@ -124,7 +122,8 @@ public void test_ConnectionString(String connStr, int port) throws SQLException @Test public void test_ValidateConnectionWhenNetworkDown() throws SQLException, IOException { final Connection conn = - connectToInstance(POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT); + connectToInstance( + POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT); assertTrue(conn.isValid(3)); containerHelper.disableConnectivity(proxyInstance_1); @@ -140,15 +139,19 @@ public void test_ValidateConnectionWhenNetworkDown() throws SQLException, IOExce public void test_ConnectWhenNetworkDown() throws SQLException, IOException { containerHelper.disableConnectivity(proxyInstance_1); - assertThrows(Exception.class, () -> { - // expected to fail since communication is cut - connectToInstance(POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT); - }); + assertThrows( + Exception.class, + () -> { + // expected to fail since communication is cut + connectToInstance( + POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT); + }); containerHelper.enableConnectivity(proxyInstance_1); - final Connection conn = connectToInstance(POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, - POSTGRES_PROXY_PORT); + final Connection conn = + connectToInstance( + POSTGRES_INSTANCE_1_URL + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT); conn.close(); } @@ -161,8 +164,11 @@ public void test_LostConnectionToWriter() throws SQLException, IOException { props.setProperty("failoverTimeoutMs", "10000"); // Connect to cluster - try (final Connection testConnection = connectToInstance( - initialWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT, props)) { + try (final Connection testConnection = + connectToInstance( + initialWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, + POSTGRES_PROXY_PORT, + props)) { // Get writer currWriter = queryInstanceId(testConnection); @@ -192,38 +198,43 @@ public void test_LostConnectionToAllReaders() throws SQLException { String anyReaderId = instanceIDs[1]; // Get Writer - try (final Connection checkWriterConnection = connectToInstance( - currentWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)) { + try (final Connection checkWriterConnection = + connectToInstance( + currentWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, + POSTGRES_PROXY_PORT)) { currWriter = queryInstanceId(checkWriterConnection); } // Connect to cluster - try (final Connection testConnection = connectToInstance( + try (final Connection testConnection = + connectToInstance( anyReaderId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)) { // Get reader currReader = queryInstanceId(testConnection); assertNotEquals(currWriter, currReader); // Put all but writer down - proxyMap.forEach((instance, proxy) -> { - if (!instance.equalsIgnoreCase(currWriter)) { - try { - containerHelper.disableConnectivity(proxy); - } catch (IOException e) { - fail("Toxics were already set, should not happen"); - } - } - }); + proxyMap.forEach( + (instance, proxy) -> { + if (!instance.equalsIgnoreCase(currWriter)) { + try { + containerHelper.disableConnectivity(proxy); + } catch (IOException e) { + fail("Toxics were already set, should not happen"); + } + } + }); assertFirstQueryThrows(testConnection, "08S02"); final String newReader = queryInstanceId(testConnection); assertEquals(currWriter, newReader); } finally { - proxyMap.forEach((instance, proxy) -> { - assertNotNull(proxy, "Proxy isn't found for " + instance); - containerHelper.enableConnectivity(proxy); - }); + proxyMap.forEach( + (instance, proxy) -> { + assertNotNull(proxy, "Proxy isn't found for " + instance); + containerHelper.enableConnectivity(proxy); + }); } } @@ -234,15 +245,18 @@ public void test_LostConnectionToReaderInstance() throws SQLException, IOExcepti String anyReaderId = instanceIDs[1]; // Get Writer - try (final Connection checkWriterConnection = connectToInstance( - currentWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)) { + try (final Connection checkWriterConnection = + connectToInstance( + currentWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, + POSTGRES_PROXY_PORT)) { currWriter = queryInstanceId(checkWriterConnection); } catch (SQLException e) { fail(e); } // Connect to instance - try (final Connection testConnection = connectToInstance( + try (final Connection testConnection = + connectToInstance( anyReaderId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)) { // Get reader currReader = queryInstanceId(testConnection); @@ -273,13 +287,16 @@ public void test_LostConnectionReadOnly() throws SQLException, IOException { String anyReaderId = instanceIDs[1]; // Get Writer - try (final Connection checkWriterConnection = connectToInstance( - currentWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)) { + try (final Connection checkWriterConnection = + connectToInstance( + currentWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, + POSTGRES_PROXY_PORT)) { currWriter = queryInstanceId(checkWriterConnection); } // Connect to instance - try (final Connection testConnection = connectToInstance( + try (final Connection testConnection = + connectToInstance( anyReaderId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT)) { // Get reader currReader = queryInstanceId(testConnection); @@ -310,24 +327,24 @@ void test_ValidInvalidValidConnections() throws SQLException { final Properties validProp = initDefaultProps(); validProp.setProperty(PropertyKey.USER.getKeyName(), AURORA_POSTGRES_USERNAME); validProp.setProperty(PropertyKey.PASSWORD.getKeyName(), AURORA_POSTGRES_PASSWORD); - final Connection validConn = connectToInstance(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT, validProp); + final Connection validConn = + connectToInstance(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT, validProp); validConn.close(); final Properties invalidProp = initDefaultProps(); invalidProp.setProperty(PropertyKey.USER.getKeyName(), "INVALID_" + AURORA_POSTGRES_USERNAME); - invalidProp.setProperty(PropertyKey.PASSWORD.getKeyName(), "INVALID_" + AURORA_POSTGRES_PASSWORD); + invalidProp.setProperty( + PropertyKey.PASSWORD.getKeyName(), "INVALID_" + AURORA_POSTGRES_PASSWORD); assertThrows( - SQLException.class, - () -> connectToInstance(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT, invalidProp) - ); + SQLException.class, + () -> connectToInstance(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT, invalidProp)); - final Connection validConn2 = connectToInstance(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT, validProp); + final Connection validConn2 = + connectToInstance(POSTGRES_INSTANCE_1_URL, AURORA_POSTGRES_PORT, validProp); validConn2.close(); } - /** - * Current writer dies, no available reader instance, connection fails. - */ + /** Current writer dies, no available reader instance, connection fails. */ @Test public void test_writerConnectionFailsDueToNoReader() throws SQLException, IOException { @@ -335,20 +352,22 @@ public void test_writerConnectionFailsDueToNoReader() throws SQLException, IOExc Properties props = initDefaultProxiedProps(); props.setProperty("failoverTimeoutMs", "10000"); - try (Connection conn = connectToInstance( + try (Connection conn = + connectToInstance( currentWriterId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, POSTGRES_PROXY_PORT, props)) { // Put all but writer down first - proxyMap.forEach((instance, proxy) -> { - if (!instance.equalsIgnoreCase(currentWriterId)) { - try { - containerHelper.disableConnectivity(proxy); - } catch (IOException e) { - fail("Toxics were already set, should not happen"); - } - } - }); + proxyMap.forEach( + (instance, proxy) -> { + if (!instance.equalsIgnoreCase(currentWriterId)) { + try { + containerHelper.disableConnectivity(proxy); + } catch (IOException e) { + fail("Toxics were already set, should not happen"); + } + } + }); // Crash the writer now final Proxy proxyInstance = proxyMap.get(currentWriterId); @@ -362,25 +381,29 @@ public void test_writerConnectionFailsDueToNoReader() throws SQLException, IOExc // (SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE) assertFirstQueryThrows(conn, "08001"); } finally { - proxyMap.forEach((instance, proxy) -> { - assertNotNull(proxy, "Proxy isn't found for " + instance); - containerHelper.enableConnectivity(proxy); - }); + proxyMap.forEach( + (instance, proxy) -> { + assertNotNull(proxy, "Proxy isn't found for " + instance); + containerHelper.enableConnectivity(proxy); + }); } } /** - * Current reader dies, after failing to connect to several reader instances, failover to another reader. + * Current reader dies, after failing to connect to several reader instances, failover to another + * reader. */ @Test - public void test_failFromReaderToReaderWithSomeReadersAreDown() - throws SQLException, IOException { + public void test_failFromReaderToReaderWithSomeReadersAreDown() throws SQLException, IOException { assertTrue(clusterSize >= 3, "Minimal cluster configuration: 1 writer + 2 readers"); final String readerNode = instanceIDs[1]; Properties props = initDefaultProxiedProps(); - try (Connection conn = connectToInstance(readerNode + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, - POSTGRES_PROXY_PORT, props)) { + try (Connection conn = + connectToInstance( + readerNode + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, + POSTGRES_PROXY_PORT, + props)) { // First kill all reader instances except one for (int i = 1; i < clusterSize - 1; i++) { final String instanceId = instanceIDs[i]; @@ -398,14 +421,14 @@ public void test_failFromReaderToReaderWithSomeReadersAreDown() // instance (Instance1). final String currentConnectionId = queryInstanceId(conn); assertTrue( - currentConnectionId.equals(instanceIDs[clusterSize - 1]) // Last reader - || currentConnectionId.equals(instanceIDs[0])); // Writer + currentConnectionId.equals(instanceIDs[clusterSize - 1]) // Last reader + || currentConnectionId.equals(instanceIDs[0])); // Writer } } /** - * Current reader dies, failover to another reader repeat to loop through instances in the cluster testing ability to - * revive previously down reader instance. + * Current reader dies, failover to another reader repeat to loop through instances in the cluster + * testing ability to revive previously down reader instance. */ @Test @Disabled @@ -418,8 +441,11 @@ public void test_failoverBackToThePreviouslyDownReader() throws Exception { // Connect to reader (Instance2). Properties props = initDefaultProxiedProps(); - try (Connection conn = connectToInstance(firstReaderInstanceId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, - POSTGRES_PROXY_PORT, props)) { + try (Connection conn = + connectToInstance( + firstReaderInstanceId + DB_CONN_STR_SUFFIX + PROXIED_DOMAIN_NAME_SUFFIX, + POSTGRES_PROXY_PORT, + props)) { conn.setReadOnly(true); // Start crashing reader (Instance2). @@ -452,7 +478,9 @@ public void test_failoverBackToThePreviouslyDownReader() throws Exception { readerInstanceIds.remove(secondReaderInstanceId); readerInstanceIds.remove(thirdReaderInstanceId); - final String fourthInstanceId = readerInstanceIds.stream().findFirst() + final String fourthInstanceId = + readerInstanceIds.stream() + .findFirst() .orElseThrow(() -> new Exception("Empty instance Id")); // Crash the fourth reader instance. @@ -478,19 +506,20 @@ public void test_failoverBackToThePreviouslyDownReader() throws Exception { final String lastInstanceId = queryInstanceId(conn); assertTrue( - firstReaderInstanceId.equals(lastInstanceId) - || secondReaderInstanceId.equals(lastInstanceId)); + firstReaderInstanceId.equals(lastInstanceId) + || secondReaderInstanceId.equals(lastInstanceId)); } } @Test public void testSuccessOpenConnection() throws SQLException { - final String url = buildConnectionString( - DB_CONN_STR_PREFIX, - POSTGRES_INSTANCE_1_URL, - String.valueOf(AURORA_POSTGRES_PORT), - AURORA_POSTGRES_DB); + final String url = + buildConnectionString( + DB_CONN_STR_PREFIX, + POSTGRES_INSTANCE_1_URL, + String.valueOf(AURORA_POSTGRES_PORT), + AURORA_POSTGRES_DB); Properties props = new Properties(); props.setProperty("user", AURORA_POSTGRES_USERNAME); @@ -508,7 +537,7 @@ public void testSuccessOpenConnection() throws SQLException { @Test public void testSuccessOpenConnectionNoPort() throws SQLException { - final String url = DB_CONN_STR_PREFIX + POSTGRES_INSTANCE_1_URL + "/" + AURORA_POSTGRES_DB; + final String url = DB_CONN_STR_PREFIX + POSTGRES_INSTANCE_1_URL + "/" + AURORA_POSTGRES_DB; Properties props = new Properties(); props.setProperty("user", AURORA_POSTGRES_USERNAME); @@ -540,12 +569,9 @@ public void testFailedHost() { Properties props = new Properties(); props.setProperty("user", AURORA_POSTGRES_USERNAME); props.setProperty("password", AURORA_POSTGRES_PASSWORD); - String url = buildConnectionString( - DB_CONN_STR_PREFIX, - "", - String.valueOf(AURORA_POSTGRES_PORT), - AURORA_POSTGRES_DB); - assertThrows(RuntimeException.class, () -> connectToInstanceCustomUrl( - url, props)); + String url = + buildConnectionString( + DB_CONN_STR_PREFIX, "", String.valueOf(AURORA_POSTGRES_PORT), AURORA_POSTGRES_DB); + assertThrows(RuntimeException.class, () -> connectToInstanceCustomUrl(url, props)); } } diff --git a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresTestSuite.java b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresTestSuite.java index f8ade937f..369fd55a7 100644 --- a/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresTestSuite.java +++ b/wrapper/src/test/java/integration/container/aurora/postgres/AuroraPostgresTestSuite.java @@ -23,8 +23,8 @@ // To add additional tests, append it inside SelectClasses, comma-separated @Suite @SelectClasses({ - AuroraPostgresIntegrationTest.class, - AuroraPostgresFailoverTest.class, - AuroraPostgresDataSourceTest.class + AuroraPostgresIntegrationTest.class, + AuroraPostgresFailoverTest.class, + AuroraPostgresDataSourceTest.class }) public class AuroraPostgresTestSuite {} diff --git a/wrapper/src/test/java/integration/container/standard/mysql/DataCachePluginTests.java b/wrapper/src/test/java/integration/container/standard/mysql/DataCachePluginTests.java index 1a4afd4d8..c6b6c7585 100644 --- a/wrapper/src/test/java/integration/container/standard/mysql/DataCachePluginTests.java +++ b/wrapper/src/test/java/integration/container/standard/mysql/DataCachePluginTests.java @@ -87,7 +87,8 @@ public void testQueryCacheable() throws SQLException { // The following SQL statement isn't in the cache so data is fetched from DB Statement statementFromDb = conn.createStatement(); - ResultSet resultSetFromDb = statementFromDb.executeQuery("select id, name from testTable where id > 0"); + ResultSet resultSetFromDb = + statementFromDb.executeQuery("select id, name from testTable where id > 0"); assertTrue(resultSetFromDb.next()); assertEquals(10, resultSetFromDb.getObject(1)); assertEquals("name10", resultSetFromDb.getObject(2)); diff --git a/wrapper/src/test/java/integration/container/standard/mysql/DataSourceTests.java b/wrapper/src/test/java/integration/container/standard/mysql/DataSourceTests.java index 7e82ab3d3..f6383212b 100644 --- a/wrapper/src/test/java/integration/container/standard/mysql/DataSourceTests.java +++ b/wrapper/src/test/java/integration/container/standard/mysql/DataSourceTests.java @@ -61,8 +61,7 @@ public void testOpenConnectionWithMysqlDataSourceClassName() throws SQLException @Disabled // TODO: check public void testOpenConnectionWithMysqlUrl() throws SQLException { ProxyDriverDataSource ds = new ProxyDriverDataSource(); - ds.setJdbcUrl( - "jdbc:mysql://" + STANDARD_MYSQL_HOST + "/" + STANDARD_MYSQL_DB); + ds.setJdbcUrl("jdbc:mysql://" + STANDARD_MYSQL_HOST + "/" + STANDARD_MYSQL_DB); Connection conn = ds.getConnection(STANDARD_MYSQL_USERNAME, STANDARD_MYSQL_PASSWORD); diff --git a/wrapper/src/test/java/integration/container/standard/mysql/LogQueryPluginTests.java b/wrapper/src/test/java/integration/container/standard/mysql/LogQueryPluginTests.java index 8240d72d4..47b9ae2b8 100644 --- a/wrapper/src/test/java/integration/container/standard/mysql/LogQueryPluginTests.java +++ b/wrapper/src/test/java/integration/container/standard/mysql/LogQueryPluginTests.java @@ -36,8 +36,7 @@ public class LogQueryPluginTests extends StandardMysqlBaseTest { @Test - public void testStatementExecuteQueryWithArg() - throws SQLException, UnsupportedEncodingException { + public void testStatementExecuteQueryWithArg() throws SQLException, UnsupportedEncodingException { Logger logger = Logger.getLogger(""); // get root logger ByteArrayOutputStream os = new ByteArrayOutputStream(); diff --git a/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlBaseTest.java b/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlBaseTest.java index ff69114f6..67199854a 100644 --- a/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlBaseTest.java +++ b/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlBaseTest.java @@ -43,7 +43,8 @@ public class StandardMysqlBaseTest { protected static ToxiproxyClient toxiproxyClient; protected static final int TOXIPROXY_CONTROL_PORT = 8474; - protected static final String PROXIED_DOMAIN_NAME_SUFFIX = System.getenv("PROXIED_DOMAIN_NAME_SUFFIX"); + protected static final String PROXIED_DOMAIN_NAME_SUFFIX = + System.getenv("PROXIED_DOMAIN_NAME_SUFFIX"); protected static final String PROXY_PORT = System.getenv("PROXY_PORT"); protected static Proxy proxy; protected static final Map proxyMap = new HashMap<>(); @@ -68,14 +69,20 @@ public void setUpEach() { proxyMap.forEach((instance, proxy) -> containerHelper.enableConnectivity(proxy)); } - protected static Proxy getProxy(ToxiproxyClient proxyClient, String host, int port) throws IOException { + protected static Proxy getProxy(ToxiproxyClient proxyClient, String host, int port) + throws IOException { final String upstream = host + ":" + port; return proxyClient.getProxy(upstream); } protected String getUrl() { String url = - DB_CONN_STR_PREFIX + STANDARD_MYSQL_HOST + ":" + STANDARD_MYSQL_PORT + "/" + STANDARD_MYSQL_DB; + DB_CONN_STR_PREFIX + + STANDARD_MYSQL_HOST + + ":" + + STANDARD_MYSQL_PORT + + "/" + + STANDARD_MYSQL_DB; return url; } @@ -84,8 +91,14 @@ protected Connection connect() throws SQLException { } protected String getProxiedUrl() { - String url = DB_CONN_STR_PREFIX + STANDARD_MYSQL_HOST + PROXIED_DOMAIN_NAME_SUFFIX + ":" + PROXY_PORT + "/" - + STANDARD_MYSQL_DB; + String url = + DB_CONN_STR_PREFIX + + STANDARD_MYSQL_HOST + + PROXIED_DOMAIN_NAME_SUFFIX + + ":" + + PROXY_PORT + + "/" + + STANDARD_MYSQL_DB; return url; } diff --git a/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlIntegrationTest.java b/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlIntegrationTest.java index 750ab8d17..e84415732 100644 --- a/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlIntegrationTest.java +++ b/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlIntegrationTest.java @@ -100,9 +100,12 @@ public void testOpenConnectionWithUnknownProfile() { Properties props = initDefaultPropsNoTimeouts(); props.setProperty("proxyDriverProfileName", "unknownProfile"); - SQLException actualException = assertThrows(SQLException.class, () -> { - DriverManager.getConnection(getUrl(), props); - }); + SQLException actualException = + assertThrows( + SQLException.class, + () -> { + DriverManager.getConnection(getUrl(), props); + }); assertTrue(actualException.getMessage().contains("unknownProfile")); } @@ -114,8 +117,8 @@ public void testOpenConnectionWithProfile() throws SQLException { props.setProperty("proxyDriverProfileName", "testProfile"); DriverConfigurationProfiles.clear(); - DriverConfigurationProfiles.addOrReplaceProfile("testProfile", - Arrays.asList(ExecutionTimeConnectionPluginFactory.class)); + DriverConfigurationProfiles.addOrReplaceProfile( + "testProfile", Arrays.asList(ExecutionTimeConnectionPluginFactory.class)); Connection conn = DriverManager.getConnection(getUrl(), props); diff --git a/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlTestSuite.java b/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlTestSuite.java index dc652151d..1a8a285c4 100644 --- a/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlTestSuite.java +++ b/wrapper/src/test/java/integration/container/standard/mysql/StandardMysqlTestSuite.java @@ -23,11 +23,11 @@ // To add additional tests, append it inside SelectClasses, comma-separated @Suite @SelectClasses({ - StandardMysqlIntegrationTest.class, - DataCachePluginTests.class, - DataSourceTests.class, - HikariTests.class, - LogQueryPluginTests.class, - SpringTests.class + StandardMysqlIntegrationTest.class, + DataCachePluginTests.class, + DataSourceTests.class, + HikariTests.class, + LogQueryPluginTests.class, + SpringTests.class }) public class StandardMysqlTestSuite {} diff --git a/wrapper/src/test/java/integration/container/standard/postgres/LogLevelTests.java b/wrapper/src/test/java/integration/container/standard/postgres/LogLevelTests.java index b636d9bbd..5ea0bb492 100644 --- a/wrapper/src/test/java/integration/container/standard/postgres/LogLevelTests.java +++ b/wrapper/src/test/java/integration/container/standard/postgres/LogLevelTests.java @@ -47,7 +47,8 @@ public void testStandardStreams() { @Test public void testSlf4j() throws IOException { org.slf4j.Logger logger = - LoggerFactory.getLogger("integration.container.standard.postgres.StandardPostgresIntegrationTest"); + LoggerFactory.getLogger( + "integration.container.standard.postgres.StandardPostgresIntegrationTest"); logger.debug("StandardPostgresIntegrationTest debug"); logger.trace("StandardPostgresIntegrationTest trace"); diff --git a/wrapper/src/test/java/integration/container/standard/postgres/LogQueryPluginTests.java b/wrapper/src/test/java/integration/container/standard/postgres/LogQueryPluginTests.java index 25625600b..a9ab878c6 100644 --- a/wrapper/src/test/java/integration/container/standard/postgres/LogQueryPluginTests.java +++ b/wrapper/src/test/java/integration/container/standard/postgres/LogQueryPluginTests.java @@ -36,8 +36,7 @@ public class LogQueryPluginTests extends StandardPostgresBaseTest { @Test - public void testStatementExecuteQueryWithArg() - throws SQLException, UnsupportedEncodingException { + public void testStatementExecuteQueryWithArg() throws SQLException, UnsupportedEncodingException { Logger logger = Logger.getLogger(""); // get root logger ByteArrayOutputStream os = new ByteArrayOutputStream(); diff --git a/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresBaseTest.java b/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresBaseTest.java index bba17f730..b0910a221 100644 --- a/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresBaseTest.java +++ b/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresBaseTest.java @@ -34,16 +34,20 @@ public class StandardPostgresBaseTest { protected static final String DB_CONN_STR_PREFIX = "aws-proxy-jdbc:postgresql://"; protected static final String STANDARD_POSTGRES_HOST = System.getenv("STANDARD_POSTGRES_HOST"); - protected static final int STANDARD_POSTGRES_PORT = Integer.parseInt(System.getenv("STANDARD_POSTGRES_PORT")); + protected static final int STANDARD_POSTGRES_PORT = + Integer.parseInt(System.getenv("STANDARD_POSTGRES_PORT")); protected static final String STANDARD_POSTGRES_DB = System.getenv("STANDARD_POSTGRES_DB"); - protected static final String STANDARD_POSTGRES_USERNAME = System.getenv("STANDARD_POSTGRES_USERNAME"); - protected static final String STANDARD_POSTGRES_PASSWORD = System.getenv("STANDARD_POSTGRES_PASSWORD"); + protected static final String STANDARD_POSTGRES_USERNAME = + System.getenv("STANDARD_POSTGRES_USERNAME"); + protected static final String STANDARD_POSTGRES_PASSWORD = + System.getenv("STANDARD_POSTGRES_PASSWORD"); protected static final String TOXIPROXY_HOST = System.getenv("TOXIPROXY_HOST"); protected static ToxiproxyClient toxiproxyClient; protected static final int TOXIPROXY_CONTROL_PORT = 8474; - protected static final String PROXIED_DOMAIN_NAME_SUFFIX = System.getenv("PROXIED_DOMAIN_NAME_SUFFIX"); + protected static final String PROXIED_DOMAIN_NAME_SUFFIX = + System.getenv("PROXIED_DOMAIN_NAME_SUFFIX"); protected static final String PROXY_PORT = System.getenv("PROXY_PORT"); protected static Proxy proxy; protected static final Map proxyMap = new HashMap<>(); @@ -70,14 +74,20 @@ public void setUpEach() { proxyMap.forEach((instance, proxy) -> containerHelper.enableConnectivity(proxy)); } - protected static Proxy getProxy(ToxiproxyClient proxyClient, String host, int port) throws IOException { + protected static Proxy getProxy(ToxiproxyClient proxyClient, String host, int port) + throws IOException { final String upstream = host + ":" + port; return proxyClient.getProxy(upstream); } protected String getUrl() { String url = - DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST + ":" + STANDARD_POSTGRES_PORT + "/" + STANDARD_POSTGRES_DB; + DB_CONN_STR_PREFIX + + STANDARD_POSTGRES_HOST + + ":" + + STANDARD_POSTGRES_PORT + + "/" + + STANDARD_POSTGRES_DB; return url; } @@ -86,8 +96,14 @@ protected Connection connect() throws SQLException { } protected String getProxiedUrl() { - String url = DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST + PROXIED_DOMAIN_NAME_SUFFIX + ":" + PROXY_PORT + "/" - + STANDARD_POSTGRES_DB; + String url = + DB_CONN_STR_PREFIX + + STANDARD_POSTGRES_HOST + + PROXIED_DOMAIN_NAME_SUFFIX + + ":" + + PROXY_PORT + + "/" + + STANDARD_POSTGRES_DB; return url; } diff --git a/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresDataSourceTest.java b/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresDataSourceTest.java index 9fc61bb17..ff2be758c 100644 --- a/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresDataSourceTest.java +++ b/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresDataSourceTest.java @@ -153,9 +153,7 @@ public void testConnectionWithDataSourceClassNameMissingUser() { targetDataSourceProps.setProperty("databaseName", STANDARD_POSTGRES_DB); ds.setTargetDataSourceProperties(targetDataSourceProps); - assertThrows( - PSQLException.class, - () -> ds.getConnection("", STANDARD_POSTGRES_PASSWORD)); + assertThrows(PSQLException.class, () -> ds.getConnection("", STANDARD_POSTGRES_PASSWORD)); } @Test @@ -173,9 +171,7 @@ public void testConnectionWithDataSourceClassNameMissingPassword() { targetDataSourceProps.setProperty("databaseName", STANDARD_POSTGRES_DB); ds.setTargetDataSourceProperties(targetDataSourceProps); - assertThrows( - PSQLException.class, - () -> ds.getConnection(STANDARD_POSTGRES_USERNAME, "")); + assertThrows(PSQLException.class, () -> ds.getConnection(STANDARD_POSTGRES_USERNAME, "")); } @Test @@ -233,10 +229,14 @@ public void testConnectionWithDataSourceClassNameUsingUrlWithCredentials() throw ds.setJdbcUrl( DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST - + ":" + STANDARD_POSTGRES_PORT + "/" + + ":" + + STANDARD_POSTGRES_PORT + + "/" + STANDARD_POSTGRES_DB - + "?user=" + STANDARD_POSTGRES_USERNAME - + "&password=" + STANDARD_POSTGRES_PASSWORD); + + "?user=" + + STANDARD_POSTGRES_USERNAME + + "&password=" + + STANDARD_POSTGRES_PASSWORD); Connection conn = ds.getConnection(); @@ -261,9 +261,11 @@ public void testConnectionWithDataSourceClassNameUsingUrlWithPort() throws SQLEx ds.setJdbcUrl( DB_CONN_STR_PREFIX - + STANDARD_POSTGRES_HOST - + ":" + STANDARD_POSTGRES_PORT + "/" - + STANDARD_POSTGRES_DB); + + STANDARD_POSTGRES_HOST + + ":" + + STANDARD_POSTGRES_PORT + + "/" + + STANDARD_POSTGRES_DB); Connection conn = ds.getConnection(STANDARD_POSTGRES_USERNAME, STANDARD_POSTGRES_PASSWORD); @@ -340,9 +342,11 @@ public void testConnectionWithUrl() throws SQLException { ds.setPortPropertyName("port"); ds.setJdbcUrl( DB_CONN_STR_PREFIX - + STANDARD_POSTGRES_HOST - + ":" + STANDARD_POSTGRES_PORT + "/" - + STANDARD_POSTGRES_DB); + + STANDARD_POSTGRES_HOST + + ":" + + STANDARD_POSTGRES_PORT + + "/" + + STANDARD_POSTGRES_DB); Connection conn = ds.getConnection(STANDARD_POSTGRES_USERNAME, STANDARD_POSTGRES_PASSWORD); @@ -362,10 +366,14 @@ public void testConnectionWithUrlWithCredentials() throws SQLException { ds.setJdbcUrl( DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST - + ":" + STANDARD_POSTGRES_PORT + "/" + + ":" + + STANDARD_POSTGRES_PORT + + "/" + STANDARD_POSTGRES_DB - + "?user=" + STANDARD_POSTGRES_USERNAME - + "&password=" + STANDARD_POSTGRES_PASSWORD); + + "?user=" + + STANDARD_POSTGRES_USERNAME + + "&password=" + + STANDARD_POSTGRES_PASSWORD); Connection conn = ds.getConnection(); @@ -413,9 +421,7 @@ public void testConnectionWithUrlMissingUser() { ds.setPortPropertyName("port"); ds.setJdbcUrl(DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST + ":" + STANDARD_POSTGRES_PORT + "/"); - assertThrows( - PSQLException.class, - () -> ds.getConnection("", STANDARD_POSTGRES_PASSWORD)); + assertThrows(PSQLException.class, () -> ds.getConnection("", STANDARD_POSTGRES_PASSWORD)); } @Test @@ -426,9 +432,7 @@ public void testConnectionWithUrlMissingPassword() { ds.setPortPropertyName("port"); ds.setJdbcUrl(DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST + ":" + STANDARD_POSTGRES_PORT + "/"); - assertThrows( - PSQLException.class, - () -> ds.getConnection(STANDARD_POSTGRES_USERNAME, "")); + assertThrows(PSQLException.class, () -> ds.getConnection(STANDARD_POSTGRES_USERNAME, "")); } @Test @@ -436,9 +440,11 @@ public void testConnectionWithUrlMissingPropertyNames() { ProxyDriverDataSource ds = new ProxyDriverDataSource(); ds.setJdbcUrl( DB_CONN_STR_PREFIX - + STANDARD_POSTGRES_HOST - + ":" + STANDARD_POSTGRES_PORT + "/" - + STANDARD_POSTGRES_DB); + + STANDARD_POSTGRES_HOST + + ":" + + STANDARD_POSTGRES_PORT + + "/" + + STANDARD_POSTGRES_DB); assertThrows( PSQLException.class, diff --git a/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresIntegrationTest.java b/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresIntegrationTest.java index c53b9fe20..6caf6fb56 100644 --- a/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresIntegrationTest.java +++ b/wrapper/src/test/java/integration/container/standard/postgres/StandardPostgresIntegrationTest.java @@ -37,60 +37,54 @@ public class StandardPostgresIntegrationTest extends StandardPostgresBaseTest { protected static String buildConnectionString( - String connStringPrefix, - String host, - String port, - String databaseName) { + String connStringPrefix, String host, String port, String databaseName) { return connStringPrefix + host + ":" + port + "/" + databaseName; } private static Stream testConnectionParameters() { return Stream.of( // missing connection prefix - Arguments.of(buildConnectionString( - "", - STANDARD_POSTGRES_HOST, - String.valueOf(STANDARD_POSTGRES_PORT), - STANDARD_POSTGRES_DB)), + Arguments.of( + buildConnectionString( + "", + STANDARD_POSTGRES_HOST, + String.valueOf(STANDARD_POSTGRES_PORT), + STANDARD_POSTGRES_DB)), // missing port - Arguments.of(buildConnectionString( - DB_CONN_STR_PREFIX, - STANDARD_POSTGRES_HOST, - "", - STANDARD_POSTGRES_DB)), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, STANDARD_POSTGRES_HOST, "", STANDARD_POSTGRES_DB)), // incorrect database name - Arguments.of(buildConnectionString( - DB_CONN_STR_PREFIX, - STANDARD_POSTGRES_HOST, - String.valueOf(STANDARD_POSTGRES_PORT), - "failedDatabaseNameTest")), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, + STANDARD_POSTGRES_HOST, + String.valueOf(STANDARD_POSTGRES_PORT), + "failedDatabaseNameTest")), // missing "/" at end of URL - Arguments.of(DB_CONN_STR_PREFIX - + STANDARD_POSTGRES_HOST - + ":" - + STANDARD_POSTGRES_PORT) - ); + Arguments.of(DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST + ":" + STANDARD_POSTGRES_PORT)); } private static Stream testPropertiesParameters() { return Stream.of( // missing username - Arguments.of(buildConnectionString( - DB_CONN_STR_PREFIX, - STANDARD_POSTGRES_HOST, - String.valueOf(STANDARD_POSTGRES_PORT), - STANDARD_POSTGRES_DB), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, + STANDARD_POSTGRES_HOST, + String.valueOf(STANDARD_POSTGRES_PORT), + STANDARD_POSTGRES_DB), "", STANDARD_POSTGRES_PASSWORD), // missing password - Arguments.of(buildConnectionString( - DB_CONN_STR_PREFIX, - STANDARD_POSTGRES_HOST, - String.valueOf(STANDARD_POSTGRES_PORT), - STANDARD_POSTGRES_DB), + Arguments.of( + buildConnectionString( + DB_CONN_STR_PREFIX, + STANDARD_POSTGRES_HOST, + String.valueOf(STANDARD_POSTGRES_PORT), + STANDARD_POSTGRES_DB), STANDARD_POSTGRES_USERNAME, - "") - ); + "")); } @Test @@ -124,8 +118,7 @@ public void testSuccessOpenConnection() throws SQLException { @Test public void testSuccessOpenConnectionNoPort() throws SQLException { - String url = - DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST + "/" + STANDARD_POSTGRES_DB; + String url = DB_CONN_STR_PREFIX + STANDARD_POSTGRES_HOST + "/" + STANDARD_POSTGRES_DB; try (Connection conn = connectCustomUrl(url, initDefaultProps())) { assertTrue(conn instanceof ConnectionWrapper); @@ -156,11 +149,9 @@ public void testFailedProperties(String url, String username, String password) { @Test public void testFailedHost() { - String url = buildConnectionString( - DB_CONN_STR_PREFIX, - "", - String.valueOf(STANDARD_POSTGRES_PORT), - STANDARD_POSTGRES_DB); + String url = + buildConnectionString( + DB_CONN_STR_PREFIX, "", String.valueOf(STANDARD_POSTGRES_PORT), STANDARD_POSTGRES_DB); assertThrows(RuntimeException.class, () -> connectCustomUrl(url, initDefaultProps())); } } diff --git a/wrapper/src/test/java/integration/host/AuroraPostgresContainerTest.java b/wrapper/src/test/java/integration/host/AuroraPostgresContainerTest.java index 9a494c29f..183e46bcf 100644 --- a/wrapper/src/test/java/integration/host/AuroraPostgresContainerTest.java +++ b/wrapper/src/test/java/integration/host/AuroraPostgresContainerTest.java @@ -97,7 +97,8 @@ public class AuroraPostgresContainerTest { private static final boolean TEST_WITH_EXISTING_DB = EXISTING_DB_CONN_SUFFIX != null; private static final ContainerHelper containerHelper = new ContainerHelper(); - private static final AuroraTestUtility auroraUtil = new AuroraTestUtility(AURORA_POSTGRES_DB_REGION); + private static final AuroraTestUtility auroraUtil = + new AuroraTestUtility(AURORA_POSTGRES_DB_REGION); @BeforeAll static void setUp() throws SQLException, InterruptedException, UnknownHostException { @@ -108,8 +109,12 @@ static void setUp() throws SQLException, InterruptedException, UnknownHostExcept if (TEST_WITH_EXISTING_DB) { dbConnStrSuffix = EXISTING_DB_CONN_SUFFIX; } else { - dbConnStrSuffix = auroraUtil.createCluster(AURORA_POSTGRES_USERNAME, AURORA_POSTGRES_PASSWORD, AURORA_POSTGRES_DB, - AURORA_POSTGRES_CLUSTER_IDENTIFIER); + dbConnStrSuffix = + auroraUtil.createCluster( + AURORA_POSTGRES_USERNAME, + AURORA_POSTGRES_PASSWORD, + AURORA_POSTGRES_DB, + AURORA_POSTGRES_CLUSTER_IDENTIFIER); runnerIP = auroraUtil.getPublicIPAddress(); auroraUtil.ec2AuthorizeIP(runnerIP); } @@ -239,8 +244,7 @@ protected static GenericContainer initializeTestContainer( // Add proxies container.addEnv( - "TOXIPROXY_INSTANCE_" + (i + 1) + "_NETWORK_ALIAS", - "toxiproxy-instance-" + (i + 1)); + "TOXIPROXY_INSTANCE_" + (i + 1) + "_NETWORK_ALIAS", "toxiproxy-instance-" + (i + 1)); } container.addEnv("AURORA_POSTGRES_PORT", Integer.toString(AURORA_POSTGRES_PORT)); container.addEnv("PROXIED_DOMAIN_NAME_SUFFIX", PROXIED_DOMAIN_NAME_SUFFIX); diff --git a/wrapper/src/test/java/integration/host/StandardMysqlContainerTest.java b/wrapper/src/test/java/integration/host/StandardMysqlContainerTest.java index d4c9d4974..5376a0e61 100644 --- a/wrapper/src/test/java/integration/host/StandardMysqlContainerTest.java +++ b/wrapper/src/test/java/integration/host/StandardMysqlContainerTest.java @@ -38,13 +38,16 @@ public class StandardMysqlContainerTest { private static final String STANDARD_MYSQL_DB = !StringUtils.isNullOrEmpty(System.getenv("STANDARD_MYSQL_DB")) - ? System.getenv("STANDARD_MYSQL_DB") : "test"; + ? System.getenv("STANDARD_MYSQL_DB") + : "test"; private static final String STANDARD_MYSQL_USERNAME = !StringUtils.isNullOrEmpty(System.getenv("STANDARD_MYSQL_USERNAME")) - ? System.getenv("STANDARD_MYSQL_USERNAME") : "test"; + ? System.getenv("STANDARD_MYSQL_USERNAME") + : "test"; private static final String STANDARD_MYSQL_PASSWORD = !StringUtils.isNullOrEmpty(System.getenv("STANDARD_MYSQL_PASSWORD")) - ? System.getenv("STANDARD_MYSQL_PASSWORD") : "test"; + ? System.getenv("STANDARD_MYSQL_PASSWORD") + : "test"; private static MySQLContainer mysqlContainer; private static GenericContainer integrationTestContainer; @@ -63,15 +66,22 @@ static void setUp() throws SQLException, ClassNotFoundException { network = Network.newNetwork(); - mysqlContainer = containerHelper.createMysqlContainer(network, STANDARD_MYSQL_HOST, - STANDARD_MYSQL_DB, STANDARD_MYSQL_USERNAME, STANDARD_MYSQL_PASSWORD); + mysqlContainer = + containerHelper.createMysqlContainer( + network, + STANDARD_MYSQL_HOST, + STANDARD_MYSQL_DB, + STANDARD_MYSQL_USERNAME, + STANDARD_MYSQL_PASSWORD); mysqlContainer.start(); proxyContainer = - containerHelper.createProxyContainer(network, STANDARD_MYSQL_HOST, PROXIED_DOMAIN_NAME_SUFFIX); + containerHelper.createProxyContainer( + network, STANDARD_MYSQL_HOST, PROXIED_DOMAIN_NAME_SUFFIX); proxyContainer.start(); - mysqlProxyPort = containerHelper.createInstanceProxy(STANDARD_MYSQL_HOST, proxyContainer, - STANDARD_MYSQL_PORT); + mysqlProxyPort = + containerHelper.createInstanceProxy( + STANDARD_MYSQL_HOST, proxyContainer, STANDARD_MYSQL_PORT); integrationTestContainer = createTestContainer(); integrationTestContainer.start(); @@ -99,7 +109,8 @@ public void debugTestInContainer() } protected static GenericContainer createTestContainer() { - return containerHelper.createTestContainer("aws/rds-test-container") + return containerHelper + .createTestContainer("aws/rds-test-container") .withNetworkAliases(STANDARD_TEST_RUNNER_NAME) .withNetwork(network) .withEnv("STANDARD_MYSQL_HOST", STANDARD_MYSQL_HOST) diff --git a/wrapper/src/test/java/integration/host/StandardPostgresContainerTest.java b/wrapper/src/test/java/integration/host/StandardPostgresContainerTest.java index 97719bee0..f899e515a 100644 --- a/wrapper/src/test/java/integration/host/StandardPostgresContainerTest.java +++ b/wrapper/src/test/java/integration/host/StandardPostgresContainerTest.java @@ -38,13 +38,16 @@ public class StandardPostgresContainerTest { private static final String STANDARD_POSTGRES_DB = !StringUtils.isNullOrEmpty(System.getenv("STANDARD_POSTGRES_DB")) - ? System.getenv("STANDARD_POSTGRES_DB") : "test-db"; + ? System.getenv("STANDARD_POSTGRES_DB") + : "test-db"; private static final String STANDARD_POSTGRES_USERNAME = !StringUtils.isNullOrEmpty(System.getenv("STANDARD_POSTGRES_USERNAME")) - ? System.getenv("STANDARD_POSTGRES_USERNAME") : "test-user"; + ? System.getenv("STANDARD_POSTGRES_USERNAME") + : "test-user"; private static final String STANDARD_POSTGRES_PASSWORD = !StringUtils.isNullOrEmpty(System.getenv("STANDARD_POSTGRES_PASSWORD")) - ? System.getenv("STANDARD_POSTGRES_PASSWORD") : "test-password"; + ? System.getenv("STANDARD_POSTGRES_PASSWORD") + : "test-password"; private static PostgreSQLContainer postgresContainer; private static GenericContainer integrationTestContainer; @@ -65,15 +68,22 @@ static void setUp() throws SQLException { network = Network.newNetwork(); - postgresContainer = containerHelper.createPostgresContainer(network, STANDARD_POSTGRES_HOST, - STANDARD_POSTGRES_DB, STANDARD_POSTGRES_USERNAME, STANDARD_POSTGRES_PASSWORD); + postgresContainer = + containerHelper.createPostgresContainer( + network, + STANDARD_POSTGRES_HOST, + STANDARD_POSTGRES_DB, + STANDARD_POSTGRES_USERNAME, + STANDARD_POSTGRES_PASSWORD); postgresContainer.start(); proxyContainer = - containerHelper.createProxyContainer(network, STANDARD_POSTGRES_HOST, PROXIED_DOMAIN_NAME_SUFFIX); + containerHelper.createProxyContainer( + network, STANDARD_POSTGRES_HOST, PROXIED_DOMAIN_NAME_SUFFIX); proxyContainer.start(); - postgresProxyPort = containerHelper.createInstanceProxy(STANDARD_POSTGRES_HOST, proxyContainer, - STANDARD_POSTGRES_PORT); + postgresProxyPort = + containerHelper.createInstanceProxy( + STANDARD_POSTGRES_HOST, proxyContainer, STANDARD_POSTGRES_PORT); integrationTestContainer = createTestContainer(); integrationTestContainer.start(); @@ -101,7 +111,8 @@ public void debugTestInContainer() } protected static GenericContainer createTestContainer() { - return containerHelper.createTestContainer("aws/rds-test-container") + return containerHelper + .createTestContainer("aws/rds-test-container") .withNetworkAliases(STANDARD_POSTGRES_TEST_RUNNER_NAME) .withNetwork(network) .withEnv("STANDARD_POSTGRES_HOST", STANDARD_POSTGRES_HOST) diff --git a/wrapper/src/test/java/integration/util/ContainerHelper.java b/wrapper/src/test/java/integration/util/ContainerHelper.java index c1b35a967..01111efbe 100644 --- a/wrapper/src/test/java/integration/util/ContainerHelper.java +++ b/wrapper/src/test/java/integration/util/ContainerHelper.java @@ -70,8 +70,8 @@ public void runTest(GenericContainer container, String task) throws IOException, InterruptedException { System.out.println("==== Container console feed ==== >>>>"); Consumer consumer = new ConsoleConsumer(); - Long exitCode = execInContainer(container, consumer, "./gradlew", task, - "--no-parallel", "--no-daemon"); + Long exitCode = + execInContainer(container, consumer, "./gradlew", task, "--no-parallel", "--no-daemon"); System.out.println("==== Container console feed ==== <<<<"); assertEquals(0, exitCode, "Some tests failed."); } @@ -80,8 +80,9 @@ public void debugTest(GenericContainer container, String task) throws IOException, InterruptedException { System.out.println("==== Container console feed ==== >>>>"); Consumer consumer = new ConsoleConsumer(); - Long exitCode = execInContainer(container, consumer, "./gradlew", task, - "--debug-jvm", "--no-parallel", "--no-daemon"); + Long exitCode = + execInContainer( + container, consumer, "./gradlew", task, "--debug-jvm", "--no-parallel", "--no-daemon"); System.out.println("==== Container console feed ==== <<<<"); assertEquals(0, exitCode, "Some tests failed."); } @@ -92,8 +93,7 @@ public GenericContainer createTestContainer(String dockerImageName) { public GenericContainer createTestContainer( String dockerImageName, String testContainerImageName) { - class FixedExposedPortContainer> - extends GenericContainer { + class FixedExposedPortContainer> extends GenericContainer { public FixedExposedPortContainer(ImageFromDockerfile withDockerfileFromBuilder) { super(withDockerfileFromBuilder); @@ -107,16 +107,16 @@ public T withFixedExposedPort(int hostPort, int containerPort) { } return new FixedExposedPortContainer<>( - new ImageFromDockerfile(dockerImageName, true) - .withDockerfileFromBuilder( - builder -> - builder - .from(testContainerImageName) - .run("mkdir", "app") - .workDir("/app") - .entryPoint("/bin/sh -c \"while true; do sleep 30; done;\"") - .expose(5005) // Exposing ports for debugger to be attached - .build())) + new ImageFromDockerfile(dockerImageName, true) + .withDockerfileFromBuilder( + builder -> + builder + .from(testContainerImageName) + .run("mkdir", "app") + .workDir("/app") + .entryPoint("/bin/sh -c \"while true; do sleep 30; done;\"") + .expose(5005) // Exposing ports for debugger to be attached + .build())) .withFixedExposedPort(5005, 5005) // Mapping container port to host .withFileSystemBind( "./build/reports/tests", @@ -191,7 +191,9 @@ protected Long execInContainer( protected boolean isRunning(InspectContainerResponse containerInfo) { try { - return containerInfo != null && containerInfo.getState() != null && containerInfo.getState().getRunning(); + return containerInfo != null + && containerInfo.getState() != null + && containerInfo.getState().getRunning(); } catch (DockerException e) { return false; } @@ -265,7 +267,7 @@ public List getAuroraInstanceEndpoints( ArrayList auroraInstances = new ArrayList<>(); try (final Connection conn = DriverManager.getConnection(connectionUrl, userName, password); - final Statement stmt = conn.createStatement()) { + final Statement stmt = conn.createStatement()) { // Get instances try (final ResultSet resultSet = stmt.executeQuery(RETRIEVE_TOPOLOGY_SQL)) { while (resultSet.next()) { @@ -284,7 +286,7 @@ public List getAuroraInstanceIds(String connectionUrl, String userName, ArrayList auroraInstances = new ArrayList<>(); try (final Connection conn = DriverManager.getConnection(connectionUrl, userName, password); - final Statement stmt = conn.createStatement()) { + final Statement stmt = conn.createStatement()) { // Get instances try (final ResultSet resultSet = stmt.executeQuery(RETRIEVE_TOPOLOGY_SQL)) { while (resultSet.next()) { @@ -315,8 +317,7 @@ public ToxiproxyContainer createProxyContainer( final Network network, String hostEndpoint, String proxyDomainNameSuffix) { return new ToxiproxyContainer(TOXIPROXY_IMAGE) .withNetwork(network) - .withNetworkAliases( - "toxiproxy-instance", hostEndpoint + proxyDomainNameSuffix); + .withNetworkAliases("toxiproxy-instance", hostEndpoint + proxyDomainNameSuffix); } // return db cluster instance proxy port @@ -371,9 +372,7 @@ public int runInContainer(String cmd) { return 1; } - /** - * Stops all traffic to and from server. - */ + /** Stops all traffic to and from server. */ public void disableConnectivity(Proxy proxy) throws IOException { proxy .toxics() @@ -384,9 +383,7 @@ public void disableConnectivity(Proxy proxy) throws IOException { .bandwidth("UP-STREAM", ToxicDirection.UPSTREAM, 0); // from driver towards database server } - /** - * Allow traffic to and from server. - */ + /** Allow traffic to and from server. */ public void enableConnectivity(Proxy proxy) { try { proxy.toxics().get("DOWN-STREAM").remove();