From 9fca342a86463562b3582c218f9bc6d4116018e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrejs=20Mivre=C5=86iks?= Date: Mon, 27 Nov 2017 22:02:56 +0200 Subject: [PATCH] Rewrite StompClient to use a different WebSocket client implementation --- README.md | 76 ++-- example/build.gradle | 2 +- .../stomp/example/StompClientExample.java | 35 +- stomp-client-ws/build.gradle | 4 +- .../eu/mivrenik/stomp/client/StompClient.java | 335 +++++++++--------- .../stomp/client}/StompSubscription.java | 4 +- .../listener/StompConnectionListener.java | 25 ++ .../listener}/StompMessageListener.java | 12 +- stomp/build.gradle | 2 +- .../java/eu/mivrenik/stomp/StompFrame.java | 68 ++-- 10 files changed, 313 insertions(+), 250 deletions(-) rename {stomp/src/main/java/eu/mivrenik/stomp => stomp-client-ws/src/main/java/eu/mivrenik/stomp/client}/StompSubscription.java (94%) create mode 100644 stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener/StompConnectionListener.java rename {stomp/src/main/java/eu/mivrenik/stomp => stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener}/StompMessageListener.java (83%) diff --git a/README.md b/README.md index 666f9ec..0a6fe5d 100644 --- a/README.md +++ b/README.md @@ -4,22 +4,25 @@ This is a [STOMP](http://eu.mivrenik.stomp.github.io/) protocol implementation. ## Example backend using Spring Boot +The following example is taken from Spring's ["Using WebSocket to build an interactive web application"](https://spring.io/guides/gs/messaging-stomp-websocket/) guide but with SockJS disabled. + ### Configuration ```java @Configuration -public class WebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer { +@EnableWebSocketMessageBroker +public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { - @Override - public void configureMessageBroker(MessageBrokerRegistry config) { - config.enableSimpleBroker("/topic"); - config.setApplicationDestinationPrefixes("/app"); - } + @Override + public void configureMessageBroker(MessageBrokerRegistry config) { + config.enableSimpleBroker("/topic"); + config.setApplicationDestinationPrefixes("/app"); + } - @Override - public void registerStompEndpoints(StompEndpointRegistry registry) { - registry.addEndpoint("/hello"); - } + @Override + public void registerStompEndpoints(StompEndpointRegistry registry) { + registry.addEndpoint("/gs-guide-websocket"); + } } ``` @@ -29,40 +32,49 @@ public class WebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBr @Controller public class GreetingController { - @MessageMapping("/hello") - @SendTo("/topic/greetings") - public String greeting(String message) throws Exception { - return "Hello, " + message + "!"; - } + @MessageMapping("/hello") + @SendTo("/topic/greetings") + public Greeting greeting(HelloMessage message) throws Exception { + Thread.sleep(1000); // simulated delay + return new Greeting("Hello, " + message.getName() + "!"); + } } ``` ## Usage +See the included client [example module](example). + ```java -StompClient stompClient; +final StompClient stompSocket = new StompClient(URI.create("ws://localhost:8080/gs-guide-websocket")); + +// Wait for a connection to establish +boolean connected; try { - stompClient = new StompClient("ws://localhost:7777/hello"); - stompClient.connect(); -} catch (WebSocketException | IOException e) { - e.printStackTrace(); - return; + connected = stompSocket.connectBlocking(); +} catch (InterruptedException e) { + e.printStackTrace(); + return; +} + +if (!connected) { + System.out.println("Failed to connect to the socket"); + return; } // Subscribing to a topic -stompClient.subscribe("/topic/greetings", new StompMessageListener() { +stompSocket.subscribe("/topic/greetings", new StompMessageListener() { - @Override - public void onMessage(String message) { - System.out.println("Server message: " + message); - } + @Override + public void onMessage(String message) { + System.out.println("Server message: " + message); + + // Disconnect + stompSocket.close(); + } }); // Sending JSON message to a server -String message = "Jack"; -stompClient.send("/app/hello", message); - -// ... -// Disconnect at some point -// stompClient.disconnect(); +String message = "{\"name\": \"Jack\"}"; +stompSocket.send("/app/hello", message); ``` diff --git a/example/build.gradle b/example/build.gradle index 758e49c..a417854 100644 --- a/example/build.gradle +++ b/example/build.gradle @@ -3,7 +3,7 @@ version '0.1' apply plugin: 'java' -sourceCompatibility = 1.8 +sourceCompatibility = 1.7 repositories { mavenCentral() diff --git a/example/src/main/java/eu/mivrenik/stomp/example/StompClientExample.java b/example/src/main/java/eu/mivrenik/stomp/example/StompClientExample.java index 8f33082..e216e36 100644 --- a/example/src/main/java/eu/mivrenik/stomp/example/StompClientExample.java +++ b/example/src/main/java/eu/mivrenik/stomp/example/StompClientExample.java @@ -1,34 +1,43 @@ package eu.mivrenik.stomp.example; -import com.neovisionaries.ws.client.WebSocketException; -import eu.mivrenik.stomp.StompMessageListener; +import eu.mivrenik.stomp.StompFrame; import eu.mivrenik.stomp.client.StompClient; +import eu.mivrenik.stomp.client.listener.StompMessageListener; -import java.io.IOException; +import java.net.URI; public class StompClientExample { public static void main(String[] args) { - StompClient stompClient; + final StompClient stompSocket = new StompClient(URI.create("ws://localhost:8080/gs-guide-websocket")); + + // Wait for a connection to establish + boolean connected; try { - stompClient = new StompClient("ws://localhost:7777/hello"); - stompClient.connect(); - } catch (WebSocketException | IOException e) { + connected = stompSocket.connectBlocking(); + } catch (InterruptedException e) { e.printStackTrace(); return; } + if (!connected) { + System.out.println("Failed to connect to the socket"); + return; + } - // Subscribing to a topic - stompClient.subscribe("/topic/greetings", new StompMessageListener() { + // Subscribing to a topic once STOMP connection is established + stompSocket.subscribe("/topic/greetings", new StompMessageListener() { @Override - public void onMessage(String message) { - System.out.println("Server message: " + message); + public void onMessage(StompFrame stompFrame) { + System.out.println("Server message: " + stompFrame.getBody()); + + // Disconnect + stompSocket.close(); } }); // Sending JSON message to a server - String message = "Jack"; - stompClient.send("/app/hello", message); + String message = "{\"name\": \"Jack\"}"; + stompSocket.send("/app/hello", message); } } diff --git a/stomp-client-ws/build.gradle b/stomp-client-ws/build.gradle index 40b0e99..af8e903 100644 --- a/stomp-client-ws/build.gradle +++ b/stomp-client-ws/build.gradle @@ -3,7 +3,7 @@ version '0.1' apply plugin: 'java' -sourceCompatibility = 1.8 +sourceCompatibility = 1.7 repositories { mavenCentral() @@ -11,5 +11,5 @@ repositories { dependencies { compile project(':stomp') - compile 'com.neovisionaries:nv-websocket-client:1.30' + compile 'org.java-websocket:Java-WebSocket:1.3.6' } diff --git a/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/StompClient.java b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/StompClient.java index 47ba97e..59f9538 100644 --- a/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/StompClient.java +++ b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/StompClient.java @@ -21,237 +21,238 @@ */ package eu.mivrenik.stomp.client; -import com.neovisionaries.ws.client.WebSocket; -import com.neovisionaries.ws.client.WebSocketException; -import com.neovisionaries.ws.client.WebSocketFactory; -import com.neovisionaries.ws.client.WebSocketFrame; -import com.neovisionaries.ws.client.WebSocketListener; -import com.neovisionaries.ws.client.WebSocketState; import eu.mivrenik.stomp.StompCommand; import eu.mivrenik.stomp.StompFrame; import eu.mivrenik.stomp.StompHeader; -import eu.mivrenik.stomp.StompMessageListener; -import eu.mivrenik.stomp.StompSubscription; +import eu.mivrenik.stomp.client.listener.StompConnectionListener; +import eu.mivrenik.stomp.client.listener.StompMessageListener; +import org.java_websocket.WebSocketListener; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.drafts.Draft; +import org.java_websocket.handshake.ServerHandshake; import java.io.IOException; +import java.net.URI; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; /** - * STOMP v1.2 client using `nv-websocket-client` WebSocket client - * implementation. - * - * @see https://eu.mivrenik.stomp.github.io/eu.mivrenik.stomp-specification-1.2.html - * @see https://github.com/TakahikoKawasaki/nv-websocket-client + * STOMP v1.2 client using `Java-WebSocket` WebSocket client implementation. + *

+ * {@see https://eu.mivrenik.stomp.github.io/eu.mivrenik.stomp-specification-1.2.html} + * {@see https://github.com/TooTallNate/Java-WebSocket} */ -public class StompClient { +public class StompClient extends WebSocketClient { + /** + * Current STOMP implementation version. + */ private static final String STOMP_VERSION = "1.2"; - private final Map subscriptions = new HashMap<>(); - private WebSocket webSocket; + + /** + * STOMP topic subscription listeners. + */ + private Map subscriptions = new HashMap<>(); + + /** + * STOMP connection status. + */ private boolean stompConnected; - public StompClient(String url) throws IOException { - this.webSocket = new WebSocketFactory().createSocket(url); - this.webSocket.addListener(webSocketListener); + /** + * STOMP connection listener. + */ + private StompConnectionListener stompConnectionListener; + + /** + * {@inheritDoc} + */ + public StompClient(URI serverUri) { + super(serverUri); } - public void connect() throws WebSocketException, IOException { - if (webSocket.getState() != WebSocketState.CREATED) { - webSocket = webSocket.recreate(); - } - webSocket.connect(); + /** + * {@inheritDoc} + */ + public StompClient(URI serverUri, Draft protocolDraft) { + super(serverUri, protocolDraft); + } + + /** + * {@inheritDoc} + */ + public StompClient(URI serverUri, Draft protocolDraft, Map httpHeaders, int connectTimeout) { + super(serverUri, protocolDraft, httpHeaders, connectTimeout); + } + + @Override + public void onOpen(ServerHandshake handshakedata) { connectStomp(); } + @Override + public void onMessage(String message) { + StompFrame stompFrame = StompFrame.fromString(message); + + switch (stompFrame.getCommand()) { + case CONNECTED: + stompConnected = true; + if (stompConnectionListener != null) { + stompConnectionListener.onConnected(); + } + break; + case MESSAGE: + Integer subscriptionId = Integer.valueOf( + stompFrame.getHeaders().get(StompHeader.SUBSCRIPTION.toString()) + ); + subscriptions.get(subscriptionId).getListener().onMessage(stompFrame); + break; + case DISCONNECT: + stompConnected = false; + if (stompConnectionListener != null) { + stompConnectionListener.onDisconnected(); + } + break; + default: + break; + } + } + + @Override + public void onClose(int code, String reason, boolean remote) { + stompConnected = false; + if (stompConnectionListener != null) { + stompConnectionListener.onDisconnected(); + } + } + + @Override + public void onError(Exception ex) { + ex.printStackTrace(); + } + + /** + * Create STOMP connection. + */ protected void connectStomp() { if (stompConnected) { return; } + if (stompConnectionListener != null) { + stompConnectionListener.onConnecting(); + } + Map headers = new HashMap<>(); headers.put(StompHeader.ACCEPT_VERSION.toString(), STOMP_VERSION); - headers.put(StompHeader.HOST.toString(), webSocket.getURI().getHost()); - webSocket.sendText(new StompFrame(StompCommand.CONNECT, headers).toString()); - } - - public void disconnect() { - disconnectStomp(); - webSocket.disconnect(); + headers.put(StompHeader.HOST.toString(), uri.getHost()); + + send(new StompFrame(StompCommand.CONNECT, headers).toString()); } + /** + * Disconnect STOMP. + */ protected void disconnectStomp() { if (!stompConnected) { return; } - webSocket.sendText(new StompFrame(StompCommand.DISCONNECT).toString()); - } - - public boolean isConnected() { - return stompConnected; + + send(new StompFrame(StompCommand.DISCONNECT).toString()); } + /** + * Send text message to the server. + * + * @param destination destination + * @param message text message + */ public void send(String destination, String message) { send(destination, message, null); } + /** + * Send text message to the server. + * + * @param destination destination + * @param message text message + * @param headers (optional) additional headers + */ public void send(String destination, String message, Map headers) { if (headers == null) { headers = new HashMap<>(); } + headers.put(StompHeader.DESTINATION.toString(), destination); - webSocket.sendText(new StompFrame(StompCommand.SEND, headers, message).toString()); + StompFrame frame = new StompFrame(StompCommand.SEND, headers, message); + + send(frame.toString()); } + /** + * Subscribe to a specific topic. + * + * @param destination topic destination + * @param listener listener + * @return STOMP subscription data that can be used to unsubscribe + */ public StompSubscription subscribe(String destination, StompMessageListener listener) { StompSubscription subscription = new StompSubscription(UUID.randomUUID().hashCode(), destination, listener); + Map headers = new HashMap<>(); headers.put(StompHeader.ID.toString(), String.valueOf(subscription.getId())); headers.put(StompHeader.DESTINATION.toString(), subscription.getDestination()); - webSocket.sendText(new StompFrame(StompCommand.SUBSCRIBE, headers).toString()); + StompFrame frame = new StompFrame(StompCommand.SUBSCRIBE, headers); + send(frame.toString()); + subscriptions.put(subscription.getId(), subscription); + return subscription; } - public void unsubscribe(StompSubscription subscription) { + /** + * Remove a single subscription. + * + * @param subscription subscription + */ + public void removeSubscription(StompSubscription subscription) { Map headers = new HashMap<>(); headers.put(StompHeader.ID.toString(), String.valueOf(subscription.getId())); - webSocket.sendText(new StompFrame(StompCommand.UNSUBSCRIBE, headers).toString()); + + StompFrame frame = new StompFrame(StompCommand.UNSUBSCRIBE, headers); + send(frame.toString()); + subscriptions.remove(subscription.getId()); } - public void unsubscribeAll(String destination) { + /** + * Unsubscribe all from a single topic. + * + * @param destination topic + */ + public void removeAllSubscriptions(String destination) { for (StompSubscription s : subscriptions.values()) { if (s.getDestination().equals(destination)) { - unsubscribe(s); + removeSubscription(s); } } } - private final WebSocketListener webSocketListener = new WebSocketListener() { + /** + * Check if STOMP is currently connected. + * + * @return STOMP connection status + */ + public boolean isStompConnected() { + return stompConnected; + } - @Override - public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception { - } - - @Override - public void onBinaryFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception { - } - - @Override - public void onCloseFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onConnected(WebSocket websocket, Map> headers) throws Exception { - } - - @Override - public void onConnectError(WebSocket websocket, WebSocketException cause) throws Exception { - } - - @Override - public void onContinuationFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, - WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception { - stompConnected = false; - } - - @Override - public void onError(WebSocket websocket, WebSocketException cause) throws Exception { - } - - @Override - public void onFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onFrameError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame) - throws Exception { - } - - @Override - public void onFrameSent(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onFrameUnsent(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onMessageDecompressionError(WebSocket websocket, WebSocketException cause, byte[] compressed) - throws Exception { - } - - @Override - public void onMessageError(WebSocket websocket, WebSocketException cause, List frames) - throws Exception { - } - - @Override - public void onPingFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onPongFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onSendError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame) - throws Exception { - } - - @Override - public void onSendingFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - } - - @Override - public void onSendingHandshake(WebSocket websocket, String requestLine, List headers) - throws Exception { - } - - @Override - public void onStateChanged(WebSocket websocket, WebSocketState newState) throws Exception { - } - - @Override - public void onTextFrame(WebSocket websocket, WebSocketFrame frame) throws Exception { - StompFrame stompFrame = StompFrame.fromString(frame.getPayloadText()); - - switch (stompFrame.getCommand()) { - case CONNECTED: - stompConnected = true; - break; - case MESSAGE: - Integer subscriptionId = Integer - .valueOf(stompFrame.getHeaders().get(StompHeader.SUBSCRIPTION.toString())); - - subscriptions.get(subscriptionId).getListener().onMessage(stompFrame.getBody()); - break; - default: - break; - } - } - - @Override - public void onTextMessage(WebSocket websocket, String text) throws Exception { - } - - @Override - public void onTextMessageError(WebSocket websocket, WebSocketException cause, byte[] data) - throws Exception { - } - - @Override - public void onUnexpectedError(WebSocket websocket, WebSocketException cause) throws Exception { - } - }; + /** + * Register STOMP conection listener. + * + * @param stompConnectionListener listener + */ + public void setStompConnectionListener(StompConnectionListener stompConnectionListener) { + this.stompConnectionListener = stompConnectionListener; + } } diff --git a/stomp/src/main/java/eu/mivrenik/stomp/StompSubscription.java b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/StompSubscription.java similarity index 94% rename from stomp/src/main/java/eu/mivrenik/stomp/StompSubscription.java rename to stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/StompSubscription.java index 1ffbf3d..83463a4 100644 --- a/stomp/src/main/java/eu/mivrenik/stomp/StompSubscription.java +++ b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/StompSubscription.java @@ -19,7 +19,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package eu.mivrenik.stomp; +package eu.mivrenik.stomp.client; + +import eu.mivrenik.stomp.client.listener.StompMessageListener; /** * STOMP subscription POJO diff --git a/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener/StompConnectionListener.java b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener/StompConnectionListener.java new file mode 100644 index 0000000..438e111 --- /dev/null +++ b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener/StompConnectionListener.java @@ -0,0 +1,25 @@ +package eu.mivrenik.stomp.client.listener; + +/** + * STOMP connection established listener. + */ +public abstract class StompConnectionListener { + + /** + * STOMP is in establishing connection state. + */ + public void onConnecting() { + } + + /** + * STOMP has been successfully connected. + */ + public void onConnected() { + } + + /** + * STOMP has been disconnected. + */ + public void onDisconnected() { + } +} diff --git a/stomp/src/main/java/eu/mivrenik/stomp/StompMessageListener.java b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener/StompMessageListener.java similarity index 83% rename from stomp/src/main/java/eu/mivrenik/stomp/StompMessageListener.java rename to stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener/StompMessageListener.java index 64a80d3..cce079d 100644 --- a/stomp/src/main/java/eu/mivrenik/stomp/StompMessageListener.java +++ b/stomp-client-ws/src/main/java/eu/mivrenik/stomp/client/listener/StompMessageListener.java @@ -19,11 +19,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package eu.mivrenik.stomp; +package eu.mivrenik.stomp.client.listener; + +import eu.mivrenik.stomp.StompFrame; /** * STOMP message subscription listener interface. */ public interface StompMessageListener { - void onMessage(String message); + + /** + * Subscription message received callback. + * + * @param stompFrame STOMP message frame + */ + void onMessage(StompFrame stompFrame); } diff --git a/stomp/build.gradle b/stomp/build.gradle index a0ca31b..0e47bae 100644 --- a/stomp/build.gradle +++ b/stomp/build.gradle @@ -3,7 +3,7 @@ version '0.1' apply plugin: 'java' -sourceCompatibility = 1.8 +sourceCompatibility = 1.7 repositories { mavenCentral() diff --git a/stomp/src/main/java/eu/mivrenik/stomp/StompFrame.java b/stomp/src/main/java/eu/mivrenik/stomp/StompFrame.java index 1808f1d..b37f77c 100644 --- a/stomp/src/main/java/eu/mivrenik/stomp/StompFrame.java +++ b/stomp/src/main/java/eu/mivrenik/stomp/StompFrame.java @@ -34,37 +34,12 @@ public class StompFrame { private Map headers = new HashMap<>(); private String body; - public StompFrame(StompCommand command) { - this(command, null, null); - } - - public StompFrame(StompCommand command, Map headers) { - this(command, headers, null); - } - - public StompFrame(StompCommand command, Map headers, String body) { - this.command = command; - this.body = body; - - if (headers != null) { - for (String k : headers.keySet()) { - this.headers.put(k, headers.get(k)); - } - } - } - - public StompCommand getCommand() { - return command; - } - - public Map getHeaders() { - return headers; - } - - public String getBody() { - return body; - } - + /** + * Create frame from string. + * + * @param data Data string + * @return STOMP frame instance + */ public static StompFrame fromString(String data) { String[] lines = data.split("\n"); int pos = 0; @@ -99,6 +74,37 @@ public class StompFrame { return new StompFrame(command, headers, body.toString()); } + public StompFrame(StompCommand command) { + this(command, null, null); + } + + public StompFrame(StompCommand command, Map headers) { + this(command, headers, null); + } + + public StompFrame(StompCommand command, Map headers, String body) { + this.command = command; + this.body = body; + + if (headers != null) { + for (String k : headers.keySet()) { + this.headers.put(k, headers.get(k)); + } + } + } + + public StompCommand getCommand() { + return command; + } + + public Map getHeaders() { + return headers; + } + + public String getBody() { + return body; + } + @Override public String toString() { StringBuilder sb = new StringBuilder();