Refactoring/Improving source: repository 5 (slf4j) (#1605)

Signed-off-by: Marinov Avgustin <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2024-02-03 17:58:54 +02:00
committed by GitHub
parent 990d1a7545
commit f8b1910d02
12 changed files with 56 additions and 75 deletions

View File

@@ -24,13 +24,12 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
import org.awaitility.Awaitility; import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException; import org.awaitility.core.ConditionTimeoutException;
import org.eclipse.hawkbit.repository.event.remote.RemoteIdEvent; import org.eclipse.hawkbit.repository.event.remote.RemoteIdEvent;
import org.eclipse.hawkbit.repository.event.remote.RemoteTenantAwareEvent; import org.eclipse.hawkbit.repository.event.remote.RemoteTenantAwareEvent;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bus.event.RemoteApplicationEvent; import org.springframework.cloud.bus.event.RemoteApplicationEvent;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
@@ -42,8 +41,8 @@ import org.springframework.test.context.support.AbstractTestExecutionListener;
/** /**
* Test rule to setup and verify the event count for a method. * Test rule to setup and verify the event count for a method.
*/ */
@Slf4j
public class EventVerifier extends AbstractTestExecutionListener { public class EventVerifier extends AbstractTestExecutionListener {
private static final Logger LOGGER = LoggerFactory.getLogger(EventVerifier.class);
private EventCaptor eventCaptor; private EventCaptor eventCaptor;
@@ -140,10 +139,10 @@ public class EventVerifier extends AbstractTestExecutionListener {
@Override @Override
public void onApplicationEvent(final RemoteApplicationEvent event) { public void onApplicationEvent(final RemoteApplicationEvent event) {
LOGGER.debug("Received event {}", event.getClass().getSimpleName()); log.debug("Received event {}", event.getClass().getSimpleName());
if (ResetCounterMarkerEvent.class.isAssignableFrom(event.getClass())) { if (ResetCounterMarkerEvent.class.isAssignableFrom(event.getClass())) {
LOGGER.debug("Retrieving reset counter marker event - resetting counters"); log.debug("Retrieving reset counter marker event - resetting counters");
capturedEvents.clear(); capturedEvents.clear();
return; return;
} }

View File

@@ -24,6 +24,7 @@ import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository; import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
@@ -71,8 +72,6 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@@ -92,6 +91,7 @@ import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.TestExecutionListeners.MergeMode; import org.springframework.test.context.TestExecutionListeners.MergeMode;
import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.TestPropertySource;
@Slf4j
@ActiveProfiles({ "test" }) @ActiveProfiles({ "test" })
@ExtendWith({ JUnitTestLoggerExtension.class , SharedSqlTestDatabaseExtension.class }) @ExtendWith({ JUnitTestLoggerExtension.class , SharedSqlTestDatabaseExtension.class })
@WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE }) @WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE })
@@ -110,7 +110,6 @@ import org.springframework.test.context.TestPropertySource;
mergeMode = MergeMode.MERGE_WITH_DEFAULTS) mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
@TestPropertySource(properties = "spring.main.allow-bean-definition-overriding=true") @TestPropertySource(properties = "spring.main.allow-bean-definition-overriding=true")
public abstract class AbstractIntegrationTest { public abstract class AbstractIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(AbstractIntegrationTest.class);
protected static final Pageable PAGE = PageRequest.of(0, 500, Sort.by(Direction.ASC, "id")); protected static final Pageable PAGE = PageRequest.of(0, 500, Sort.by(Direction.ASC, "id"));
@@ -436,7 +435,7 @@ public abstract class AbstractIntegrationTest {
try { try {
FileUtils.cleanDirectory(new File(ARTIFACT_DIRECTORY)); FileUtils.cleanDirectory(new File(ARTIFACT_DIRECTORY));
} catch (final IOException | IllegalArgumentException e) { } catch (final IOException | IllegalArgumentException e) {
LOG.warn("Cannot cleanup file-directory", e); log.warn("Cannot cleanup file-directory", e);
} }
} }
} }
@@ -452,7 +451,7 @@ public abstract class AbstractIntegrationTest {
try { try {
FileUtils.deleteDirectory(new File(ARTIFACT_DIRECTORY)); FileUtils.deleteDirectory(new File(ARTIFACT_DIRECTORY));
} catch (final IOException | IllegalArgumentException e) { } catch (final IOException | IllegalArgumentException e) {
LOG.warn("Cannot delete file-directory", e); log.warn("Cannot delete file-directory", e);
} }
} }
} }

