Commit 37bf28f1 authored by Shouib's avatar Shouib

feat: initialize persistent H2 database infrastructure

parent 3e5975df
node_modules/
dist/
build/
target/
*.log
.env*
data/
.DS_Store
Thumbs.db
*.tmp
*.swp
.vscode/
.idea/
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.banking</groupId>
<artifactId>banking-transaction-system</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>27</maven.compiler.source>
<maven.compiler.target>27</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.11.0</junit.version>
<mockito.version>5.11.0</mockito.version>
<jackson.version>2.17.0</jackson.version>
<h2.version>2.2.224</h2.version>
</properties>
<dependencies>
<!-- JSON processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
......@@ -30,10 +30,10 @@ description: "Task list template for feature implementation"
**Purpose**: Project initialization and basic structure
- [ ] T001 Create project structure per implementation plan in `src/main/java/com/banking/` and `src/test/java/com/banking/`
- [ ] T002 Initialize `pom.xml` with Java 27, Jackson, H2, JUnit 5, and Mockito dependencies
- [ ] T003 [P] Create `src/main/resources/db.properties` for H2 database configuration
- [ ] T004 [P] Implement `com.banking.config.AppConfig` for centralized application settings
- [X] T001 Create project structure per implementation plan in `src/main/java/com/banking/` and `src/test/java/com/banking/`
- [X] T002 Initialize `pom.xml` with Java 27, Jackson, H2, JUnit 5, and Mockito dependencies
- [X] T003 [P] Create `src/main/resources/db.properties` for H2 database configuration
- [X] T004 [P] Implement `com.banking.config.AppConfig` for centralized application settings
---
......@@ -41,7 +41,7 @@ description: "Task list template for feature implementation"
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
- [ ] T005 Implement `com.banking.persistence.DatabaseManager` for JDBC connection pooling and lifecycle management
- [X] T005 Implement `com.banking.persistence.DatabaseManager` for JDBC connection lifecycle management (no pooling)
- [ ] T006 [P] Implement `com.banking.persistence.AccountRepository` for basic account CRUD operations (including `SELECT FOR UPDATE`)
- [ ] T007 [P] Implement `com.banking.persistence.TransactionLedgerRepository` for idempotent ledger operations
- [ ] T008 Implement `com.banking.service.IdempotencyManager` to handle sequence key validation and ledger lookups
......
package com.banking.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Centralized application configuration manager.
* Handles loading and accessing system properties and configuration files.
*/
public class AppConfig {
private static final Logger LOGGER = Logger.getLogger(AppConfig.class.getName());
private static final Properties properties = new Properties();
static {
try (InputStream input = AppConfig.class.getClassLoader().getResourceAsStream("db.properties")) {
if (input == null) {
LOGGER.severe("Unable to find db.properties");
} else {
properties.load(input);
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Error loading configuration file", ex);
}
}
public static String getProperty(String key) {
return properties.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
public static int getIntProperty(String key, int defaultValue) {
String value = properties.getProperty(key);
return value != null ? Integer.parseInt(value) : defaultValue;
}
public static boolean getBooleanProperty(String key, boolean defaultValue) {
String value = properties.getProperty(key);
return value != null ? Boolean.parseBoolean(value) : defaultValue;
}
}
package com.banking.persistence;
import com.banking.config.AppConfig;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Manages the lifecycle of JDBC connections to the H2 database.
* Following the approved architecture: one JDBC Connection per transaction.
*/
public class DatabaseManager {
private static final Logger LOGGER = Logger.getLogger(DatabaseManager.class.getName());
private static boolean isInitialized = false;
/**
* Establishes a new connection to the database.
* Ensures the data directory exists and the schema is initialized before connecting.
*
* @return A new SQL Connection
* @throws SQLException if a database access error occurs
*/
public static Connection getConnection() throws SQLException {
ensureDataDirectoryExists();
if (!isInitialized) {
initializeSchema();
isInitialized = true;
}
String url = AppConfig.getProperty("db.url");
String user = AppConfig.getProperty("db.user");
String password = AppConfig.getProperty("db.password");
String driver = AppConfig.getProperty("db.driver");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
LOGGER.log(Level.SEVERE, "H2 Driver not found", e);
throw new SQLException("Database driver not found: " + driver, e);
}
return DriverManager.getConnection(url, user, password);
}
/**
* Initializes the database schema by executing schema.sql.
*/
private static void initializeSchema() {
LOGGER.info("Initializing database schema...");
try {
var resource = AppConfig.class.getClassLoader().getResource("schema.sql");
if (resource == null) {
throw new IOException("schema.sql not found in resources");
}
StringBuilder sql = new StringBuilder();
try (var is = resource.openStream();
BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(is))) {
String line;
while ((line = reader.readLine()) != null) {
sql.append(line).append("\n");
}
}
String fullSql = sql.toString();
// To ensure the schema is actually applied to the file-based DB,
// we use the same connection settings.
try (Connection conn = DriverManager.getConnection(
AppConfig.getProperty("db.url"),
AppConfig.getProperty("db.user"),
AppConfig.getProperty("db.password"));
Statement stmt = conn.createStatement()) {
// We use RUNSCRIPT for H2 to execute the file directly,
// but since we already read it into a string, we split by semicolon.
String[] statements = fullSql.split(";");
for (String s : statements) {
String trimmed = s.trim();
if (!trimmed.isEmpty()) {
stmt.execute(trimmed);
}
}
LOGGER.info("Database schema initialized successfully.");
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Failed to initialize database schema", e);
throw new RuntimeException("Database initialization failed", e);
}
}
/**
* Ensures the directory for database files exists.
* Based on the provided db.url (e.g., jdbc:h2:file:./data/banking_db).
*/
private static void ensureDataDirectoryExists() {
String url = AppConfig.getProperty("db.url");
if (url != null && url.contains("file:")) {
String path = url.substring(url.indexOf("file:") + 5);
if (path.contains(";")) {
path = path.substring(0, path.indexOf(";"));
}
File dbFile = new File(path);
File dataDir = dbFile.getParentFile();
if (dataDir != null && !dataDir.exists()) {
if (dataDir.mkdirs()) {
LOGGER.info("Created data directory: " + dataDir.getAbsolutePath());
} else if (!dataDir.exists()) {
LOGGER.warning("Failed to create data directory: " + dataDir.getAbsolutePath());
}
}
}
}
}
# H2 Database Configuration
db.url=jdbc:h2:file:./data/banking_db
db.user=sa
db.password=
db.driver=org.h2.Driver
CREATE TABLE IF NOT EXISTS ACCOUNT (
account_id VARCHAR(50) PRIMARY KEY,
balance DECIMAL(20, 2) NOT NULL CHECK (balance >= 0),
last_processed_seq_key BIGINT NOT NULL DEFAULT 0 CHECK (last_processed_seq_key >= 0)
);
CREATE TABLE IF NOT EXISTS TRANSACTION_LEDGER (
id IDENTITY PRIMARY KEY,
account_id VARCHAR(50) NOT NULL,
balance_after DECIMAL(20, 2) NOT NULL,
sequence_key BIGINT NOT NULL,
amount DECIMAL(20, 2) NOT NULL CHECK (amount > 0),
outcome VARCHAR(20) NOT NULL CHECK (outcome IN ('SUCCESS', 'INSUFFICIENT_FUNDS')),
response_message VARCHAR(255) NOT NULL,
timestamp TIMESTAMP NOT NULL,
FOREIGN KEY (account_id) REFERENCES ACCOUNT(account_id),
UNIQUE (account_id, sequence_key)
);
package com.banking.persistence;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static org.junit.jupiter.api.Assertions.*;
class DatabaseManagerTest {
@BeforeEach
void setUp() {
// Reset the DatabaseManager initialization state and clear data directory
try {
java.lang.reflect.Field field = DatabaseManager.class.getDeclaredField("isInitialized");
field.setAccessible(true);
field.set(null, false);
} catch (Exception e) {
throw new RuntimeException(e);
}
File dataDir = new File("./data");
if (dataDir.exists()) {
deleteDirectory(dataDir);
}
}
private void deleteDirectory(File directory) {
File[] allContents = directory.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
directory.delete();
}
@Test
void testConnectionSucceeds() throws SQLException {
try (Connection conn = DatabaseManager.getConnection()) {
assertNotNull(conn);
assertFalse(conn.isClosed());
}
}
@Test
void testDataDirectoryCreatedAutomatically() throws SQLException {
// The @BeforeEach already deleted the directory
File dataDir = new File("./data");
assertFalse(dataDir.exists(), "Data directory should not exist yet");
DatabaseManager.getConnection().close();
assertTrue(dataDir.exists(), "Data directory should be created by DatabaseManager");
assertTrue(dataDir.isDirectory());
}
@Test
void testSchemaInitialization() throws SQLException {
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement()) {
// Verify ACCOUNT table exists
try (ResultSet rs = stmt.executeQuery("SELECT * FROM ACCOUNT")) {
assertNotNull(rs);
}
// Verify TRANSACTION_LEDGER table exists
try (ResultSet rs = stmt.executeQuery("SELECT * FROM TRANSACTION_LEDGER")) {
assertNotNull(rs);
}
}
}
@Test
void testConnectionReopening() throws SQLException {
Connection conn1 = DatabaseManager.getConnection();
conn1.close();
Connection conn2 = DatabaseManager.getConnection();
assertNotNull(conn2);
assertFalse(conn2.isClosed());
conn2.close();
}
@Test
void testDataSurvivesRestart() throws SQLException {
String accountId = "test-acc-1";
double balance = 100.00;
// 1. Insert data and close connection
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement()) {
stmt.execute("INSERT INTO ACCOUNT (account_id, balance) VALUES ('" + accountId + "', " + balance + ")");
}
// 2. Open new connection and verify data exists
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT balance FROM ACCOUNT WHERE account_id = '" + accountId + "'")) {
assertTrue(rs.next());
assertEquals(balance, rs.getDouble("balance"), 0.001);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment