mirror of
https://github.com/gmbrax/MediaManager-core.git
synced 2026-11-09 22:10:17 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3998b18671 |
@@ -13,7 +13,7 @@
|
|||||||
<maven.compiler.target>17</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<hibernate.version>7.1.7.Final</hibernate.version>
|
<hibernate.version>7.1.7.Final</hibernate.version>
|
||||||
<postgresql.version>42.7.7</postgresql.version>
|
<postgresql.version>42.7.5</postgresql.version>
|
||||||
<hikaricp.version>5.1.0</hikaricp.version>
|
<hikaricp.version>5.1.0</hikaricp.version>
|
||||||
<log4j.version>2.23.1</log4j.version>
|
<log4j.version>2.23.1</log4j.version>
|
||||||
<junit.version>5.10.2</junit.version>
|
<junit.version>5.10.2</junit.version>
|
||||||
@@ -78,22 +78,9 @@
|
|||||||
<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>
|
|
||||||
</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>
|
||||||
@@ -104,54 +91,12 @@
|
|||||||
<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,6 +1,5 @@
|
|||||||
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;
|
||||||
@@ -15,7 +14,6 @@ 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 DatabaseManager databaseManager;
|
||||||
private static DelegateActionManager actionManager;
|
|
||||||
private static IPCManager ipcManager;
|
private static IPCManager ipcManager;
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
@@ -26,9 +24,8 @@ public class MediaManagerApplication {
|
|||||||
loadConfiguration();
|
loadConfiguration();
|
||||||
databaseManager = new DatabaseManager(config);
|
databaseManager = new DatabaseManager(config);
|
||||||
databaseManager.init();
|
databaseManager.init();
|
||||||
actionManager = new DelegateActionManager();
|
|
||||||
actionManager.start();
|
ipcManager = new IPCManager(config);
|
||||||
ipcManager = new IPCManager(config,actionManager);
|
|
||||||
ipcManager.init();
|
ipcManager.init();
|
||||||
|
|
||||||
// TODO: Start application services
|
// TODO: Start application services
|
||||||
@@ -54,9 +51,6 @@ 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,11 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
package com.mediamanager.service.delegate;
|
|
||||||
|
|
||||||
import com.google.protobuf.ByteString;
|
|
||||||
import com.mediamanager.protocol.TransportProtocol;
|
|
||||||
import com.mediamanager.service.delegate.handler.CloseHandler;
|
|
||||||
import com.mediamanager.service.delegate.handler.EchoHandler;
|
|
||||||
import com.mediamanager.service.delegate.handler.HeartbeatHandler;
|
|
||||||
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());
|
|
||||||
handlerRegistry.put("heartbeat",new HeartbeatHandler());
|
|
||||||
handlerRegistry.put("close", new CloseHandler());
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package com.mediamanager.service.delegate.handler;
|
|
||||||
|
|
||||||
import com.google.protobuf.ByteString;
|
|
||||||
import com.google.protobuf.InvalidProtocolBufferException;
|
|
||||||
import com.mediamanager.protocol.TestProtocol.CloseCommand;
|
|
||||||
import com.mediamanager.protocol.TestProtocol.CloseResponse;
|
|
||||||
import com.mediamanager.protocol.TransportProtocol;
|
|
||||||
import com.mediamanager.service.delegate.ActionHandler;
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
|
|
||||||
public class CloseHandler implements ActionHandler {
|
|
||||||
private static final Logger logger = LogManager.getLogger(CloseHandler.class);
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public TransportProtocol.Response.Builder handle(ByteString requestPayload)
|
|
||||||
throws InvalidProtocolBufferException {
|
|
||||||
|
|
||||||
CloseCommand.parseFrom(requestPayload); // Valida
|
|
||||||
|
|
||||||
logger.info("Close command received - connection will close");
|
|
||||||
|
|
||||||
CloseResponse response = CloseResponse.newBuilder()
|
|
||||||
.setMessage("Connection closing. Goodbye!")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
return TransportProtocol.Response.newBuilder()
|
|
||||||
.setPayload(ByteString.copyFrom(response.toByteArray()))
|
|
||||||
.setStatusCode(200)
|
|
||||||
.putHeaders("Connection", "close"); // ← Marca para fechar
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package com.mediamanager.service.delegate.handler;
|
|
||||||
|
|
||||||
import com.google.protobuf.ByteString;
|
|
||||||
import com.google.protobuf.InvalidProtocolBufferException;
|
|
||||||
import com.mediamanager.protocol.TestProtocol.EchoCommand; // ← Import
|
|
||||||
import com.mediamanager.protocol.TestProtocol.EchoResponse; // ← Import
|
|
||||||
import com.mediamanager.protocol.TransportProtocol;
|
|
||||||
import com.mediamanager.service.delegate.ActionHandler;
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
|
|
||||||
public class EchoHandler implements ActionHandler {
|
|
||||||
private static final Logger logger = LogManager.getLogger(EchoHandler.class);
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public TransportProtocol.Response.Builder handle(ByteString requestPayload)
|
|
||||||
throws InvalidProtocolBufferException { // ← Pode lançar exceção
|
|
||||||
|
|
||||||
// 1. Parse Protobuf bytes → EchoCommand
|
|
||||||
EchoCommand command = EchoCommand.parseFrom(requestPayload);
|
|
||||||
|
|
||||||
logger.debug("Echo received: {}", command.getMessage());
|
|
||||||
|
|
||||||
// 2. Cria EchoResponse (Protobuf)
|
|
||||||
EchoResponse echoResponse = EchoResponse.newBuilder()
|
|
||||||
.setMessage(command.getMessage())
|
|
||||||
.setServerTimestamp(System.currentTimeMillis())
|
|
||||||
.build();
|
|
||||||
|
|
||||||
// 3. Serializa EchoResponse → bytes
|
|
||||||
ByteString responsePayload = ByteString.copyFrom(echoResponse.toByteArray());
|
|
||||||
|
|
||||||
// 4. Retorna Response
|
|
||||||
return TransportProtocol.Response.newBuilder()
|
|
||||||
.setPayload(responsePayload)
|
|
||||||
.setStatusCode(200);
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package com.mediamanager.service.delegate.handler;
|
|
||||||
|
|
||||||
import com.google.protobuf.ByteString;
|
|
||||||
import com.google.protobuf.InvalidProtocolBufferException;
|
|
||||||
import com.mediamanager.protocol.TestProtocol.HeartbeatCommand;
|
|
||||||
import com.mediamanager.protocol.TestProtocol.HeartbeatResponse;
|
|
||||||
import com.mediamanager.protocol.TransportProtocol;
|
|
||||||
import com.mediamanager.service.delegate.ActionHandler;
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
|
|
||||||
public class HeartbeatHandler implements ActionHandler {
|
|
||||||
private static final Logger logger = LogManager.getLogger(HeartbeatHandler.class);
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public TransportProtocol.Response.Builder handle(ByteString requestPayload)
|
|
||||||
throws InvalidProtocolBufferException {
|
|
||||||
|
|
||||||
HeartbeatCommand command = HeartbeatCommand.parseFrom(requestPayload);
|
|
||||||
|
|
||||||
long serverTime = System.currentTimeMillis();
|
|
||||||
|
|
||||||
logger.debug("Heartbeat received. Client T1={}, Server T2={}",
|
|
||||||
command.getClientTimestamp(), serverTime);
|
|
||||||
|
|
||||||
HeartbeatResponse response = HeartbeatResponse.newBuilder()
|
|
||||||
.setClientTimestamp(command.getClientTimestamp()) // Echo T1
|
|
||||||
.setServerTimestamp(serverTime) // T2
|
|
||||||
.build();
|
|
||||||
|
|
||||||
return TransportProtocol.Response.newBuilder()
|
|
||||||
.setPayload(ByteString.copyFrom(response.toByteArray()))
|
|
||||||
.setStatusCode(200);
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
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;
|
||||||
@@ -27,8 +26,6 @@ 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;
|
||||||
@@ -38,9 +35,8 @@ public class IPCManager {
|
|||||||
private final AtomicInteger clientIdCounter = new AtomicInteger(0);
|
private final AtomicInteger clientIdCounter = new AtomicInteger(0);
|
||||||
|
|
||||||
|
|
||||||
public IPCManager(Properties config, DelegateActionManager actionManager){
|
public IPCManager(Properties config){
|
||||||
configuration = config;
|
configuration = config;
|
||||||
this.actionManager = actionManager;
|
|
||||||
logger.debug("IPCManager created with configuration:");
|
logger.debug("IPCManager created with configuration:");
|
||||||
|
|
||||||
|
|
||||||
@@ -185,7 +181,7 @@ public class IPCManager {
|
|||||||
// Nenhum cliente conectado no momento
|
// Nenhum cliente conectado no momento
|
||||||
// Dorme por um curto período antes de verificar novamente
|
// Dorme por um curto período antes de verificar novamente
|
||||||
// Isso evita consumir CPU desnecessariamente em um loop vazio
|
// Isso evita consumir CPU desnecessariamente em um loop vazio
|
||||||
Thread.sleep(1); // 1 milissegundos
|
Thread.sleep(100); // 100 milissegundos
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
@@ -223,113 +219,32 @@ public class IPCManager {
|
|||||||
logger.debug("Client {} handler thread started", clientId);
|
logger.debug("Client {} handler thread started", clientId);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// LOOP: processa múltiplas requests na mesma conexão
|
// TODO: No próximo passo, vamos implementar:
|
||||||
while (channel.isOpen()) {
|
// 1. Ler mensagens JSON do SocketChannel
|
||||||
TransportProtocol.Request request = readRequest(channel);
|
// 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
|
||||||
|
|
||||||
if (request == null) {
|
// Por enquanto, apenas mantém a conexão aberta brevemente
|
||||||
// Cliente desconectou gracefully
|
// para testar que o sistema de aceitação e threads está funcionando
|
||||||
logger.info("Client {} disconnected (end of stream)", clientId);
|
Thread.sleep(100);
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info("Client {} sent request {}", clientId, request.getRequestId());
|
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);
|
|
||||||
|
|
||||||
// Verifica se é comando CLOSE
|
|
||||||
String connectionHeader = response.getHeadersOrDefault("Connection", "");
|
|
||||||
if ("close".equals(connectionHeader)) {
|
|
||||||
logger.info("Client {} requested connection close", clientId);
|
|
||||||
break; // Sai do loop e fecha
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (channel.isOpen()) {
|
|
||||||
logger.error("IO error handling client {}", clientId, e);
|
|
||||||
} else {
|
|
||||||
logger.debug("Client {} connection closed by peer", clientId);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("Unexpected 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 {
|
||||||
if (channel.isOpen()) {
|
|
||||||
channel.close();
|
channel.close();
|
||||||
}
|
|
||||||
logger.debug("Client {} channel closed", clientId);
|
logger.debug("Client {} channel closed", clientId);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("Error closing client {} channel", clientId, e);
|
logger.error("Error closing client {} channel", clientId, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
option java_package = "com.mediamanager.protocol";
|
|
||||||
option java_outer_classname = "TestProtocol";
|
|
||||||
|
|
||||||
package mediamanager.test;
|
|
||||||
|
|
||||||
message EchoCommand {
|
|
||||||
string message = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EchoResponse {
|
|
||||||
string message = 1;
|
|
||||||
int64 server_timestamp = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message HeartbeatCommand {
|
|
||||||
int64 client_timestamp = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message HeartbeatResponse {
|
|
||||||
int64 client_timestamp = 1;
|
|
||||||
int64 server_timestamp = 2;
|
|
||||||
}
|
|
||||||
message CloseCommand {
|
|
||||||
// Vazio - apenas sinaliza fechamento
|
|
||||||
}
|
|
||||||
message CloseResponse {
|
|
||||||
string message = 1;
|
|
||||||
}
|
|
||||||
@@ -18,17 +18,17 @@
|
|||||||
</Appenders>
|
</Appenders>
|
||||||
|
|
||||||
<Loggers>
|
<Loggers>
|
||||||
<Logger name="com.mediamanager" level="INFO" additivity="false">
|
<Logger name="com.mediamanager" level="debug" additivity="false">
|
||||||
<AppenderRef ref="Console"/>
|
<AppenderRef ref="Console"/>
|
||||||
<AppenderRef ref="FileAppender"/>
|
<AppenderRef ref="FileAppender"/>
|
||||||
</Logger>
|
</Logger>
|
||||||
|
|
||||||
<Logger name="org.hibernate" level="INFO" additivity="false">
|
<Logger name="org.hibernate" level="info" additivity="false">
|
||||||
<AppenderRef ref="Console"/>
|
<AppenderRef ref="Console"/>
|
||||||
<AppenderRef ref="FileAppender"/>
|
<AppenderRef ref="FileAppender"/>
|
||||||
</Logger>
|
</Logger>
|
||||||
|
|
||||||
<Root level="INFO">
|
<Root level="info">
|
||||||
<AppenderRef ref="Console"/>
|
<AppenderRef ref="Console"/>
|
||||||
<AppenderRef ref="FileAppender"/>
|
<AppenderRef ref="FileAppender"/>
|
||||||
</Root>
|
</Root>
|
||||||
|
|||||||
Reference in New Issue
Block a user