#2270: renamed datasource config flag

This commit is contained in:
DarioGii 2024-12-23 10:40:25 +00:00
parent ad8dd68a19
commit b21d45e92c
11 changed files with 76 additions and 50 deletions

View File

@ -72,6 +72,29 @@ sourceSets {
} }
} }
test {
java {
if (System.getenv("DOCKER_ENABLE_SECURITY") == "false") {
exclude "stirling/software/SPDF/config/security/**"
exclude "stirling/software/SPDF/controller/api/UserControllerTest.java"
exclude "stirling/software/SPDF/controller/api/DatabaseControllerTest.java"
exclude "stirling/software/SPDF/controller/web/AccountWebControllerTest.java"
exclude "stirling/software/SPDF/controller/web/DatabaseWebControllerTest.java"
exclude "stirling/software/SPDF/model/ApiKeyAuthenticationTokenTest.java"
exclude "stirling/software/SPDF/model/AttemptCounterTest.java"
exclude "stirling/software/SPDF/model/AuthorityTest.java"
exclude "stirling/software/SPDF/model/PersistentLoginTest.java"
exclude "stirling/software/SPDF/model/SessionEntityTest.java"
exclude "stirling/software/SPDF/model/UserTest.java"
exclude "stirling/software/SPDF/repository/**"
}
if (System.getenv("STIRLING_PDF_DESKTOP_UI") == "false") {
exclude "stirling/software/SPDF/UI/impl/**"
}
}
}
} }
openApi { openApi {

View File

@ -36,7 +36,7 @@ services:
SYSTEM_DATASOURCE_HOSTNAME: "db" SYSTEM_DATASOURCE_HOSTNAME: "db"
SYSTEM_DATASOURCE_PORT: "5432" SYSTEM_DATASOURCE_PORT: "5432"
SYSTEM_DATASOURCE_NAME: "stirling_pdf" SYSTEM_DATASOURCE_NAME: "stirling_pdf"
SYSTEM_DATASOURCE_USEDEFAULT: "false" SYSTEM_DATASOURCE_ENABLECUSTOMDATABASE: "false"
SYSTEM_DATASOURCE_USERNAME: "admin" SYSTEM_DATASOURCE_USERNAME: "admin"
SYSTEM_DATASOURCE_PASSWORD: "stirling" SYSTEM_DATASOURCE_PASSWORD: "stirling"
restart: on-failure:5 restart: on-failure:5

View File

@ -44,7 +44,7 @@ services:
SYSTEM_DATASOURCE_HOSTNAME: "db" SYSTEM_DATASOURCE_HOSTNAME: "db"
SYSTEM_DATASOURCE_PORT: "5432" SYSTEM_DATASOURCE_PORT: "5432"
SYSTEM_DATASOURCE_NAME: "stirling_pdf" SYSTEM_DATASOURCE_NAME: "stirling_pdf"
SYSTEM_DATASOURCE_USEDEFAULT: "false" SYSTEM_DATASOURCE_ENABLECUSTOMDATABASE: "false"
SYSTEM_DATASOURCE_USERNAME: "admin" SYSTEM_DATASOURCE_USERNAME: "admin"
SYSTEM_DATASOURCE_PASSWORD: "stirling" SYSTEM_DATASOURCE_PASSWORD: "stirling"
restart: on-failure:5 restart: on-failure:5

View File

@ -36,7 +36,7 @@ services:
SYSTEM_DATASOURCE_HOSTNAME: "db" SYSTEM_DATASOURCE_HOSTNAME: "db"
SYSTEM_DATASOURCE_PORT: "5432" SYSTEM_DATASOURCE_PORT: "5432"
SYSTEM_DATASOURCE_NAME: "stirling_pdf" SYSTEM_DATASOURCE_NAME: "stirling_pdf"
SYSTEM_DATASOURCE_USEDEFAULT: "false" SYSTEM_DATASOURCE_ENABLECUSTOMDATABASE: "false"
SYSTEM_DATASOURCE_USERNAME: "admin" SYSTEM_DATASOURCE_USERNAME: "admin"
SYSTEM_DATASOURCE_PASSWORD: "stirling" SYSTEM_DATASOURCE_PASSWORD: "stirling"
restart: on-failure:5 restart: on-failure:5

View File

@ -33,7 +33,7 @@ services:
SYSTEM_DATASOURCE_HOSTNAME: "db" SYSTEM_DATASOURCE_HOSTNAME: "db"
SYSTEM_DATASOURCE_PORT: "5432" SYSTEM_DATASOURCE_PORT: "5432"
SYSTEM_DATASOURCE_NAME: "stirling_pdf" SYSTEM_DATASOURCE_NAME: "stirling_pdf"
SYSTEM_DATASOURCE_USEDEFAULT: "false" SYSTEM_DATASOURCE_ENABLECUSTOMDATABASE: "false"
SYSTEM_DATASOURCE_USERNAME: "admin" SYSTEM_DATASOURCE_USERNAME: "admin"
SYSTEM_DATASOURCE_PASSWORD: "stirling" SYSTEM_DATASOURCE_PASSWORD: "stirling"
restart: on-failure:5 restart: on-failure:5

View File

@ -1,8 +1,5 @@
package stirling.software.SPDF.config.security.database; package stirling.software.SPDF.config.security.database;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -15,16 +12,22 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.ApplicationProperties; import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.provider.UnsupportedProviderException; import stirling.software.SPDF.model.provider.UnsupportedProviderException;
@Getter
@Slf4j @Slf4j
@Getter
@Configuration @Configuration
public class DatabaseConfig { public class DatabaseConfig {
public static final String DATASOURCE_DEFAULT_URL =
"jdbc:h2:file:./configs/stirling-pdf-DB-2.3.232;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE";
public static final String DATASOURCE_URL_TEMPLATE = "jdbc:%s://%s:%4d/%s"; public static final String DATASOURCE_URL_TEMPLATE = "jdbc:%s://%s:%4d/%s";
public static final String DEFAULT_DRIVER = "org.h2.Driver";
public static final String DEFAULT_USERNAME = "sa";
public static final String POSTGRES_DRIVER = "org.postgresql.Driver";
private final ApplicationProperties applicationProperties; private final ApplicationProperties applicationProperties;
public DatabaseConfig(@Autowired ApplicationProperties applicationProperties) { @Autowired
public DatabaseConfig(ApplicationProperties applicationProperties) {
this.applicationProperties = applicationProperties; this.applicationProperties = applicationProperties;
} }
@ -42,12 +45,12 @@ public class DatabaseConfig {
ApplicationProperties.Datasource datasource = system.getDatasource(); ApplicationProperties.Datasource datasource = system.getDatasource();
DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create(); DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
if (datasource.isUseDefault()) { if (datasource.isEnableCustomDatabase()) {
log.debug("Using default H2 database"); log.debug("Using default H2 database");
dataSourceBuilder.driverClassName("org.h2.Driver"); dataSourceBuilder.driverClassName(DEFAULT_DRIVER);
dataSourceBuilder.url(datasource.getDefaultUrl()); dataSourceBuilder.url(DATASOURCE_DEFAULT_URL);
dataSourceBuilder.username("sa"); dataSourceBuilder.username(DEFAULT_USERNAME);
return dataSourceBuilder.build(); return dataSourceBuilder.build();
} }
@ -79,15 +82,6 @@ public class DatabaseConfig {
return DATASOURCE_URL_TEMPLATE.formatted(dataSourceType, hostname, port, dataSourceName); return DATASOURCE_URL_TEMPLATE.formatted(dataSourceType, hostname, port, dataSourceName);
} }
/**
* @return a <code>Connection</code> using the configured <code>DataSource</code>
* @throws SQLException if a database access error occurs
* @throws UnsupportedProviderException when an unsupported database is selected
*/
public Connection connection() throws SQLException, UnsupportedProviderException {
return dataSource().getConnection();
}
/** /**
* Selects the database driver based on the type of database chosen. * Selects the database driver based on the type of database chosen.
* *
@ -103,11 +97,11 @@ public class DatabaseConfig {
switch (driver) { switch (driver) {
case H2 -> { case H2 -> {
log.debug("H2 driver selected"); log.debug("H2 driver selected");
return "org.h2.Driver"; return DEFAULT_DRIVER;
} }
case POSTGRESQL -> { case POSTGRESQL -> {
log.debug("Postgres driver selected"); log.debug("Postgres driver selected");
return "org.postgresql.Driver"; return POSTGRES_DRIVER;
} }
default -> { default -> {
log.warn("{} driver selected", driverName); log.warn("{} driver selected", driverName);

View File

@ -18,6 +18,8 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.PathResource; import org.springframework.core.io.PathResource;
import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.EncodedResource;
@ -29,7 +31,6 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.interfaces.DatabaseInterface; import stirling.software.SPDF.config.interfaces.DatabaseInterface;
import stirling.software.SPDF.model.ApplicationProperties; import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.exception.BackupNotFoundException; import stirling.software.SPDF.model.exception.BackupNotFoundException;
import stirling.software.SPDF.model.provider.UnsupportedProviderException;
import stirling.software.SPDF.utils.FileInfo; import stirling.software.SPDF.utils.FileInfo;
@Slf4j @Slf4j
@ -40,7 +41,14 @@ public class DatabaseService implements DatabaseInterface {
public static final String SQL_SUFFIX = ".sql"; public static final String SQL_SUFFIX = ".sql";
private static final String BACKUP_DIR = "configs/db/backup/"; private static final String BACKUP_DIR = "configs/db/backup/";
@Autowired private DatabaseConfig databaseConfig; private final ApplicationProperties applicationProperties;
private final DataSource dataSource;
@Autowired
public DatabaseService(ApplicationProperties applicationProperties, DataSource dataSource) {
this.applicationProperties = applicationProperties;
this.dataSource = dataSource;
}
/** /**
* Checks if there is at least one backup * Checks if there is at least one backup
@ -133,7 +141,7 @@ public class DatabaseService implements DatabaseInterface {
/** Filter and delete old backups if there are more than 5 */ /** Filter and delete old backups if there are more than 5 */
@Override @Override
public void exportDatabase() throws SQLException, UnsupportedProviderException { public void exportDatabase() throws SQLException {
List<FileInfo> filteredBackupList = List<FileInfo> filteredBackupList =
this.getBackupList().stream() this.getBackupList().stream()
.filter(backup -> !backup.getFileName().startsWith(BACKUP_PREFIX + "user_")) .filter(backup -> !backup.getFileName().startsWith(BACKUP_PREFIX + "user_"))
@ -148,12 +156,12 @@ public class DatabaseService implements DatabaseInterface {
Path insertOutputFilePath = Path insertOutputFilePath =
this.getBackupFilePath(BACKUP_PREFIX + dateNow.format(myFormatObj) + SQL_SUFFIX); this.getBackupFilePath(BACKUP_PREFIX + dateNow.format(myFormatObj) + SQL_SUFFIX);
try (Connection conn = databaseConfig.connection()) { try (Connection conn = dataSource.getConnection()) {
ScriptUtils.executeSqlScript( ScriptUtils.executeSqlScript(
conn, new EncodedResource(new PathResource(insertOutputFilePath))); conn, new EncodedResource(new PathResource(insertOutputFilePath)));
log.info("Database export completed: {}", insertOutputFilePath); log.info("Database export completed: {}", insertOutputFilePath);
} catch (SQLException | UnsupportedProviderException e) { } catch (SQLException e) {
log.error("Error during database export: {}", e.getMessage(), e); log.error("Error during database export: {}", e.getMessage(), e);
throw e; throw e;
} catch (ScriptException e) { } catch (ScriptException e) {
@ -184,13 +192,12 @@ public class DatabaseService implements DatabaseInterface {
public String getH2Version() { public String getH2Version() {
String version = "Unknown"; String version = "Unknown";
if (databaseConfig if (applicationProperties
.getApplicationProperties()
.getSystem() .getSystem()
.getDatasource() .getDatasource()
.getType() .getType()
.equals(ApplicationProperties.Driver.H2.name())) { .equals(ApplicationProperties.Driver.H2.name())) {
try (Connection conn = databaseConfig.connection()) { try (Connection conn = dataSource.getConnection()) {
try (Statement stmt = conn.createStatement(); try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT H2VERSION() AS version")) { ResultSet rs = stmt.executeQuery("SELECT H2VERSION() AS version")) {
if (rs.next()) { if (rs.next()) {
@ -198,7 +205,7 @@ public class DatabaseService implements DatabaseInterface {
log.info("H2 Database Version: {}", version); log.info("H2 Database Version: {}", version);
} }
} }
} catch (SQLException | UnsupportedProviderException e) { } catch (SQLException e) {
log.error("Error retrieving H2 version: {}", e.getMessage(), e); log.error("Error retrieving H2 version: {}", e.getMessage(), e);
} }
} }
@ -240,14 +247,21 @@ public class DatabaseService implements DatabaseInterface {
} }
private void executeDatabaseScript(Path scriptPath) { private void executeDatabaseScript(Path scriptPath) {
try (Connection conn = databaseConfig.connection()) { if (applicationProperties
ScriptUtils.executeSqlScript(conn, new EncodedResource(new PathResource(scriptPath))); .getSystem()
.getDatasource()
.getType()
.equals(ApplicationProperties.Driver.H2.name())) {
try (Connection conn = dataSource.getConnection()) {
ScriptUtils.executeSqlScript(
conn, new EncodedResource(new PathResource(scriptPath)));
log.info("Database import completed: {}", scriptPath); log.info("Database import completed: {}", scriptPath);
} catch (SQLException | UnsupportedProviderException e) { } catch (SQLException e) {
log.error("Error during database import: {}", e.getMessage(), e); log.error("Error during database import: {}", e.getMessage(), e);
} catch (ScriptException e) { } catch (ScriptException e) {
log.error("Error: File {} not found", scriptPath.toString(), e); log.error("Error: File {} not found", scriptPath.toString(), e);
}
} }
} }

View File

@ -252,14 +252,13 @@ public class ApplicationProperties {
@Data @Data
public static class Datasource { public static class Datasource {
private boolean enableCustomDatabase;
private String type; private String type;
private String hostName; private String hostName;
private Integer port; private Integer port;
private String name; private String name;
private String username; private String username;
@ToString.Exclude private String password; @ToString.Exclude private String password;
private boolean useDefault;
private final String defaultUrl;
} }
public enum Driver { public enum Driver {

View File

@ -86,14 +86,13 @@ system:
tessdataDir: /usr/share/tessdata # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored. tessdataDir: /usr/share/tessdata # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored.
enableAnalytics: undefined # set to 'true' to enable analytics, set to 'false' to disable analytics; for enterprise users, this is set to true enableAnalytics: undefined # set to 'true' to enable analytics, set to 'false' to disable analytics; for enterprise users, this is set to true
datasource: datasource:
enableCustomDatabase: true # set this property to 'true' if you would like to use the default database configuration
type: postgresql # the type of the database to set (e.g. 'h2', 'postgresql') type: postgresql # the type of the database to set (e.g. 'h2', 'postgresql')
hostName: localhost # the host name to use for the database url. Set to 'localhost' when running the app locally. Set to match the name of the container name of your database container when running the app on a server (Docker configuration) hostName: localhost # the host name to use for the database url. Set to 'localhost' when running the app locally. Set to match the name of the container name of your database container when running the app on a server (Docker configuration)
port: 5432 # set the port number of the database. Ensure this matches the port the database is listening to port: 5432 # set the port number of the database. Ensure this matches the port the database is listening to
name: postgres # set the name of your database. Should match the name of the database you create name: postgres # set the name of your database. Should match the name of the database you create
username: postgres # set the database username username: postgres # set the database username
password: postgres # set the database password password: postgres # set the database password
useDefault: 'true' # set this property to 'true' if you would like to use the default database configuration
defaultUrl: jdbc:h2:file:./configs/stirling-pdf-DB-2.3.232;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE # the default database url for the application
ui: ui:
appName: '' # application's visible name appName: '' # application's visible name

View File

@ -29,12 +29,10 @@ class DatabaseConfigTest {
void testDefaultConfigurationForDataSource() throws UnsupportedProviderException { void testDefaultConfigurationForDataSource() throws UnsupportedProviderException {
var system = mock(ApplicationProperties.System.class); var system = mock(ApplicationProperties.System.class);
var datasource = mock(ApplicationProperties.Datasource.class); var datasource = mock(ApplicationProperties.Datasource.class);
var testUrl = "jdbc:h2:mem:test";
when(applicationProperties.getSystem()).thenReturn(system); when(applicationProperties.getSystem()).thenReturn(system);
when(system.getDatasource()).thenReturn(datasource); when(system.getDatasource()).thenReturn(datasource);
when(datasource.isUseDefault()).thenReturn(true); when(datasource.isEnableCustomDatabase()).thenReturn(true);
when(datasource.getDefaultUrl()).thenReturn(testUrl);
var result = databaseConfig.dataSource(); var result = databaseConfig.dataSource();
@ -48,7 +46,7 @@ class DatabaseConfigTest {
when(applicationProperties.getSystem()).thenReturn(system); when(applicationProperties.getSystem()).thenReturn(system);
when(system.getDatasource()).thenReturn(datasource); when(system.getDatasource()).thenReturn(datasource);
when(datasource.isUseDefault()).thenReturn(false); when(datasource.isEnableCustomDatabase()).thenReturn(false);
when(datasource.getType()).thenReturn("postgresql"); when(datasource.getType()).thenReturn("postgresql");
when(datasource.getHostName()).thenReturn("localhost"); when(datasource.getHostName()).thenReturn("localhost");
when(datasource.getPort()).thenReturn(5432); when(datasource.getPort()).thenReturn(5432);
@ -69,7 +67,7 @@ class DatabaseConfigTest {
when(applicationProperties.getSystem()).thenReturn(system); when(applicationProperties.getSystem()).thenReturn(system);
when(system.getDatasource()).thenReturn(datasource); when(system.getDatasource()).thenReturn(datasource);
when(datasource.isUseDefault()).thenReturn(false); when(datasource.isEnableCustomDatabase()).thenReturn(false);
when(datasource.getType()).thenReturn(datasourceType); when(datasource.getType()).thenReturn(datasourceType);
assertThrows(UnsupportedProviderException.class, () -> databaseConfig.dataSource()); assertThrows(UnsupportedProviderException.class, () -> databaseConfig.dataSource());

View File

@ -13,7 +13,6 @@ import static java.nio.file.Files.delete;
import static java.nio.file.Files.exists; import static java.nio.file.Files.exists;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@Disabled
@SpringBootTest @SpringBootTest
public class SPDFApplicationIntegrationTest { public class SPDFApplicationIntegrationTest {