From bd757fc731751e2b545645ac8a07cf9fecad16fd Mon Sep 17 00:00:00 2001 From: Thibaut Valentin Date: Fri, 8 Mar 2024 16:30:08 +0100 Subject: [PATCH] wip: test ws --- pom.xml | 5 ++ .../fr/titionfire/ffsaf/ws/FileSocket.java | 84 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 src/main/java/fr/titionfire/ffsaf/ws/FileSocket.java diff --git a/pom.xml b/pom.xml index 64b4168..6c3aafc 100644 --- a/pom.xml +++ b/pom.xml @@ -104,6 +104,11 @@ jodd-util 6.2.1 + + + io.quarkus + quarkus-websockets + diff --git a/src/main/java/fr/titionfire/ffsaf/ws/FileSocket.java b/src/main/java/fr/titionfire/ffsaf/ws/FileSocket.java new file mode 100644 index 0000000..be5e725 --- /dev/null +++ b/src/main/java/fr/titionfire/ffsaf/ws/FileSocket.java @@ -0,0 +1,84 @@ +package fr.titionfire.ffsaf.ws; + +import io.quarkus.runtime.annotations.RegisterForReflection; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.websocket.*; +import jakarta.websocket.server.PathParam; +import jakarta.websocket.server.ServerEndpoint; +import lombok.AllArgsConstructor; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@ServerEndpoint("/api/ws/file/{id}") +@ApplicationScoped +public class FileSocket { + Map sessions = new ConcurrentHashMap<>(); + + @OnOpen + public void onOpen(Session session, @PathParam("id") String id) { + try { + File file = File.createTempFile("safca-", ".tmp"); + FileRecv fileRecv = new FileRecv(file, new FileOutputStream(file, true), System.currentTimeMillis(), + session); + System.out.println("File created: " + file.getAbsolutePath()); + sessions.put(id, fileRecv); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @OnClose + public void onClose(Session session, @PathParam("id") String id) { + if (sessions.containsKey(id)) { + FileRecv fileRecv = sessions.get(id); + if (fileRecv.fos != null) { + try { + fileRecv.fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + sessions.remove(id); + } + + @OnError + public void onError(Session session, @PathParam("id") String id, Throwable throwable) { + if (sessions.containsKey(id)) { + FileRecv fileRecv = sessions.get(id); + if (fileRecv.fos != null) { + try { + fileRecv.fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + sessions.remove(id); + } + + @OnMessage + public void onMessage(String message, @PathParam("id") String id) { + if (sessions.containsKey(id)) { + FileRecv fileRecv = sessions.get(id); + try { + fileRecv.fos.write(message.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @AllArgsConstructor + @RegisterForReflection + class FileRecv { + File file; + FileOutputStream fos; + long time; + Session session; + } +}