View File

@@ -15,8 +15,7 @@ import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import org.slf4j.Logger; import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.TestExecutionListener; import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.support.AbstractTestExecutionListener; import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.util.AntPathMatcher; import org.springframework.util.AntPathMatcher;
@@ -25,9 +24,9 @@ import org.springframework.util.AntPathMatcher;
* A {@link TestExecutionListener} for creating and dropping SQL schemas if * A {@link TestExecutionListener} for creating and dropping SQL schemas if
* tests are setup with an SQL schema. * tests are setup with an SQL schema.
*/ */
@Slf4j
public abstract class AbstractSqlTestDatabase extends AbstractTestExecutionListener { public abstract class AbstractSqlTestDatabase extends AbstractTestExecutionListener {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSqlTestDatabase.class);
protected static final AntPathMatcher MATCHER = new AntPathMatcher(); protected static final AntPathMatcher MATCHER = new AntPathMatcher();
protected final DatasourceContext context; protected final DatasourceContext context;
@@ -43,13 +42,13 @@ public abstract class AbstractSqlTestDatabase extends AbstractTestExecutionListe
protected abstract String getRandomSchemaUri(); protected abstract String getRandomSchemaUri();
protected void executeStatement(final String uri, final String statement) { protected void executeStatement(final String uri, final String statement) {
LOGGER.trace("\033[0;33mExecuting statement {} on uri {} \033[0m", statement, uri); log.trace("\033[0;33mExecuting statement {} on uri {} \033[0m", statement, uri);
try (final Connection connection = getConnection(uri, context.getUsername(), context.getPassword()); try (final Connection connection = getConnection(uri, context.getUsername(), context.getPassword());
final PreparedStatement preparedStatement = connection.prepareStatement(statement)) { final PreparedStatement preparedStatement = connection.prepareStatement(statement)) {
preparedStatement.execute(); preparedStatement.execute();
} catch (final SQLException e) { } catch (final SQLException e) {
LOGGER.error("Execution of statement '{}' on uri {} failed!", statement, uri, e); log.error("Execution of statement '{}' on uri {} failed!", statement, uri, e);
} }
} }
} }

View File

