Ether Framework
Unified API docs for Ether modules
Loading...
Searching...
No Matches
JettyWebSocketEndpointAdapter.java
Go to the documentation of this file.
1package dev.rafex.ether.websocket.jetty12;
2
3/*-
4 * #%L
5 * ether-websocket-jetty12
6 * %%
7 * Copyright (C) 2025 - 2026 Raúl Eduardo González Argote
8 * %%
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 * #L%
27 */
28
29import java.nio.ByteBuffer;
30import java.util.List;
31import java.util.Map;
32import java.util.UUID;
33
34import org.eclipse.jetty.websocket.api.Callback;
35import org.eclipse.jetty.websocket.api.Session;
36
37import dev.rafex.ether.websocket.core.WebSocketCloseStatus;
38import dev.rafex.ether.websocket.core.WebSocketEndpoint;
39
40/**
41 * Adapta una instancia de {@link WebSocketEndpoint} al Listener de Jetty 12.
42 *
43 * <p>Esta clase traduce los eventos del ciclo de vida de Jetty a las llamadas
44 * definidas en la interfaz {@link WebSocketEndpoint}.</p>
45 */
46public final class JettyWebSocketEndpointAdapter implements Session.Listener.AutoDemanding {
47
48 private final WebSocketEndpoint endpoint;
49 private final String path;
50 private final Map<String, String> pathParams;
51 private final Map<String, List<String>> queryParams;
52 private final Map<String, List<String>> headers;
53 private volatile JettyWebSocketSession session;
54
55 /**
56 * Crea un adaptador para el endpoint dado.
57 *
58 * @param endpoint el endpoint personalizado que manejará los eventos
59 * @param path la ruta asociada a la conexión
60 * @param pathParams parámetros extraídos de la ruta
61 * @param queryParams parámetros de la consulta HTTP
62 * @param headers cabeceras HTTP
63 */
64 public JettyWebSocketEndpointAdapter(final WebSocketEndpoint endpoint, final String path,
65 final Map<String, String> pathParams, final Map<String, List<String>> queryParams,
66 final Map<String, List<String>> headers) {
67 this.endpoint = endpoint;
68 this.path = path;
69 this.pathParams = pathParams;
70 this.queryParams = queryParams;
71 this.headers = headers;
72 }
73
74 @Override
75 public void onWebSocketOpen(final Session session) {
76 this.session = new JettyWebSocketSession(session, path, pathParams, queryParams, headers);
77 this.session.attribute("requestId", resolveRequestId(headers));
78 try {
79 endpoint.onOpen(this.session);
80 } catch (final Exception e) {
81 handleFailure(e);
82 }
83 }
84
85 @Override
86 public void onWebSocketText(final String message) {
87 try {
88 endpoint.onText(session, message);
89 } catch (final Exception e) {
90 handleFailure(e);
91 }
92 }
93
94 @Override
95 public void onWebSocketBinary(final ByteBuffer payload, final Callback callback) {
96 try {
97 endpoint.onBinary(session, payload == null ? ByteBuffer.allocate(0) : payload.slice());
98 callback.succeed();
99 } catch (final Exception e) {
100 callback.fail(e);
101 handleFailure(e);
102 }
103 }
104
105 @Override
106 public void onWebSocketPartialText(final String payload, final boolean fin) {
107 if (fin) {
108 onWebSocketText(payload);
109 return;
110 }
111 onWebSocketClose(WebSocketCloseStatus.PROTOCOL_ERROR.code(),
112 "unsupported:text_fragmentation", Callback.NOOP);
113 }
114
115 @Override
116 public void onWebSocketPartialBinary(final ByteBuffer payload, final boolean fin, final Callback callback) {
117 if (fin) {
118 onWebSocketBinary(payload, callback);
119 return;
120 }
121 callback.fail(new UnsupportedOperationException("unsupported: binary fragmentation"));
122 handleFailure(new UnsupportedOperationException("unsupported: binary fragmentation"));
123 }
124
125 @Override
126 public void onWebSocketClose(final int statusCode, final String reason, final Callback callback) {
127 if (session == null) {
128 callback.succeed();
129 return;
130 }
131 try {
132 endpoint.onClose(session, WebSocketCloseStatus.of(statusCode, reason));
133 callback.succeed();
134 } catch (final Exception e) {
135 endpoint.onError(session, e);
136 callback.fail(e);
137 }
138 }
139
140 private void handleFailure(final Exception error) {
141 endpoint.onError(session, error);
142 if (session != null && session.isOpen()) {
143 session.close(WebSocketCloseStatus.SERVER_ERROR);
144 }
145 }
146
147 private static String resolveRequestId(final Map<String, List<String>> headers) {
148 final var values = headers.get("x-request-id");
149 if (values != null && !values.isEmpty() && values.get(0) != null && !values.get(0).isBlank()) {
150 return values.get(0);
151 }
152 return UUID.randomUUID().toString();
153 }
154
155 @Override
156 public void onWebSocketError(final Throwable cause) {
157 if (session == null) {
158 return;
159 }
160 endpoint.onError(session, cause);
161 }
162}
void onWebSocketBinary(final ByteBuffer payload, final Callback callback)
void onWebSocketClose(final int statusCode, final String reason, final Callback callback)
void onWebSocketPartialBinary(final ByteBuffer payload, final boolean fin, final Callback callback)
JettyWebSocketEndpointAdapter(final WebSocketEndpoint endpoint, final String path, final Map< String, String > pathParams, final Map< String, List< String > > queryParams, final Map< String, List< String > > headers)
Crea un adaptador para el endpoint dado.
boolean isOpen()
Returns whether the underlying session is still open.
CompletionStage< Void > close(final WebSocketCloseStatus status)
Closes the session with the given status code and reason.
Define el contrato de un punto final WebSocket.
default void onError(final WebSocketSession session, final Throwable error)
Invocado cuando ocurre un error en la conexión WebSocket.