mirror of
https://github.com/gmbrax/MediaManager-core.git
synced 2026-11-09 22:10:17 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
353fee5985 | ||
|
|
e56d86c0e5 | ||
|
|
77259308c6 | ||
|
|
a0ad10b1bc | ||
|
|
23b6d54674 |
@@ -55,7 +55,7 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
<artifactId>log4j-slf4j2-impl</artifactId>
|
<artifactId>log4j-slf4j-impl</artifactId>
|
||||||
<version>${log4j.version}</version>
|
<version>${log4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
@@ -78,9 +78,29 @@
|
|||||||
<version>${junit.version}</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.protobuf</groupId>
|
||||||
|
<artifactId>protobuf-java</artifactId>
|
||||||
|
<version>4.32.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.zonky.test</groupId>
|
||||||
|
<artifactId>embedded-postgres</artifactId>
|
||||||
|
<version>2.2.0</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
<extensions>
|
||||||
|
<extension>
|
||||||
|
<groupId>kr.motd.maven</groupId>
|
||||||
|
<artifactId>os-maven-plugin</artifactId>
|
||||||
|
<version>1.7.1</version>
|
||||||
|
</extension>
|
||||||
|
</extensions>
|
||||||
|
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
@@ -91,12 +111,54 @@
|
|||||||
<target>17</target>
|
<target>17</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>3.2.5</version>
|
<version>3.2.5</version>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
|
<!-- Protocol Buffers Plugin -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.xolstice.maven.plugins</groupId>
|
||||||
|
<artifactId>protobuf-maven-plugin</artifactId>
|
||||||
|
<version>0.6.1</version>
|
||||||
|
<configuration>
|
||||||
|
<protocExecutable>/usr/bin/protoc</protocExecutable>
|
||||||
|
<protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
|
||||||
|
<outputDirectory>${project.build.directory}/generated-sources/protobuf/java</outputDirectory>
|
||||||
|
<clearOutputDirectory>false</clearOutputDirectory>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>compile</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<!-- Build Helper Plugin - Adiciona generated sources ao classpath -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>build-helper-maven-plugin</artifactId>
|
||||||
|
<version>3.5.0</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>add-source</id>
|
||||||
|
<phase>generate-sources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>add-source</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<sources>
|
||||||
|
<source>${project.build.directory}/generated-sources/protobuf/java</source>
|
||||||
|
</sources>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
<!-- Maven Shade Plugin - Creates executable JAR with all dependencies -->
|
<!-- Maven Shade Plugin - Creates executable JAR with all dependencies -->
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.mediamanager;
|
package com.mediamanager;
|
||||||
|
|
||||||
|
import com.mediamanager.service.delegate.DelegateActionManager;
|
||||||
import com.mediamanager.service.ipc.IPCManager;
|
import com.mediamanager.service.ipc.IPCManager;
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
@@ -8,24 +9,59 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import com.mediamanager.service.database.DatabaseManager;
|
import com.mediamanager.service.database.LocalDatabaseManager;
|
||||||
|
|
||||||
public class MediaManagerApplication {
|
public class MediaManagerApplication {
|
||||||
private static final Logger logger = LogManager.getLogger(MediaManagerApplication.class);
|
private static final Logger logger = LogManager.getLogger(MediaManagerApplication.class);
|
||||||
private static Properties config;
|
private static Properties config;
|
||||||
private static DatabaseManager databaseManager;
|
private static LocalDatabaseManager databaseManager;
|
||||||
|
private static DelegateActionManager actionManager;
|
||||||
private static IPCManager ipcManager;
|
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) {
|
public static void main(String[] args) {
|
||||||
logger.info("Starting MediaManager Core Application...");
|
logger.info("Starting MediaManager Core Application...");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Load configuration
|
// Load configuration
|
||||||
loadConfiguration();
|
loadConfiguration();
|
||||||
databaseManager = new DatabaseManager(config);
|
String runTypeString = config.getProperty("runtype","local");
|
||||||
databaseManager.init();
|
ApplicationMode mode = null;
|
||||||
|
|
||||||
ipcManager = new IPCManager(config);
|
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 LocalDatabaseManager(config);
|
||||||
|
break;
|
||||||
|
case SERVER:
|
||||||
|
throw new Exception("Server mode not yet implemented");
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
databaseManager.init();
|
||||||
|
actionManager = new DelegateActionManager();
|
||||||
|
actionManager.start();
|
||||||
|
ipcManager = new IPCManager(config,actionManager);
|
||||||
ipcManager.init();
|
ipcManager.init();
|
||||||
|
|
||||||
// TODO: Start application services
|
// TODO: Start application services
|
||||||
@@ -51,6 +87,9 @@ public class MediaManagerApplication {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (actionManager != null) {
|
||||||
|
actionManager.stop();
|
||||||
|
}
|
||||||
|
|
||||||
logger.info("MediaManager Core shutdown successfully");
|
logger.info("MediaManager Core shutdown successfully");
|
||||||
logger.info("Goodbye!");
|
logger.info("Goodbye!");
|
||||||
|
|||||||
@@ -1,55 +1,28 @@
|
|||||||
package com.mediamanager.service.database;
|
package com.mediamanager.service.database;
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.DriverManager;
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.sql.Statement;
|
import java.sql.Statement;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
|
public abstract class DatabaseManager {
|
||||||
|
protected final Properties configuration;
|
||||||
|
protected Connection connection;
|
||||||
|
protected static final Logger logger = LogManager.getLogger(DatabaseManager.class);
|
||||||
|
|
||||||
public class DatabaseManager {
|
|
||||||
private final Properties configuration;
|
|
||||||
private Connection connection;
|
|
||||||
private static final Logger logger = LogManager.getLogger(DatabaseManager.class);
|
|
||||||
public DatabaseManager(Properties config) {
|
public DatabaseManager(Properties config) {
|
||||||
this.configuration = config;
|
this.configuration = config;
|
||||||
logger.debug("DatabaseManager created with configuration:");
|
logger.debug("DatabaseManager created with configuration:");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void init() throws Exception {
|
public abstract void init() throws Exception;
|
||||||
logger.info("Initializing database connection...");
|
|
||||||
validateConfiguration();
|
|
||||||
|
|
||||||
String databaseType = configuration.getProperty("database.type");
|
protected abstract Connection createConnection() throws Exception;
|
||||||
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 void performSanityChecks() throws SQLException {
|
||||||
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 {
|
|
||||||
logger.debug("Performing sanity checks...");
|
logger.debug("Performing sanity checks...");
|
||||||
try (Statement stmt = connection.createStatement()) {
|
try (Statement stmt = connection.createStatement()) {
|
||||||
stmt.execute("SELECT 1");
|
stmt.execute("SELECT 1");
|
||||||
@@ -59,27 +32,6 @@ public class DatabaseManager {
|
|||||||
String databaseProductVersion = connection.getMetaData().getDatabaseProductVersion();
|
String databaseProductVersion = connection.getMetaData().getDatabaseProductVersion();
|
||||||
logger.info("Connected to database: {} v{}", databaseProductName, databaseProductVersion);
|
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() {
|
public Connection getConnection() {
|
||||||
return connection;
|
return connection;
|
||||||
@@ -98,4 +50,13 @@ public class DatabaseManager {
|
|||||||
logger.debug("No database connection to close");
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.mediamanager.service.database;
|
||||||
|
|
||||||
|
import io.zonky.test.db.postgres.embedded.EmbeddedPostgres;
|
||||||
|
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.util.Properties;
|
||||||
|
|
||||||
|
public class LocalDatabaseManager extends DatabaseManager {
|
||||||
|
private static final Logger logger = LogManager.getLogger(LocalDatabaseManager.class);
|
||||||
|
private EmbeddedPostgres embeddedPostgres;
|
||||||
|
|
||||||
|
public LocalDatabaseManager(Properties config) {
|
||||||
|
super(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init() throws Exception {
|
||||||
|
logger.info("Initializing embedded PostgreSQL database...");
|
||||||
|
|
||||||
|
// Configurações específicas do modo local
|
||||||
|
String dataDir = configuration.getProperty("local.database.dir",
|
||||||
|
System.getProperty("user.home") + "/.mediamanager/db");
|
||||||
|
int port = Integer.parseInt(
|
||||||
|
configuration.getProperty("local.database.port", "54321")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Cria diretório se não existir
|
||||||
|
Path dataPath = Paths.get(dataDir);
|
||||||
|
Files.createDirectories(dataPath);
|
||||||
|
logger.debug("Using data directory: {}", dataDir);
|
||||||
|
|
||||||
|
// Inicia o PostgreSQL embedded
|
||||||
|
logger.info("Starting embedded PostgreSQL on port {}", port);
|
||||||
|
embeddedPostgres = EmbeddedPostgres.builder()
|
||||||
|
.setDataDirectory(dataPath)
|
||||||
|
.setCleanDataDirectory(false) // Mantém dados
|
||||||
|
.setPort(port)
|
||||||
|
.start();
|
||||||
|
|
||||||
|
// Cria a conexão
|
||||||
|
this.connection = createConnection();
|
||||||
|
logger.info("Embedded database connection established successfully");
|
||||||
|
|
||||||
|
// Usa o método da classe pai para sanity checks
|
||||||
|
performSanityChecks();
|
||||||
|
logger.info("Database sanity checks passed successfully");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Connection createConnection() throws Exception {
|
||||||
|
if (embeddedPostgres == null) {
|
||||||
|
throw new IllegalStateException("Embedded PostgreSQL not started");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Pega conexão do embedded
|
||||||
|
Connection conn = embeddedPostgres.getPostgresDatabase().getConnection();
|
||||||
|
logger.debug("Got connection from embedded PostgreSQL");
|
||||||
|
return conn;
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Failed to get embedded connection", e);
|
||||||
|
throw new Exception("Embedded connection failed: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
// Primeiro fecha a conexão (método da classe pai)
|
||||||
|
super.close();
|
||||||
|
|
||||||
|
// Depois para o embedded
|
||||||
|
if (embeddedPostgres != null) {
|
||||||
|
try {
|
||||||
|
logger.info("Stopping embedded PostgreSQL...");
|
||||||
|
embeddedPostgres.close();
|
||||||
|
logger.info("Embedded PostgreSQL stopped successfully");
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Error stopping embedded PostgreSQL", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.mediamanager.service.delegate;
|
||||||
|
|
||||||
|
import com.google.protobuf.ByteString;
|
||||||
|
import com.google.protobuf.InvalidProtocolBufferException;
|
||||||
|
import com.mediamanager.protocol.TransportProtocol;
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface ActionHandler {
|
||||||
|
TransportProtocol.Response.Builder handle(ByteString requestPayload) throws InvalidProtocolBufferException;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.mediamanager.service.delegate;
|
||||||
|
|
||||||
|
import com.google.protobuf.ByteString;
|
||||||
|
import com.mediamanager.protocol.TransportProtocol;
|
||||||
|
import com.mediamanager.service.delegate.handler.EchoHandler;
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class DelegateActionManager {
|
||||||
|
private static final Logger logger = LogManager.getLogger(DelegateActionManager.class);
|
||||||
|
|
||||||
|
private final Map<String, ActionHandler> handlerRegistry;
|
||||||
|
|
||||||
|
public DelegateActionManager() {
|
||||||
|
|
||||||
|
logger.debug("DelegateActionManager created");
|
||||||
|
this.handlerRegistry = new HashMap<>();
|
||||||
|
registerHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void registerHandlers() {
|
||||||
|
handlerRegistry.put("echo",new EchoHandler());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void start(){
|
||||||
|
logger.info("DelegateActionManager started");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop(){
|
||||||
|
logger.info("DelegateActionManager stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
public TransportProtocol.Response ProcessedRequest(TransportProtocol.Request request){
|
||||||
|
String requestId = request.getRequestId();
|
||||||
|
logger.info("Processing request: {}", requestId);
|
||||||
|
String action = request.getHeadersMap().getOrDefault("action", "unknown");
|
||||||
|
ActionHandler handler = handlerRegistry.get(action);
|
||||||
|
TransportProtocol.Response.Builder responseBuilder;
|
||||||
|
if (handler == null) {
|
||||||
|
logger.warn("No handler found for action: {}", action);
|
||||||
|
responseBuilder = TransportProtocol.Response.newBuilder()
|
||||||
|
.setStatusCode(404) // 404 Not Found
|
||||||
|
.setPayload(ByteString.copyFromUtf8("Error: Action '" + action + "' not found."));
|
||||||
|
} else{
|
||||||
|
try {
|
||||||
|
logger.debug("Delegating action '{}' to handler...", action);
|
||||||
|
responseBuilder = handler.handle(request.getPayload());
|
||||||
|
}catch (Exception e) {
|
||||||
|
logger.error("Handler for action '{}' threw an exception:", action, e);
|
||||||
|
responseBuilder = TransportProtocol.Response.newBuilder()
|
||||||
|
.setStatusCode(500) // 500 Internal Server Error
|
||||||
|
.setPayload(ByteString.copyFromUtf8("Error: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return responseBuilder.setRequestId(requestId).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.mediamanager.service.delegate.handler;
|
||||||
|
|
||||||
|
import com.google.protobuf.ByteString;
|
||||||
|
import com.mediamanager.protocol.TransportProtocol;
|
||||||
|
import com.mediamanager.service.delegate.ActionHandler;
|
||||||
|
|
||||||
|
public class EchoHandler implements ActionHandler {
|
||||||
|
@Override
|
||||||
|
public TransportProtocol.Response.Builder handle(ByteString requestPayload) {
|
||||||
|
String payloadText = requestPayload.toStringUtf8();
|
||||||
|
String responseText = "Server received: " + payloadText;
|
||||||
|
|
||||||
|
return TransportProtocol.Response.newBuilder()
|
||||||
|
.setPayload(ByteString.copyFromUtf8(responseText))
|
||||||
|
.setStatusCode(200);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
package com.mediamanager.service.ipc;
|
package com.mediamanager.service.ipc;
|
||||||
|
|
||||||
|
import com.mediamanager.protocol.TransportProtocol;
|
||||||
|
import com.mediamanager.service.delegate.DelegateActionManager;
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.StandardProtocolFamily;
|
import java.net.StandardProtocolFamily;
|
||||||
import java.net.UnixDomainSocketAddress;
|
import java.net.UnixDomainSocketAddress;
|
||||||
@@ -26,6 +27,8 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
public class IPCManager {
|
public class IPCManager {
|
||||||
private final Properties configuration;
|
private final Properties configuration;
|
||||||
private static final Logger logger = LogManager.getLogger(IPCManager.class);
|
private static final Logger logger = LogManager.getLogger(IPCManager.class);
|
||||||
|
private final DelegateActionManager actionManager;
|
||||||
|
|
||||||
private Path socketPath;
|
private Path socketPath;
|
||||||
private UnixDomainSocketAddress socketAddress;
|
private UnixDomainSocketAddress socketAddress;
|
||||||
private ServerSocketChannel serverChannel;
|
private ServerSocketChannel serverChannel;
|
||||||
@@ -35,8 +38,9 @@ public class IPCManager {
|
|||||||
private final AtomicInteger clientIdCounter = new AtomicInteger(0);
|
private final AtomicInteger clientIdCounter = new AtomicInteger(0);
|
||||||
|
|
||||||
|
|
||||||
public IPCManager(Properties config){
|
public IPCManager(Properties config, DelegateActionManager actionManager){
|
||||||
configuration = config;
|
configuration = config;
|
||||||
|
this.actionManager = actionManager;
|
||||||
logger.debug("IPCManager created with configuration:");
|
logger.debug("IPCManager created with configuration:");
|
||||||
|
|
||||||
|
|
||||||
@@ -219,24 +223,25 @@ public class IPCManager {
|
|||||||
logger.debug("Client {} handler thread started", clientId);
|
logger.debug("Client {} handler thread started", clientId);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// TODO: No próximo passo, vamos implementar:
|
TransportProtocol.Request request = readRequest(channel);
|
||||||
// 1. Ler mensagens JSON do SocketChannel
|
|
||||||
// 2. Parsear o JSON para objetos Java
|
|
||||||
// 3. Processar a requisição
|
|
||||||
// 4. Criar uma resposta JSON
|
|
||||||
// 5. Escrever a resposta de volta no SocketChannel
|
|
||||||
|
|
||||||
// Por enquanto, apenas mantém a conexão aberta brevemente
|
if (request != null) {
|
||||||
// para testar que o sistema de aceitação e threads está funcionando
|
logger.info("Client {} sent request {}", clientId, request.getRequestId());
|
||||||
Thread.sleep(100);
|
|
||||||
|
|
||||||
logger.debug("Client {} processing complete", clientId);
|
// Processa usando o DelegateActionManager
|
||||||
|
TransportProtocol.Response response = actionManager.ProcessedRequest(request);
|
||||||
|
|
||||||
|
// Envia resposta de volta
|
||||||
|
writeResponse(channel, response);
|
||||||
|
|
||||||
|
logger.info("Client {} response sent", clientId);
|
||||||
|
} else {
|
||||||
|
logger.warn("Client {} sent null message", clientId);
|
||||||
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("Error handling client {}", clientId, e);
|
logger.error("Error handling client {}", clientId, e);
|
||||||
} finally {
|
} finally {
|
||||||
// SEMPRE fecha o canal quando terminar
|
|
||||||
// O finally garante que isso acontece mesmo se houver exceção
|
|
||||||
try {
|
try {
|
||||||
channel.close();
|
channel.close();
|
||||||
logger.debug("Client {} channel closed", clientId);
|
logger.debug("Client {} channel closed", clientId);
|
||||||
@@ -245,6 +250,67 @@ public class IPCManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private TransportProtocol.Request readRequest(SocketChannel channel) throws IOException {
|
||||||
|
// Primeiro, lê o tamanho da mensagem (4 bytes = int32)
|
||||||
|
java.nio.ByteBuffer sizeBuffer = java.nio.ByteBuffer.allocate(4);
|
||||||
|
int bytesRead = 0;
|
||||||
|
|
||||||
|
while (bytesRead < 4) {
|
||||||
|
int read = channel.read(sizeBuffer);
|
||||||
|
if (read == -1) {
|
||||||
|
logger.debug("Client disconnected before sending size");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
bytesRead += read;
|
||||||
|
}
|
||||||
|
|
||||||
|
sizeBuffer.flip();
|
||||||
|
int messageSize = sizeBuffer.getInt();
|
||||||
|
logger.debug("Expecting message of {} bytes", messageSize);
|
||||||
|
|
||||||
|
// Validação básica de segurança
|
||||||
|
if (messageSize <= 0 || messageSize > 1024 * 1024) { // Max 1MB
|
||||||
|
throw new IOException("Invalid message size: " + messageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agora lê a mensagem completa
|
||||||
|
java.nio.ByteBuffer messageBuffer = java.nio.ByteBuffer.allocate(messageSize);
|
||||||
|
bytesRead = 0;
|
||||||
|
|
||||||
|
while (bytesRead < messageSize) {
|
||||||
|
int read = channel.read(messageBuffer);
|
||||||
|
if (read == -1) {
|
||||||
|
throw new IOException("Client disconnected while reading message");
|
||||||
|
}
|
||||||
|
bytesRead += read;
|
||||||
|
}
|
||||||
|
|
||||||
|
messageBuffer.flip();
|
||||||
|
|
||||||
|
// Deserializa o Protocol Buffers
|
||||||
|
byte[] messageBytes = new byte[messageSize];
|
||||||
|
messageBuffer.get(messageBytes);
|
||||||
|
|
||||||
|
return TransportProtocol.Request.parseFrom(messageBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeResponse(SocketChannel channel, TransportProtocol.Response response) throws IOException {
|
||||||
|
byte[] messageBytes = response.toByteArray();
|
||||||
|
int messageSize = messageBytes.length;
|
||||||
|
|
||||||
|
logger.debug("Writing response of {} bytes", messageSize);
|
||||||
|
|
||||||
|
java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(4 + messageSize);
|
||||||
|
buffer.putInt(messageSize);
|
||||||
|
buffer.put(messageBytes);
|
||||||
|
buffer.flip();
|
||||||
|
|
||||||
|
while (buffer.hasRemaining()) {
|
||||||
|
channel.write(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug("Response written successfully");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
option java_package = "com.mediamanager.protocol";
|
||||||
|
option java_outer_classname = "TransportProtocol";
|
||||||
|
|
||||||
|
package mediamanager;
|
||||||
|
|
||||||
|
message Request {
|
||||||
|
string request_id = 1;
|
||||||
|
bytes payload = 2;
|
||||||
|
map<string, string> headers = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message Response {
|
||||||
|
string request_id = 1;
|
||||||
|
int32 status_code = 2;
|
||||||
|
bytes payload = 3;
|
||||||
|
map<string, string> headers = 4;
|
||||||
|
}
|
||||||
@@ -23,4 +23,5 @@ ipc.pipe.path=/tmp/mediamanager
|
|||||||
ipc.buffer.size=8192
|
ipc.buffer.size=8192
|
||||||
|
|
||||||
ipc.socket.path=/tmp/mediamanager
|
ipc.socket.path=/tmp/mediamanager
|
||||||
|
runtype=local
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,29 @@
|
|||||||
<AppenderRef ref="FileAppender"/>
|
<AppenderRef ref="FileAppender"/>
|
||||||
</Logger>
|
</Logger>
|
||||||
|
|
||||||
|
<Logger name="io.zonky.test" level="INFO" additivity="false">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
<AppenderRef ref="FileAppender"/>
|
||||||
|
</Logger>
|
||||||
|
|
||||||
|
<!-- PostgreSQL JDBC Driver -->
|
||||||
|
<Logger name="org.postgresql" level="WARN" additivity="false">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
<AppenderRef ref="FileAppender"/>
|
||||||
|
</Logger>
|
||||||
|
|
||||||
|
<!-- Processo do PostgreSQL embedded -->
|
||||||
|
<Logger name="org.postgresql.embedded" level="INFO" additivity="false">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
<AppenderRef ref="FileAppender"/>
|
||||||
|
</Logger>
|
||||||
|
|
||||||
|
<!-- HikariCP Connection Pool -->
|
||||||
|
<Logger name="com.zaxxer.hikari" level="INFO" additivity="false">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
<AppenderRef ref="FileAppender"/>
|
||||||
|
</Logger>
|
||||||
|
|
||||||
<Root level="info">
|
<Root level="info">
|
||||||
<AppenderRef ref="Console"/>
|
<AppenderRef ref="Console"/>
|
||||||
<AppenderRef ref="FileAppender"/>
|
<AppenderRef ref="FileAppender"/>
|
||||||
|
|||||||
Reference in New Issue
Block a user