@@ -9,17 +9,15 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Holds all database related configuration * Holds all database related configuration
*/ */
@Slf4j
public class DatasourceContext { public class DatasourceContext {
private static final Logger LOGGER = LoggerFactory.getLogger(DatasourceContext.class);
public static final String SPRING_DATASOURCE_URL_KEY = "spring.datasource.url"; public static final String SPRING_DATASOURCE_URL_KEY = "spring.datasource.url";
public static final String SPRING_DATABASE_KEY = "spring.jpa.database"; public static final String SPRING_DATABASE_KEY = "spring.jpa.database";
public static final String SPRING_DATABASE_USERNAME_KEY = "spring.datasource.username"; public static final String SPRING_DATABASE_USERNAME_KEY = "spring.datasource.username";
@@ -82,7 +80,7 @@ public class DatasourceContext {
} }
public boolean isNotProperlyConfigured() { public boolean isNotProperlyConfigured() {
LOGGER.debug("Datasource environment variables: [database: {}, username: {}, password: {}, datasourceUrl: {}]", log.debug("Datasource environment variables: [database: {}, username: {}, password: {}, datasourceUrl: {}]",
database, username, password, datasourceUrl); database, username, password, datasourceUrl);
return database == null || datasourceUrl == null || username == null || password == null; return database == null || datasourceUrl == null || username == null || password == null;

View File

@@ -10,19 +10,17 @@
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.eclipse.hawkbit.repository.test.util.DatasourceContext.SPRING_DATASOURCE_URL_KEY; import static org.eclipse.hawkbit.repository.test.util.DatasourceContext.SPRING_DATASOURCE_URL_KEY;
/** /**
* Provides a convenient way to generate a test database that can be used, and disposed of after the test is executed. * Provides a convenient way to generate a test database that can be used, and disposed of after the test is executed.
*/ */
@Slf4j
public class DisposableSqlTestDatabaseExtension extends SharedSqlTestDatabaseExtension implements AfterAllCallback { public class DisposableSqlTestDatabaseExtension extends SharedSqlTestDatabaseExtension implements AfterAllCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(SharedSqlTestDatabaseExtension.class);
private DatasourceContext datasourceContext = null; private DatasourceContext datasourceContext = null;
@@ -37,7 +35,7 @@ public class DisposableSqlTestDatabaseExtension extends SharedSqlTestDatabaseExt
sharedContext.getUsername(), sharedContext.getPassword()); sharedContext.getUsername(), sharedContext.getPassword());
final AbstractSqlTestDatabase database = matchingDatabase(datasourceContext); final AbstractSqlTestDatabase database = matchingDatabase(datasourceContext);
final String randomSchemaUri = database.createRandomSchema().getRandomSchemaUri(); final String randomSchemaUri = database.createRandomSchema().getRandomSchemaUri();
LOGGER.info("\033[0;33mRandom Schema URI is {} \033[0m", randomSchemaUri); log.info("\033[0;33mRandom Schema URI is {} \033[0m", randomSchemaUri);
System.setProperty(SPRING_DATASOURCE_URL_KEY, randomSchemaUri); System.setProperty(SPRING_DATASOURCE_URL_KEY, randomSchemaUri);
} }

View File

