Compare commits

...
Author SHA1 Message Date
Gustavo Henrique Miranda ba53d4d8c4 Merge pull request #10 from gmbrax/refactor/add-hibernate-and-reflection-dependency
Remove `Media` entity and integrate Hibernate ORM into `DatabaseManager`:
2025-11-28 00:38:21 -03:00
Gustavo Henrique Santos Souza de Miranda 081a1f1ed4 Add exception handling for entity scanning in DatabaseManager
- Wrap entity scanning in a try-catch block to handle potential exceptions.
- Log descriptive error messages and throw a runtime exception for failure cases.
- Warn if no `@Entity` classes are found during the scan.
2025-11-27 19:20:22 -03:00
Gustavo Henrique Santos Souza de Miranda e395e21e8c Add validation for required Hibernate configuration properties in DatabaseManager
- Ensure non-null and non-empty values for `hibernate.dialect`, `database.driver`, and `connectionUrl`.
- Throw `IllegalStateException` when required properties are missing.
2025-11-27 19:08:11 -03:00
Gustavo Henrique Santos Souza de Miranda 412a590a98 Add exception handling for Hibernate initialization in DatabaseManager
- Wrap Hibernate setup in a try-catch block.
- Log errors during initialization failure with descriptive messages.
- Throw a runtime exception if setup fails to ensure proper error propagation.
2025-11-27 19:04:44 -03:00
Gustavo Henrique Santos Souza de Miranda bc0199312f Add null and open-state checks for EntityManager and EntityManagerFactory closure
- Ensure safe closure of `EntityManager` and `EntityManagerFactory`.
- Add logging for successful closure and error handling during exceptions.
2025-11-27 18:55:43 -03:00
Gustavo Henrique Santos Souza de Miranda 4ae1e3075d Remove Media entity and integrate Hibernate ORM into DatabaseManager:
- Deleted `Media` class and its annotations.
- Added Hibernate ORM initialization in `DatabaseManager`, including dynamic entity scanning and configuration.
- Updated `pom.xml` to include dependencies for Hibernate community dialects and Reflections.
2025-11-27 18:40:08 -03:00
Gustavo Henrique Miranda fc09c4e257 Merge pull request #9 from gmbrax/fix/fix-unsecure-postgres-version
Fix the pom.xml
2025-11-24 22:19:31 -03:00
Gustavo Henrique Santos Souza de Miranda 53004a3730 Fix the pom.xml to alter the postgres dependency to a safer version due a CVE in the 42.7.5 then it was bumped t0 42.7.7 2025-11-24 21:59:35 -03:00
Gustavo Henrique Miranda 7e154eb01c Merge pull request #7 from gmbrax/feature/IPC-Unix-Socket
Feature/ipc unix socket
2025-11-22 23:41:12 -03:00
Gustavo Henrique Miranda 24fadf9474 Merge pull request #6 from gmbrax/feature/add-SQLite-Implementation
Feature/add sq lite implementation
2025-11-22 23:37:31 -03:00
Gustavo Henrique Santos Souza de Miranda 2704be31bc Fix logging library dependency in pom.xml: replace log4j-slf4j2-impl with log4j-slf4j-impl. 2025-11-21 18:19:38 -03:00
Gustavo Henrique Santos Souza de Miranda dc4b6cbdfa Add SQLite support with SqliteDatabaseManager and application mode handling:
- Created `SqliteDatabaseManager` for SQLite database initialization and management.
- Refactored `DatabaseManager` into an abstract class to support different database implementations.
- Introduced `ApplicationMode` enum to switch between `local` and `server` modes.
- Updated `MediaManagerApplication` to handle `runtype` configuration and initialize SQLite in `local` mode.
- Updated `config.properties.example` with new `runtype` property.
- Added SQLite JDBC dependency to `pom.xml`.
2025-11-21 18:03:20 -03:00
Gustavo Henrique Miranda 77259308c6 Merge pull request #5 from gmbrax/feature/IPC-Unix-Socket
Feature/ipc unix socket
2025-11-20 09:16:50 -03:00
Gustavo Henrique Miranda 3998b18671 Merge pull request #4 from gmbrax/feature/IPC-Unix-Socket
feature/IPC-Unix-Socket
2025-11-14 22:40:49 -03:00
6 changed files with 263 additions and 192 deletions
+18 -2
View File
@@ -13,7 +13,7 @@
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hibernate.version>7.1.7.Final</hibernate.version>
<postgresql.version>42.7.5</postgresql.version>
<postgresql.version>42.7.7</postgresql.version>
<hikaricp.version>5.1.0</hikaricp.version>
<log4j.version>2.23.1</log4j.version>
<junit.version>5.10.2</junit.version>
@@ -35,6 +35,12 @@
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-community-dialects</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- HikariCP for connection pooling -->
<dependency>
<groupId>com.zaxxer</groupId>
@@ -55,7 +61,7 @@
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
@@ -83,6 +89,16 @@
<artifactId>protobuf-java</artifactId>
<version>4.32.0</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.44.1.0</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
</dependencies>
<build>
@@ -1,5 +1,6 @@
package com.mediamanager;
import com.mediamanager.service.database.DatabaseManager;
import com.mediamanager.service.delegate.DelegateActionManager;
import com.mediamanager.service.ipc.IPCManager;
import org.apache.logging.log4j.LogManager;
@@ -9,7 +10,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.mediamanager.service.database.DatabaseManager;
import com.mediamanager.service.database.SqliteDatabaseManager;
public class MediaManagerApplication {
private static final Logger logger = LogManager.getLogger(MediaManagerApplication.class);
@@ -18,13 +19,46 @@ public class MediaManagerApplication {
private static DelegateActionManager actionManager;
private static IPCManager ipcManager;
public enum ApplicationMode {
LOCAL("local"),
SERVER("server");
private final String value;
ApplicationMode(String value) {
this.value = value;
}
}
public static void main(String[] args) {
logger.info("Starting MediaManager Core Application...");
try {
// Load configuration
loadConfiguration();
databaseManager = new DatabaseManager(config);
String runTypeString = config.getProperty("runtype","local");
ApplicationMode mode = null;
for (ApplicationMode am : ApplicationMode.values()) {
if (am.value.equalsIgnoreCase(runTypeString)) {
mode = am;
break;
}
}
if (mode == null) {
logger.error("Invalid run type: {}", runTypeString);
throw new Exception("Invalid run type: " + runTypeString);
}
logger.info("Run type: {}", mode);
switch (mode) {
case LOCAL:
logger.info("Starting local database...");
databaseManager = new SqliteDatabaseManager(config);
break;
case SERVER:
throw new Exception("Server mode not yet implemented");
default:
}
databaseManager.init();
actionManager = new DelegateActionManager();
actionManager.start();
@@ -102,4 +136,4 @@ public class MediaManagerApplication {
public static Properties getConfig() {
return config;
}
}
}
@@ -1,128 +0,0 @@
package com.mediamanager.model;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "media")
public class Media {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@Column(nullable = false, unique = true)
private String filePath;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private MediaType type;
@Column
private Long fileSize;
@Column
private String mimeType;
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
// Constructors
public Media() {}
public Media(String title, String filePath, MediaType type) {
this.title = title;
this.filePath = filePath;
this.type = type;
}
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public MediaType getType() {
return type;
}
public void setType(MediaType type) {
this.type = type;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public enum MediaType {
VIDEO,
AUDIO,
IMAGE,
DOCUMENT,
OTHER
}
}
@@ -1,55 +1,38 @@
package com.mediamanager.service.database;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.cfg.Configuration;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import jakarta.persistence.Entity;
import java.util.Set;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DatabaseManager {
private final Properties configuration;
private Connection connection;
private static final Logger logger = LogManager.getLogger(DatabaseManager.class);
public abstract class DatabaseManager {
protected final Properties configuration;
protected Connection connection;
protected String connectionUrl;
protected EntityManagerFactory entityManagerFactory;
protected EntityManager entityManager;
protected static final Logger logger = LogManager.getLogger(DatabaseManager.class);
public DatabaseManager(Properties config) {
this.configuration = config;
logger.debug("DatabaseManager created with configuration:");
}
public void init() throws Exception {
logger.info("Initializing database connection...");
validateConfiguration();
public abstract void init() throws Exception;
String databaseType = configuration.getProperty("database.type");
String databaseUrl = configuration.getProperty("database.url");
String databaseUsername = configuration.getProperty("database.username");
String databasePassword = configuration.getProperty("database.password");
String databasePort = configuration.getProperty("database.port");
String databaseName = configuration.getProperty("database.name");
protected abstract Connection createConnection() throws Exception;
String connectionString = String.format("jdbc:postgresql://%s:%s/%s", databaseUrl, databasePort, databaseName);
logger.debug("Attempting to connect to: {}", connectionString);
try {
connection = DriverManager.getConnection(connectionString, databaseUsername, databasePassword);
logger.info("Database connection established successfully");
performSanityChecks();
logger.info("Database sanity checks passed successfully");
} catch (SQLException e) {
logger.error("Failed to connect to database", e);
throw new Exception("Database connection failed: " + e.getMessage(), e);
}
}
private void performSanityChecks() throws SQLException {
protected void performSanityChecks() throws SQLException {
logger.debug("Performing sanity checks...");
try (Statement stmt = connection.createStatement()) {
stmt.execute("SELECT 1");
@@ -59,33 +42,28 @@ public class DatabaseManager {
String databaseProductVersion = connection.getMetaData().getDatabaseProductVersion();
logger.info("Connected to database: {} v{}", databaseProductName, databaseProductVersion);
}
private void validateConfiguration() throws Exception {
String[] requiredProperties = {
"database.url",
"database.username",
"database.password",
"database.port",
"database.name"
};
for (String property : requiredProperties) {
if (configuration.getProperty(property) == null ||
configuration.getProperty(property).trim().isEmpty()) {
throw new Exception("Required database configuration missing: " + property);
}
}
logger.debug("Database configuration validated successfully");
}
public Connection getConnection() {
return connection;
}
public void close() {
if (entityManager != null && entityManager.isOpen()) {
try {
entityManager.close();
logger.info("EntityManager closed");
} catch (Exception e) {
logger.error("Error closing EntityManager: {}", e.getMessage());
}
}
if (entityManagerFactory != null && entityManagerFactory.isOpen()) {
try {
entityManagerFactory.close();
logger.info("EntityManagerFactory closed");
} catch (Exception e) {
logger.error("Error closing EntityManagerFactory: {}", e.getMessage());
}
}
if (connection != null) {
try {
logger.info("Closing database connection...");
@@ -98,4 +76,74 @@ public class DatabaseManager {
logger.debug("No database connection to close");
}
}
}
protected boolean testConnection() {
try (Statement stmt = connection.createStatement()) {
stmt.execute("SELECT 1");
return true;
} catch (SQLException e) {
logger.error("Connection test failed", e);
return false;
}
}
protected void initializeHibernate() {
logger.info("Initializing Hibernate ORM...");
Configuration hibernateConfig = new Configuration();
String dialect = configuration.getProperty("hibernate.dialect");
String hbm2ddl = configuration.getProperty("hibernate.hbm2ddl.auto");
String driver = configuration.getProperty("database.driver");
if (dialect == null || dialect.isEmpty()) {
throw new IllegalStateException("hibernate.dialect property is required but not configured");
}
if (driver == null || driver.isEmpty()) {
throw new IllegalStateException("database.driver property is required but not configured");
}
if (connectionUrl == null || connectionUrl.isEmpty()) {
throw new IllegalStateException("connectionUrl must be set before initializing Hibernate");
}
hibernateConfig.setProperty("hibernate.connection.url", connectionUrl);
hibernateConfig.setProperty("hibernate.connection.driver_class", driver);
hibernateConfig.setProperty("hibernate.dialect", dialect);
hibernateConfig.setProperty("hibernate.hbm2ddl.auto", hbm2ddl);
hibernateConfig.setProperty("hibernate.show_sql",
configuration.getProperty("hibernate.show_sql", "false"));
hibernateConfig.setProperty("hibernate.format_sql",
configuration.getProperty("hibernate.format_sql", "true"));
logger.info("Scanning for entities in package: com.mediamanager.model");
Set<Class<?>> entityClasses;
try {
Reflections reflections = new Reflections("com.mediamanager.model", Scanners.TypesAnnotated);
entityClasses = reflections.getTypesAnnotatedWith(Entity.class);
} catch (Exception e) {
logger.error("Failed to scan for entities: {}", e.getMessage());
throw new RuntimeException("Entity scanning failed", e);
}
logger.info("Found {} entities", entityClasses.size());
if (entityClasses.isEmpty()) {
logger.warn("No @Entity classes found in package com.mediamanager.model - is this expected?");
}
for (Class<?> entityClass : entityClasses) {
logger.debug("Registering entity: {}", entityClass.getSimpleName());
hibernateConfig.addAnnotatedClass(entityClass);
}
try {
entityManagerFactory = hibernateConfig.buildSessionFactory().unwrap(EntityManagerFactory.class);
entityManager = entityManagerFactory.createEntityManager();
} catch (Exception e) {
logger.error("Failed to initialize Hibernate: {}", e.getMessage());
throw new RuntimeException("Hibernate initialization failed", e);
}
logger.info("Hibernate ORM initialized successfully");
}
}
@@ -0,0 +1,99 @@
package com.mediamanager.service.database;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class SqliteDatabaseManager extends DatabaseManager {
private static final Logger logger = LogManager.getLogger(SqliteDatabaseManager.class);
public SqliteDatabaseManager(Properties config) {
super(config);
}
@Override
public void init() throws Exception {
logger.info("Initializing SQLite database...");
String dataDir = configuration.getProperty("database.dir",
System.getProperty("user.home") + "/.mediamanager/db");
String dbFilename = configuration.getProperty("database.filename", "mediamanager.db");
String driverClassName = configuration.getProperty("database.driver", "org.sqlite.JDBC");
try {
Class.forName(driverClassName);
}catch(ClassNotFoundException e) {
logger.error("Failed to load SQLite driver", e);
throw e;
}
Path dataPath = Paths.get(dataDir);
if (!Files.exists(dataPath)) {
Files.createDirectories(dataPath);
logger.debug("Created database directory: {}", dataDir);
}
Path dbFile = dataPath.resolve(dbFilename);
this.connectionUrl = "jdbc:sqlite:" + dbFile.toAbsolutePath().toString();
logger.info("Database file path: {}", dbFile);
logger.info("Connection URL: {}", this.connectionUrl);
initializeHibernate();
this.connection = createConnection();
configurePerformancePragmas();
performSanityChecks();
ensureSchemaExists();
logger.info("SQLite database initialized successfully");
}
@Override
protected Connection createConnection() throws Exception {
try {
// O driver org.xerial.sqlite-jdbc é carregado automaticamente aqui
Connection conn = DriverManager.getConnection(this.connectionUrl);
logger.debug("Got connection to SQLite file");
return conn;
} catch (SQLException e) {
logger.error("Failed to create SQLite connection", e);
throw new Exception("SQLite connection failed: " + e.getMessage(), e);
}
}
private void configurePerformancePragmas() throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.execute("PRAGMA journal_mode=WAL;");
stmt.execute("PRAGMA foreign_keys=ON;");
stmt.execute("PRAGMA synchronous=NORMAL;");
stmt.execute("PRAGMA busy_timeout=5000;");
logger.debug("SQLite performance PRAGMAs applied (WAL, Synchronous, ForeignKeys).");
}
}
private void ensureSchemaExists() throws SQLException {
}
@Override
public void close() {
super.close();
logger.info("SQLite resources released.");
}
}
+3 -1
View File
@@ -21,6 +21,8 @@ hibernate.format_sql=true
ipc.pipe.name=mediamanager-pipe
ipc.pipe.path=/tmp/mediamanager
ipc.buffer.size=8192
runtype=local
ipc.socket.path=/tmp/mediamanager