Initial commit

This commit is contained in:
Andrejs Mivreņiks 2016-10-08 15:49:36 +03:00
commit fb3ae6c404
8 changed files with 708 additions and 0 deletions

134
.gitignore vendored Normal file
View File

@ -0,0 +1,134 @@
# Created by https://www.gitignore.io/api/java,maven,eclipse,intellij
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
### Java ###
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

18
pom.xml Normal file
View File

@ -0,0 +1,18 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>eu.mivrenik</groupId>
<artifactId>stomp</artifactId>
<version>0.1</version>
<properties>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>com.neovisionaries</groupId>
<artifactId>nv-websocket-client</artifactId>
<version>1.30</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,250 @@
/*
* Copyright (c) 2016 Andrejs Mivreņiks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package eu.mivrenik.stomp;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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;
/**
* STOMP v1.2 client using `nv-websocket-client` WebSocket client
* implementation.
*
* @see https://stomp.github.io/stomp-specification-1.2.html
* @see https://github.com/TakahikoKawasaki/nv-websocket-client
*
*/
public class StompClient {
private static final String STOMP_VERSION = "1.2";
private final Map<Integer, StompSubscription> subscriptions = new HashMap<>();
private WebSocket webSocket;
private boolean stompConnected;
public StompClient(String url) throws IOException {
this.webSocket = new WebSocketFactory().createSocket(url);
this.webSocket.addListener(webSocketListener);
}
public void connect() throws WebSocketException, IOException {
if (webSocket.getState() != WebSocketState.CREATED) {
webSocket = webSocket.recreate();
}
webSocket.connect();
connectStomp();
}
protected void connectStomp() {
if (stompConnected)
return;
Map<String, String> 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();
}
protected void disconnectStomp() {
if (!stompConnected)
return;
webSocket.sendText(new StompFrame(StompCommand.DISCONNECT).toString());
}
public boolean isConnected() {
return stompConnected;
}
public void send(String destination, String message) {
send(destination, message, null);
}
public void send(String destination, String message, Map<String, String> headers) {
if (headers == null)
headers = new HashMap<>();
headers.put(StompHeader.DESTINATION.toString(), destination);
webSocket.sendText(new StompFrame(StompCommand.SEND, headers, message).toString());
}
public StompSubscription subscribe(String destination, StompMessageListener listener) {
StompSubscription subscription = new StompSubscription(UUID.randomUUID().hashCode(), destination, listener);
Map<String, String> 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());
subscriptions.put(subscription.getId(), subscription);
return subscription;
}
public void unsubscribe(StompSubscription subscription) {
Map<String, String> headers = new HashMap<>();
headers.put(StompHeader.ID.toString(), String.valueOf(subscription.getId()));
webSocket.sendText(new StompFrame(StompCommand.UNSUBSCRIBE, headers).toString());
subscriptions.remove(subscription.getId());
}
public void unsubscribeAll(String destination) {
for (StompSubscription s : subscriptions.values())
if (s.getDestination().equals(destination))
unsubscribe(s);
}
private final WebSocketListener webSocketListener = new WebSocketListener() {
@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<String, List<String>> 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<WebSocketFrame> 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<String[]> 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 {
}
};
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) 2016 Andrejs Mivreņiks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package eu.mivrenik.stomp;
/**
* STOMP commands.
*
*/
enum StompCommand {
CONNECT("CONNECT"),
CONNECTED("CONNECTED"),
DISCONNECT("DISCONNECT"),
ERROR("ERROR"),
MESSAGE("MESSAGE"),
RECEIPT("RECEIPT"),
SEND("SEND"),
SUBSCRIBE("SUBSCRIBE"),
UNSUBSCRIBE("UNSUBSCRIBE");
private final String value;
public static StompCommand fromValue(String value) {
for (StompCommand c : StompCommand.values())
if (c.value.equals(value))
return c;
throw new IllegalArgumentException("Unknown STOMP command:" + value);
}
private StompCommand(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
}

View File

@ -0,0 +1,118 @@
/*
* Copyright (c) 2016 Andrejs Mivreņiks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package eu.mivrenik.stomp;
import java.util.HashMap;
import java.util.Map;
/**
* STOMP Frame.
*
* @link https://stomp.github.io/stomp-specification-1.2.html#STOMP_Frames
*
*/
class StompFrame {
private StompCommand command;
private Map<String, String> headers = new HashMap<>();
private String body;
public StompFrame(StompCommand command) {
this(command, null, null);
}
public StompFrame(StompCommand command, Map<String, String> headers) {
this(command, headers, null);
}
public StompFrame(StompCommand command, Map<String, String> 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<String, String> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
public static StompFrame fromString(String data) {
String[] lines = data.split("\n");
int pos = 0;
// Ignore empty lines
while (pos < lines.length && lines[pos].isEmpty())
pos++;
// Command
StompCommand command = StompCommand.fromValue(lines[pos++]);
// Headers
Map<String, String> headers = new HashMap<>();
while (!lines[pos].isEmpty()) {
String[] keyValue = lines[pos].split(":");
headers.put(keyValue[0], keyValue[1]);
pos++;
}
pos++;
// Body
StringBuilder body = new StringBuilder();
for (; pos < lines.length; pos++) {
body.append(lines[pos]);
if (body.charAt(body.length() - 1) == '\0') {
body.deleteCharAt(body.length() - 1);
break;
}
}
return new StompFrame(command, headers, body.toString());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
// Command
sb.append(command);
sb.append('\n');
// Headers
for (String k : headers.keySet()) {
sb.append(k);
sb.append(':');
sb.append(headers.get(k));
sb.append('\n');
}
sb.append('\n');
// Body
if (body != null)
sb.append(body);
sb.append('\0');
return sb.toString();
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2016 Andrejs Mivreņiks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package eu.mivrenik.stomp;
/**
* STOMP headers.
*
*/
enum StompHeader {
ACCEPT_VERSION("accept-version"),
CONTENT_LENGTH("content-length"),
CONTENT_TYPE("content-type"),
DESTINATION("destination"),
HOST("host"),
ID("id"),
MESSAGE_ID("message-id"),
RECEIPT_ID("receipt-id"),
RECEIPT("receipt"),
SUBSCRIPTION("subscription"),
VERSION("version");
private final String value;
private StompHeader(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (c) 2016 Andrejs Mivreņiks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package eu.mivrenik.stomp;
/**
* STOMP message subscription listener interface.
*
*/
public interface StompMessageListener {
void onMessage(String message);
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (c) 2016 Andrejs Mivreņiks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package eu.mivrenik.stomp;
/**
* STOMP subscription POJO
*
*/
public class StompSubscription {
private final Integer id;
private final String destination;
private final StompMessageListener listener;
public StompSubscription(Integer id, String destination, StompMessageListener listener) {
this.id = id;
this.destination = destination;
this.listener = listener;
}
public Integer getId() {
return id;
}
public String getDestination() {
return destination;
}
public StompMessageListener getListener() {
return listener;
}
}