@@ -9,24 +9,21 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.HexFormat; import java.util.HexFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Hash digest utility. * Hash digest utility.
*/ */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class HashGeneratorUtils { public final class HashGeneratorUtils {
private static final Logger LOG = LoggerFactory.getLogger(HashGeneratorUtils.class);
private HashGeneratorUtils() {
}
/** /**
* Generates a MD5 cryptographic string. * Generates a MD5 cryptographic string.
* *
@@ -67,9 +64,8 @@ public final class HashGeneratorUtils {
final byte[] hashedBytes = digest.digest(message); final byte[] hashedBytes = digest.digest(message);
return HexFormat.of().withLowerCase().formatHex(hashedBytes); return HexFormat.of().withLowerCase().formatHex(hashedBytes);
} catch (final NoSuchAlgorithmException e) { } catch (final NoSuchAlgorithmException e) {
LOG.error("Algorithm could not be found", e); log.error("Algorithm could not be found", e);
} }
return null; return null;
} }
}
}

View File

@@ -9,28 +9,26 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher; import org.junit.jupiter.api.extension.TestWatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Slf4j
public class JUnitTestLoggerExtension implements BeforeTestExecutionCallback, TestWatcher { public class JUnitTestLoggerExtension implements BeforeTestExecutionCallback, TestWatcher {
private static final Logger LOG = LoggerFactory.getLogger(JUnitTestLoggerExtension.class);
@Override @Override
public void testSuccessful(final ExtensionContext context) { public void testSuccessful(final ExtensionContext context) {
LOG.info("Test {} succeeded.", context.getTestMethod()); log.info("Test {} succeeded.", context.getTestMethod());
} }
@Override @Override
public void testFailed(final ExtensionContext context, final Throwable cause) { public void testFailed(final ExtensionContext context, final Throwable cause) {
LOG.error("Test {} failed with {}.", context.getTestMethod(), cause.getMessage()); log.error("Test {} failed with {}.", context.getTestMethod(), cause.getMessage());
} }
@Override @Override
public void beforeTestExecution(final ExtensionContext context) { public void beforeTestExecution(final ExtensionContext context) {
LOG.info("Starting Test {}...", context.getTestMethod()); log.info("Starting Test {}...", context.getTestMethod());
} }
} }

View File

@@ -11,19 +11,18 @@ package org.eclipse.hawkbit.repository.test.util;
import java.util.List; import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.cache.TenantAwareCacheManager; import org.eclipse.hawkbit.cache.TenantAwareCacheManager;
import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
@Slf4j
public class JpaTestRepositoryManagement { public class JpaTestRepositoryManagement {
private static final Logger LOGGER = LoggerFactory.getLogger(JpaTestRepositoryManagement.class);
private static final Pageable PAGE = PageRequest.of(0, 400, Sort.by(Direction.ASC, "id")); private static final Pageable PAGE = PageRequest.of(0, 400, Sort.by(Direction.ASC, "id"));
private final TenantAwareCacheManager cacheManager; private final TenantAwareCacheManager cacheManager;
@@ -64,7 +63,7 @@ public class JpaTestRepositoryManagement {
return null; return null;
}); });
} catch (final Exception e) { } catch (final Exception e) {
LOGGER.error("Error while delete tenant", e); log.error("Error while delete tenant", e);
} }
}); });
} }

View File

@@ -9,18 +9,16 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* An {@link Extension} for creating and dropping MS SQL Server * An {@link Extension} for creating and dropping MS SQL Server
* schemas if tests are set up with MS SQL Server. * schemas if tests are set up with MS SQL Server.
*/ */
@Slf4j
public class MsSqlTestDatabase extends AbstractSqlTestDatabase { public class MsSqlTestDatabase extends AbstractSqlTestDatabase {
private static final Logger LOGGER = LoggerFactory.getLogger(MsSqlTestDatabase.class);
public MsSqlTestDatabase(final DatasourceContext context) { public MsSqlTestDatabase(final DatasourceContext context) {
super(context); super(context);
} }
@@ -28,7 +26,7 @@ public class MsSqlTestDatabase extends AbstractSqlTestDatabase {
@Override @Override
public MsSqlTestDatabase createRandomSchema() { public MsSqlTestDatabase createRandomSchema() {
final String uri = context.getDatasourceUrl(); final String uri = context.getDatasourceUrl();
LOGGER.info("\033[0;33mCreating mssql schema {} \033[0m", context.getRandomSchemaName()); log.info("\033[0;33mCreating mssql schema {} \033[0m", context.getRandomSchemaName());
executeStatement(uri.split(";database=")[0], "CREATE DATABASE " + context.getRandomSchemaName() + ";"); executeStatement(uri.split(";database=")[0], "CREATE DATABASE " + context.getRandomSchemaName() + ";");
return this; return this;
@@ -38,7 +36,7 @@ public class MsSqlTestDatabase extends AbstractSqlTestDatabase {
protected void dropRandomSchema() { protected void dropRandomSchema() {
final String uri = context.getDatasourceUrl(); final String uri = context.getDatasourceUrl();
final String dbServerUri = uri.split(";database=")[0]; final String dbServerUri = uri.split(";database=")[0];
LOGGER.info("\033[0;33mDropping mssql schema {} \033[0m", context.getRandomSchemaName()); log.info("\033[0;33mDropping mssql schema {} \033[0m", context.getRandomSchemaName());
// Needed to avoid the DROP is rejected with "database still in use" // Needed to avoid the DROP is rejected with "database still in use"
executeStatement(dbServerUri, "ALTER DATABASE " + context.getRandomSchemaName() + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE;"); executeStatement(dbServerUri, "ALTER DATABASE " + context.getRandomSchemaName() + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE;");

View File

@@ -11,17 +11,16 @@ package org.eclipse.hawkbit.repository.test.util;
import java.util.Map; import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* An {@link Extension} for creating and dropping MySql schemas if * An {@link Extension} for creating and dropping MySql schemas if
* tests are set up with MySql. * tests are set up with MySql.
*/ */
@Slf4j
public class MySqlTestDatabase extends AbstractSqlTestDatabase { public class MySqlTestDatabase extends AbstractSqlTestDatabase {
private static final Logger LOGGER = LoggerFactory.getLogger(MySqlTestDatabase.class);
protected static final String MYSQL_URI_PATTERN = "jdbc:mariadb://{host}:{port}/{db}*"; protected static final String MYSQL_URI_PATTERN = "jdbc:mariadb://{host}:{port}/{db}*";
public MySqlTestDatabase(final DatasourceContext context) { public MySqlTestDatabase(final DatasourceContext context) {
@@ -32,7 +31,7 @@ public class MySqlTestDatabase extends AbstractSqlTestDatabase {
public MySqlTestDatabase createRandomSchema() { public MySqlTestDatabase createRandomSchema() {
final String uri = context.getDatasourceUrl(); final String uri = context.getDatasourceUrl();
final String schemaName = getSchemaName(uri); final String schemaName = getSchemaName(uri);
LOGGER.info("\033[0;33mCreating mysql schema {} if not existing \033[0m", context.getRandomSchemaName()); log.info("\033[0;33mCreating mysql schema {} if not existing \033[0m", context.getRandomSchemaName());
executeStatement(uri.split("/" + schemaName)[0], executeStatement(uri.split("/" + schemaName)[0],
"CREATE SCHEMA IF NOT EXISTS " + context.getRandomSchemaName() + ";"); "CREATE SCHEMA IF NOT EXISTS " + context.getRandomSchemaName() + ";");
@@ -43,7 +42,7 @@ public class MySqlTestDatabase extends AbstractSqlTestDatabase {
protected void dropRandomSchema() { protected void dropRandomSchema() {
final String uri = context.getDatasourceUrl(); final String uri = context.getDatasourceUrl();
final String schemaName = getSchemaName(uri); final String schemaName = getSchemaName(uri);
LOGGER.info("\033[0;33mDropping mysql schema {} \033[0m", context.getRandomSchemaName()); log.info("\033[0;33mDropping mysql schema {} \033[0m", context.getRandomSchemaName());
executeStatement(uri.split("/" + schemaName)[0], "DROP SCHEMA " + context.getRandomSchemaName() + ";"); executeStatement(uri.split("/" + schemaName)[0], "DROP SCHEMA " + context.getRandomSchemaName() + ";");
} }

View File

@@ -11,17 +11,16 @@ package org.eclipse.hawkbit.repository.test.util;
import java.util.Map; import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* An {@link Extension} for creating and dropping MySql schemas if * An {@link Extension} for creating and dropping MySql schemas if
* tests are set up with MySql. * tests are set up with MySql.
*/ */
@Slf4j
public class PostgreSqlTestDatabase extends AbstractSqlTestDatabase { public class PostgreSqlTestDatabase extends AbstractSqlTestDatabase {
private static final Logger LOGGER = LoggerFactory.getLogger(PostgreSqlTestDatabase.class);
private static final String POSTGRESQL_URI_PATTERN = "jdbc:postgresql://{host}:{port}/{db}*"; private static final String POSTGRESQL_URI_PATTERN = "jdbc:postgresql://{host}:{port}/{db}*";
public PostgreSqlTestDatabase(final DatasourceContext context) { public PostgreSqlTestDatabase(final DatasourceContext context) {
@@ -30,7 +29,7 @@ public class PostgreSqlTestDatabase extends AbstractSqlTestDatabase {
@Override @Override
protected PostgreSqlTestDatabase createRandomSchema() { protected PostgreSqlTestDatabase createRandomSchema() {
LOGGER.info("\033[0;33mCreating postgreSql schema {} \033[0m", context.getRandomSchemaName()); log.info("\033[0;33mCreating postgreSql schema {} \033[0m", context.getRandomSchemaName());
final String uri = getBaseUri() + "?currentSchema=" + getSchemaName(); final String uri = getBaseUri() + "?currentSchema=" + getSchemaName();
executeStatement(uri, "CREATE SCHEMA " + context.getRandomSchemaName() + ";"); executeStatement(uri, "CREATE SCHEMA " + context.getRandomSchemaName() + ";");
return this; return this;
@@ -38,7 +37,7 @@ public class PostgreSqlTestDatabase extends AbstractSqlTestDatabase {
@Override @Override
protected void dropRandomSchema() { protected void dropRandomSchema() {
LOGGER.info("\033[0;33mDropping postgreSql schema {}\033[0m", context.getRandomSchemaName()); log.info("\033[0;33mDropping postgreSql schema {}\033[0m", context.getRandomSchemaName());
final String uri = getBaseUri() + "?currentSchema=" + getSchemaName(); final String uri = getBaseUri() + "?currentSchema=" + getSchemaName();
executeStatement(uri, "DROP SCHEMA " + context.getRandomSchemaName() + " CASCADE;"); executeStatement(uri, "DROP SCHEMA " + context.getRandomSchemaName() + " CASCADE;");
} }

View File

@@ -13,17 +13,16 @@ import static org.eclipse.hawkbit.repository.test.util.DatasourceContext.SPRING_
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Represents a test database configuration for a "shared" database instance across all tests annotated with this extension * Represents a test database configuration for a "shared" database instance across all tests annotated with this extension
*/ */
@Slf4j
public class SharedSqlTestDatabaseExtension implements BeforeAllCallback { public class SharedSqlTestDatabaseExtension implements BeforeAllCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(SharedSqlTestDatabaseExtension.class);
protected static final AtomicReference<DatasourceContext> CONTEXT = new AtomicReference<>(); protected static final AtomicReference<DatasourceContext> CONTEXT = new AtomicReference<>();
@Override @Override
@@ -31,20 +30,20 @@ public class SharedSqlTestDatabaseExtension implements BeforeAllCallback {
final DatasourceContext testDatasourceContext = new DatasourceContext(); final DatasourceContext testDatasourceContext = new DatasourceContext();
if (testDatasourceContext.isNotProperlyConfigured()) { if (testDatasourceContext.isNotProperlyConfigured()) {
LOGGER.info("\033[0;33mSchema generation skipped... No datasource environment variables found!\033[0m"); log.info("\033[0;33mSchema generation skipped... No datasource environment variables found!\033[0m");
return; return;
} }
// update CONTEXT only if the current value is null => initialize only // update CONTEXT only if the current value is null => initialize only
if (!CONTEXT.compareAndSet(null, testDatasourceContext)) { if (!CONTEXT.compareAndSet(null, testDatasourceContext)) {
final String randomSchemaUri = matchingDatabase(testDatasourceContext).getRandomSchemaUri(); final String randomSchemaUri = matchingDatabase(testDatasourceContext).getRandomSchemaUri();
LOGGER.info("\033[0;33mReusing Random Schema at URI {} \033[0m", randomSchemaUri); log.info("\033[0;33mReusing Random Schema at URI {} \033[0m", randomSchemaUri);
return; return;
} }
final AbstractSqlTestDatabase database = matchingDatabase(testDatasourceContext); final AbstractSqlTestDatabase database = matchingDatabase(testDatasourceContext);
final String randomSchemaUri = database.createRandomSchema().getRandomSchemaUri(); final String randomSchemaUri = database.createRandomSchema().getRandomSchemaUri();
LOGGER.info("\033[0;33mRandom Schema URI is {} \033[0m", randomSchemaUri); log.info("\033[0;33mRandom Schema URI is {} \033[0m", randomSchemaUri);
System.setProperty(SPRING_DATASOURCE_URL_KEY, randomSchemaUri); System.setProperty(SPRING_DATASOURCE_URL_KEY, randomSchemaUri);
registerDropSchemaOnSystemShutdownHook(database, randomSchemaUri); registerDropSchemaOnSystemShutdownHook(database, randomSchemaUri);
@@ -52,7 +51,7 @@ public class SharedSqlTestDatabaseExtension implements BeforeAllCallback {
private void registerDropSchemaOnSystemShutdownHook(final AbstractSqlTestDatabase database, final String schemaUri) { private void registerDropSchemaOnSystemShutdownHook(final AbstractSqlTestDatabase database, final String schemaUri) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> { Runtime.getRuntime().addShutdownHook(new Thread(() -> {
LOGGER.warn("\033[0;33mDropping schema at url {} \033[0m", schemaUri); log.warn("\033[0;33mDropping schema at url {} \033[0m", schemaUri);
database.dropRandomSchema(); database.dropRandomSchema();
})); }));
} }