From 405704968e0eb7a97b12aa544f6d323c23e2d773 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 10 Feb 2023 10:01:03 +0100 Subject: [PATCH] [Minor] Code cleanup --- .../postgresql/PostgreSqlInitializer.java | 22 ++------ .../PostgreSqlPersistenceHandler.java | 11 ++-- .../PostgreSqlSchemaInitializer.java | 2 +- .../postgresql/dao/test/CachedDaoTest.java | 20 +++---- .../command/AbstractRealmCommandTest.java | 2 - .../command/InMemoryTransactionTest.java | 2 - .../test/AbstractRealmServiceTest.java | 27 +++++---- .../strolch/performance/PerformanceTest.java | 6 +- .../main/java/li/strolch/db/DbConstants.java | 15 ++--- .../li/strolch/db/DbSchemaVersionCheck.java | 56 +++++++++---------- 10 files changed, 74 insertions(+), 89 deletions(-) diff --git a/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlInitializer.java b/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlInitializer.java index 753ca17fc..c725812d1 100644 --- a/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlInitializer.java +++ b/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlInitializer.java @@ -69,9 +69,8 @@ public abstract class PostgreSqlInitializer extends SystemAction { logger.info(MessageFormat.format(msg, realmName, migrationType)); ModelStatistics statistics; - try (StrolchTransaction tx = this.persistenceHandler - .openTx(this.agent.getContainer().getRealm(realmName), getCertificate(), getClass().getSimpleName(), - false)) { + try (StrolchTransaction tx = this.persistenceHandler.openTx(this.agent.getContainer().getRealm(realmName), + getCertificate(), getClass().getSimpleName(), false)) { File dataStoreF = getDataStoreFile(this.runtimeConfig, this.realmConfig, realmName); StoreToDaoElementListener listener = new StoreToDaoElementListener(tx); @@ -84,19 +83,10 @@ public abstract class PostgreSqlInitializer extends SystemAction { } protected boolean checkNeedsDbInit(DbMigrationState migrationType) { - boolean needsDbInit; - switch (migrationType) { - case CREATED: - case DROPPED_CREATED: - needsDbInit = true; - break; - case MIGRATED: - case NOTHING: - default: - needsDbInit = false; - break; - } - return needsDbInit; + return switch (migrationType) { + case CREATED, DROPPED_CREATED -> true; + case MIGRATED, NOTHING -> false; + }; } protected File getDataStoreFile(RuntimeConfiguration runtimeConfiguration, diff --git a/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlPersistenceHandler.java b/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlPersistenceHandler.java index b005db7cc..7aba91b9c 100644 --- a/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlPersistenceHandler.java +++ b/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlPersistenceHandler.java @@ -94,12 +94,11 @@ public class PostgreSqlPersistenceHandler extends StrolchComponent implements Pe @Override public void start() throws Exception { - ComponentConfiguration configuration = getConfiguration(); - boolean allowSchemaCreation = configuration.getBoolean(PROP_ALLOW_SCHEMA_CREATION, Boolean.FALSE); - boolean allowSchemaMigration = configuration.getBoolean(PROP_ALLOW_SCHEMA_MIGRATION, Boolean.FALSE); - boolean allowSchemaDrop = configuration.getBoolean(PROP_ALLOW_SCHEMA_DROP, Boolean.FALSE); - boolean allowDataInitOnSchemaCreate = configuration.getBoolean(PROP_ALLOW_DATA_INIT_ON_SCHEMA_CREATE, - Boolean.FALSE); + ComponentConfiguration config = getConfiguration(); + boolean allowSchemaCreation = config.getBoolean(PROP_ALLOW_SCHEMA_CREATION, false); + boolean allowSchemaMigration = config.getBoolean(PROP_ALLOW_SCHEMA_MIGRATION, false); + boolean allowSchemaDrop = config.getBoolean(PROP_ALLOW_SCHEMA_DROP, false); + boolean allowDataInitOnSchemaCreate = config.getBoolean(PROP_ALLOW_DATA_INIT_ON_SCHEMA_CREATE, false); DbSchemaVersionCheck schemaVersionCheck = new DbSchemaVersionCheck(SCRIPT_PREFIX_STROLCH, this.getClass(), allowSchemaCreation, allowSchemaMigration, allowSchemaDrop); diff --git a/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlSchemaInitializer.java b/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlSchemaInitializer.java index 8b0149f91..63e0b100e 100644 --- a/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlSchemaInitializer.java +++ b/persistence-postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlSchemaInitializer.java @@ -28,7 +28,7 @@ import li.strolch.privilege.model.PrivilegeContext; */ public class PostgreSqlSchemaInitializer extends PostgreSqlInitializer { - private Map dbMigrationStates; + private final Map dbMigrationStates; public PostgreSqlSchemaInitializer(StrolchAgent agent, PostgreSqlPersistenceHandler persistenceHandler, Map dbMigrationStates) { diff --git a/persistence-postgresql/src/test/java/li/strolch/persistence/postgresql/dao/test/CachedDaoTest.java b/persistence-postgresql/src/test/java/li/strolch/persistence/postgresql/dao/test/CachedDaoTest.java index d45381239..9fa735a02 100644 --- a/persistence-postgresql/src/test/java/li/strolch/persistence/postgresql/dao/test/CachedDaoTest.java +++ b/persistence-postgresql/src/test/java/li/strolch/persistence/postgresql/dao/test/CachedDaoTest.java @@ -15,7 +15,6 @@ */ package li.strolch.persistence.postgresql.dao.test; -import static li.strolch.db.DbConstants.PROP_DB_ALLOW_HOST_OVERRIDE_ENV; import static li.strolch.db.DbConstants.PROP_DB_HOST_OVERRIDE; import static li.strolch.persistence.postgresql.PostgreSqlPersistenceHandler.SCRIPT_PREFIX_ARCHIVE; import static li.strolch.persistence.postgresql.PostgreSqlPersistenceHandler.SCRIPT_PREFIX_STROLCH; @@ -43,13 +42,13 @@ import org.slf4j.LoggerFactory; public class CachedDaoTest extends AbstractModelTest { - public static final String RUNTIME_PATH = "target/cachedRuntime/"; //$NON-NLS-1$ - public static final String DB_STORE_PATH_DIR = "dbStore"; //$NON-NLS-1$ - public static final String CONFIG_SRC = "src/test/resources/cachedRuntime"; //$NON-NLS-1$ + public static final String RUNTIME_PATH = "target/cachedRuntime/"; + public static final String DB_STORE_PATH_DIR = "dbStore"; + public static final String CONFIG_SRC = "src/test/resources/cachedRuntime"; - public static final String DB_URL = "jdbc:postgresql://localhost/testdb"; //$NON-NLS-1$ - public static final String DB_USERNAME = "testuser"; //$NON-NLS-1$ - public static final String DB_PASSWORD = "test"; //$NON-NLS-1$ + public static final String DB_URL = "jdbc:postgresql://localhost/testdb"; + public static final String DB_USERNAME = "testuser"; + public static final String DB_PASSWORD = "test"; private static final Logger logger = LoggerFactory.getLogger(CachedDaoTest.class); @@ -70,7 +69,9 @@ public class CachedDaoTest extends AbstractModelTest { File configSrc = new File(CONFIG_SRC); runtimeMock = new RuntimeMock(); runtimeMock.mockRuntime(rootPath, configSrc); - new File(rootPath, DB_STORE_PATH_DIR).mkdir(); + File dbStorePath = new File(rootPath, DB_STORE_PATH_DIR); + if (!dbStorePath.mkdir()) + throw new IllegalStateException("Failed to created db store path " + dbStorePath); runtimeMock.startContainer(); PostgreSqlPersistenceHandler persistenceHandler = (PostgreSqlPersistenceHandler) runtimeMock.getContainer() @@ -89,8 +90,7 @@ public class CachedDaoTest extends AbstractModelTest { Version dbVersion = DbSchemaVersionCheck.getExpectedDbVersion(scriptPrefix, PostgreSqlPersistenceHandler.class); logger.info(MessageFormat.format("Dropping schema for expected version {0}", dbVersion)); - String sql = DbSchemaVersionCheck.getSql(scriptPrefix, PostgreSqlPersistenceHandler.class, dbVersion, - "drop"); //$NON-NLS-1$ + String sql = DbSchemaVersionCheck.getSql(scriptPrefix, PostgreSqlPersistenceHandler.class, dbVersion, "drop"); logger.info(StringHelper.NEW_LINE + sql); try (Connection connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) { connection.prepareStatement(sql).execute(); diff --git a/service/src/test/java/li/strolch/command/AbstractRealmCommandTest.java b/service/src/test/java/li/strolch/command/AbstractRealmCommandTest.java index b8b26f0b6..a45022cb0 100644 --- a/service/src/test/java/li/strolch/command/AbstractRealmCommandTest.java +++ b/service/src/test/java/li/strolch/command/AbstractRealmCommandTest.java @@ -15,8 +15,6 @@ */ package li.strolch.command; -import static li.strolch.db.DbConstants.PROP_DB_HOST_OVERRIDE; -import static li.strolch.runtime.configuration.DbConnectionBuilder.overridePostgresqlHost; import static li.strolch.service.test.AbstractRealmServiceTest.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; diff --git a/service/src/test/java/li/strolch/command/InMemoryTransactionTest.java b/service/src/test/java/li/strolch/command/InMemoryTransactionTest.java index a3a7e9fda..61e80af06 100644 --- a/service/src/test/java/li/strolch/command/InMemoryTransactionTest.java +++ b/service/src/test/java/li/strolch/command/InMemoryTransactionTest.java @@ -1,7 +1,5 @@ package li.strolch.command; -import static li.strolch.db.DbConstants.PROP_DB_HOST_OVERRIDE; -import static li.strolch.runtime.configuration.DbConnectionBuilder.overridePostgresqlHost; import static li.strolch.service.test.AbstractRealmServiceTest.*; import static org.junit.Assert.*; diff --git a/service/src/test/java/li/strolch/service/test/AbstractRealmServiceTest.java b/service/src/test/java/li/strolch/service/test/AbstractRealmServiceTest.java index deabd89f1..68cfb9637 100644 --- a/service/src/test/java/li/strolch/service/test/AbstractRealmServiceTest.java +++ b/service/src/test/java/li/strolch/service/test/AbstractRealmServiceTest.java @@ -20,6 +20,7 @@ import static li.strolch.runtime.configuration.DbConnectionBuilder.overridePostg import static li.strolch.testbase.runtime.RuntimeMock.assertServiceResult; import java.io.File; +import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.DriverManager; @@ -49,8 +50,8 @@ public abstract class AbstractRealmServiceTest expectedServiceResultType, - Runner before, Runner validator, Runner after) throws IllegalAccessException, InstantiationException { + Runner before, Runner validator, Runner after) + throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { - Service svc = getSvcClass().newInstance(); + Service svc = getSvcClass().getConstructor().newInstance(); T arg = getArgInstance(); if (before != null) @@ -165,34 +167,37 @@ public abstract class AbstractRealmServiceTest expectedServiceResultType, Runner before, Runner validator, Runner after) - throws InstantiationException, IllegalAccessException { + throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { doService(REALM_CACHED, ServiceResultState.SUCCESS, expectedServiceResultType, before, validator, after); } private void runCachedWithAuditsAndVersioning(Class expectedServiceResultType, Runner before, Runner validator, - Runner after) throws InstantiationException, IllegalAccessException { + Runner after) + throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { doService(REALM_CACHED_AUDITS_VERSIONING, ServiceResultState.SUCCESS, expectedServiceResultType, before, validator, after); } - protected void runTransient() throws IllegalAccessException, InstantiationException { + protected void runTransient() + throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { runTransient(null); } protected void runTransient(Class expectedServiceResultType) - throws IllegalAccessException, InstantiationException { + throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { runTransient(expectedServiceResultType, null, null, null); } private void runTransient(Class expectedServiceResultType, Runner before, Runner validator, Runner after) - throws InstantiationException, IllegalAccessException { + throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { doService(REALM_TRANSIENT, ServiceResultState.SUCCESS, expectedServiceResultType, before, validator, after); } } diff --git a/test-performance/src/test/java/li/strolch/performance/PerformanceTest.java b/test-performance/src/test/java/li/strolch/performance/PerformanceTest.java index e774a7804..d568d4bff 100644 --- a/test-performance/src/test/java/li/strolch/performance/PerformanceTest.java +++ b/test-performance/src/test/java/li/strolch/performance/PerformanceTest.java @@ -122,7 +122,7 @@ public abstract class PerformanceTest { logger.info("Task " + i + " executed " + results.get(i) + " TXs"); } - long avg = (long) results.stream().mapToLong(l -> l).average().getAsDouble(); + long avg = (long) results.stream().mapToLong(l -> l).average().orElse(0.0D); long took = System.currentTimeMillis() - start; long txPerSec = avg / (took / 1000); logger.info("Average TXs was " + avg + " with " + txPerSec + " TXs/s"); @@ -130,8 +130,8 @@ public abstract class PerformanceTest { public class PerformanceTask extends ForkJoinTask { - private String username; - private int nrOfElements; + private final String username; + private final int nrOfElements; private PerformanceTestResult svcResult; public PerformanceTask(String username, int nrOfElements) { diff --git a/utils/src/main/java/li/strolch/db/DbConstants.java b/utils/src/main/java/li/strolch/db/DbConstants.java index 24dbef955..17049c4a2 100644 --- a/utils/src/main/java/li/strolch/db/DbConstants.java +++ b/utils/src/main/java/li/strolch/db/DbConstants.java @@ -20,13 +20,14 @@ package li.strolch.db; */ public class DbConstants { - public static final String PROP_DB_URL = "db.url"; //$NON-NLS-1$ - public static final String PROP_DB_IGNORE_REALM = "db.ignore.realm"; //$NON-NLS-1$ - public static final String PROP_DB_USERNAME = "db.username"; //$NON-NLS-1$ - public static final String PROP_DB_PASSWORD = "db.password"; //$NON-NLS-1$ - public static final String PROP_DB_VERBOSE = "db.verbose"; //$NON-NLS-1$ - public static final String PROP_DB_ALLOW_HOST_OVERRIDE_ENV = "db.allowHostOverrideEnv"; //$NON-NLS-1$ - public static final String PROP_DB_HOST_OVERRIDE = "db.hostOverride"; //$NON-NLS-1$ + public static final String PROP_USE_ENV = "db.useEnv"; + public static final String PROP_DB_URL = "db.url"; + public static final String PROP_DB_IGNORE_REALM = "db.ignore.realm"; + public static final String PROP_DB_USERNAME = "db.username"; + public static final String PROP_DB_PASSWORD = "db.password"; + public static final String PROP_DB_VERBOSE = "db.verbose"; + public static final String PROP_DB_ALLOW_HOST_OVERRIDE_ENV = "db.allowHostOverrideEnv"; + public static final String PROP_DB_HOST_OVERRIDE = "db.hostOverride"; public static final String PROP_ALLOW_SCHEMA_CREATION = "allowSchemaCreation"; public static final String PROP_ALLOW_SCHEMA_MIGRATION = "allowSchemaMigration"; public static final String PROP_ALLOW_SCHEMA_DROP = "allowSchemaDrop"; diff --git a/utils/src/main/java/li/strolch/db/DbSchemaVersionCheck.java b/utils/src/main/java/li/strolch/db/DbSchemaVersionCheck.java index dac6f8c73..758d021c6 100644 --- a/utils/src/main/java/li/strolch/db/DbSchemaVersionCheck.java +++ b/utils/src/main/java/li/strolch/db/DbSchemaVersionCheck.java @@ -42,16 +42,15 @@ import org.slf4j.LoggerFactory; /** * @author Robert von Burg <eitch@eitchnet.ch> */ -@SuppressWarnings(value = "nls") public class DbSchemaVersionCheck { private static final Logger logger = LoggerFactory.getLogger(DbSchemaVersionCheck.class); - private String app; - private Class ctxClass; - private boolean allowSchemaCreation; - private boolean allowSchemaMigration; - private boolean allowSchemaDrop; - private Map dbMigrationStates; + private final String app; + private final Class ctxClass; + private final boolean allowSchemaCreation; + private final boolean allowSchemaMigration; + private final boolean allowSchemaDrop; + private final Map dbMigrationStates; /** * @param app @@ -127,18 +126,13 @@ public class DbSchemaVersionCheck { DbMigrationState migrationType = detectMigrationState(realm, expectedDbVersion, currentVersion); switch (migrationType) { - case CREATED: - createSchema(con, realm, expectedDbVersion); - break; - case MIGRATED: - migrateSchema(con, realm, currentVersion, expectedDbVersion); - break; - case DROPPED_CREATED: - throw new DbException("Migration type " + migrationType + " not handled!"); - case NOTHING: - // do nothing - default: - break; + case CREATED -> createSchema(con, realm, expectedDbVersion); + case MIGRATED -> migrateSchema(con, realm, currentVersion, expectedDbVersion); + case DROPPED_CREATED -> throw new DbException("Migration type " + migrationType + " not handled!"); + + // do nothing + case NOTHING -> { + } } con.commit(); @@ -215,8 +209,8 @@ public class DbSchemaVersionCheck { return DbMigrationState.MIGRATED; } - throw new DbException(MessageFormat - .format("[{0}:{1}]Current version {2} is later than expected version {3}", this.app, realm, + throw new DbException( + MessageFormat.format("[{0}:{1}]Current version {2} is later than expected version {3}", this.app, realm, currentVersion, expectedDbVersion)); } @@ -312,8 +306,8 @@ public class DbSchemaVersionCheck { throw new DbException("Failed to execute schema generation SQL: " + e.getMessage(), e); } - logger.info(MessageFormat - .format("[{0}:{1}] Successfully created schema with version {2}", this.app, realm, version)); + logger.info(MessageFormat.format("[{0}:{1}] Successfully created schema with version {2}", this.app, realm, + version)); } /** @@ -345,8 +339,8 @@ public class DbSchemaVersionCheck { "Expected version " + expectedVersion + " is weirdly before current version" + currentVersion + " for " + this.app); - logger.info(MessageFormat - .format("[{0}:{1}] Migrating schema from {2} to {3}...", this.app, realm, currentVersion, + logger.info( + MessageFormat.format("[{0}:{1}] Migrating schema from {2} to {3}...", this.app, realm, currentVersion, expectedVersion)); // first get all possible migration scripts @@ -383,8 +377,8 @@ public class DbSchemaVersionCheck { throw new IllegalStateException("Failed to read current version", e); } - logger.info(MessageFormat - .format("[{0}:{1}] Successfully migrated schema to version {2}", this.app, realm, expectedVersion)); + logger.info(MessageFormat.format("[{0}:{1}] Successfully migrated schema to version {2}", this.app, realm, + expectedVersion)); } public List parseMigrationVersions() { @@ -401,8 +395,8 @@ public class DbSchemaVersionCheck { ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { String entryName = ze.getName(); - if (entryName.endsWith(".sql") && entryName.startsWith(this.app) && entryName - .contains("migration")) + if (entryName.endsWith(".sql") && entryName.startsWith(this.app) && entryName.contains( + "migration")) versions.add(parseVersion(entryName)); } } catch (IOException e) { @@ -463,7 +457,7 @@ public class DbSchemaVersionCheck { throw new DbException("Failed to execute schema drop SQL: " + e.getMessage(), e); } - logger.info(MessageFormat - .format("[{0}:{1}] Successfully dropped schema with version {2}", this.app, realm, version)); + logger.info(MessageFormat.format("[{0}:{1}] Successfully dropped schema with version {2}", this.app, realm, + version)); } }