) milliseconds
+ */
serverHeartbeat = Math.max(serverHeartbeatNew, Integer.parseInt(heartbeats[0]));
}
}
if (clientHeartbeat > 0 || serverHeartbeat > 0) {
scheduler = Schedulers.io();
if (clientHeartbeat > 0) {
- //client MUST/WANT send heart-beat
- Log.d(TAG, "Client will send heart-beat every " + clientHeartbeat + " ms");
+ /**
+ * client MUST/WANT send heart-beat
+ */
+ HiLog.error(LABEL, "Client will send heart-beat every " + clientHeartbeat + "ms");
scheduleClientHeartBeat();
}
if (serverHeartbeat > 0) {
- Log.d(TAG, "Client will listen to server heart-beat every " + serverHeartbeat + " ms");
- //client WANT to listen to server heart-beat
+ HiLog.error(LABEL, "Client will listen to server heart-beat every " + serverHeartbeat + " ms");
+ /**
+ * client WANT to listen to server heart-beat
+ */
scheduleServerHeartBeatCheck();
-
- // initialize the server heartbeat
- lastServerHeartBeat = System.currentTimeMillis();
+ /**
+ * initialize the server heartbeat
+ */
+ lastServerHearBeat = System.currentTimeMillis();
}
}
}
@@ -129,8 +164,11 @@ public class HeartBeatTask {
private void scheduleServerHeartBeatCheck() {
if (serverHeartbeat > 0 && scheduler != null) {
final long now = System.currentTimeMillis();
- Log.d(TAG, "Scheduling server heart-beat to be checked in " + serverHeartbeat + " ms and now is '" + now + "'");
- //add some slack on the check
+ HiLog.error(LABEL, "Scheduling server heart-beat to be checked in "
+ + serverHeartbeat + " ms and now is '" + now + "'");
+ /**
+ * add some slack on the check
+ */
serverCheckHeartBeatTask = scheduler.scheduleDirect(() ->
checkServerHeartBeat(), serverHeartbeat, TimeUnit.MILLISECONDS);
}
@@ -139,17 +177,20 @@ public class HeartBeatTask {
private void checkServerHeartBeat() {
if (serverHeartbeat > 0) {
final long now = System.currentTimeMillis();
- //use a forgiving boundary as some heart beats can be delayed or lost.
+ /**
+ * use a forgiving boundary as some heart beats can be delayed or lost.
+ */
final long boundary = now - (3 * serverHeartbeat);
- //we need to check because the task could failed to abort
- if (lastServerHeartBeat < boundary) {
- Log.d(TAG, "It's a sad day ;( Server didn't send heart-beat on time. Last received at '" + lastServerHeartBeat + "' and now is '" + now + "'");
+ /**
+ * we need to check because the task could failed to abort
+ */
+ if (lastServerHearBeat < boundary) {
if (failedListener != null) {
failedListener.onServerHeartBeatFailed();
}
} else {
- Log.d(TAG, "We were checking and server sent heart-beat on time. So well-behaved :)");
- lastServerHeartBeat = System.currentTimeMillis();
+ HiLog.error(LABEL, "We were checking and server sent heart-beat on time. So well-behaved :)");
+ lastServerHearBeat = System.currentTimeMillis();
}
}
}
@@ -158,8 +199,9 @@ public class HeartBeatTask {
* Used to abort the server heart-beat check.
*/
private void abortServerHeartBeatCheck() {
- lastServerHeartBeat = System.currentTimeMillis();
- Log.d(TAG, "Aborted last check because server sent heart-beat on time ('" + lastServerHeartBeat + "'). So well-behaved :)");
+ lastServerHearBeat = System.currentTimeMillis();
+ HiLog.error(LABEL, "Aborted last check because server sent heart-beat on time ('"
+ + lastServerHearBeat + "'). So well-behaved :)");
if (serverCheckHeartBeatTask != null) {
serverCheckHeartBeatTask.dispose();
}
@@ -171,7 +213,7 @@ public class HeartBeatTask {
*/
private void scheduleClientHeartBeat() {
if (clientHeartbeat > 0 && scheduler != null) {
- Log.d(TAG, "Scheduling client heart-beat to be sent in " + clientHeartbeat + " ms");
+ HiLog.error(LABEL, "Scheduling client heart-beat to be sent in " + clientHeartbeat + " ms");
clientSendHeartBeatTask = scheduler.scheduleDirect(() ->
sendClientHeartBeat(), clientHeartbeat, TimeUnit.MILLISECONDS);
}
@@ -181,9 +223,11 @@ public class HeartBeatTask {
* Send the raw heart-beat to the server.
*/
private void sendClientHeartBeat() {
- sendCallback.sendClientHeartBeat("\r\n");
- Log.d(TAG, "PING >>>");
- //schedule next client heart beat
+ sendCallback.sendClientHeartBeat(System.lineSeparator());
+ HiLog.error(LABEL, "PING >>>");
+ /**
+ * schedule next client heart beat
+ */
this.scheduleClientHeartBeat();
}
@@ -198,11 +242,29 @@ public class HeartBeatTask {
scheduleClientHeartBeat();
}
+ /**
+ * FailedListener
+ *
+ * @since 2021-04-27
+ */
public interface FailedListener {
+ /**
+ * onServerHeartBeatFailed 返回头部
+ */
void onServerHeartBeatFailed();
}
+ /**
+ * SendCallback
+ *
+ * @since 2021-04-27
+ */
public interface SendCallback {
+ /**
+ * sendClientHeartBeat 返回头部
+ *
+ * @param pingMessage 频率消息
+ */
void sendClientHeartBeat(String pingMessage);
}
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/Stomp.java b/lib/src/main/java/ua/naiksoftware/stomp/Stomp.java
index db6563511aebc875ce8c3471c1afb2d9d32f7ec9..b1d2823408a03e78086129131deba40f760914f7 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/Stomp.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/Stomp.java
@@ -1,14 +1,14 @@
package ua.naiksoftware.stomp;
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-
-import java.util.Map;
+import io.reactivex.annotations.NonNull;
+import io.reactivex.annotations.Nullable;
import okhttp3.OkHttpClient;
import ua.naiksoftware.stomp.provider.OkHttpConnectionProvider;
import ua.naiksoftware.stomp.provider.WebSocketsConnectionProvider;
+import java.util.Map;
+
/**
* Supported overlays:
* - org.java_websocket.WebSocket ('org.java-websocket:Java-WebSocket:1.3.2')
@@ -18,20 +18,35 @@ import ua.naiksoftware.stomp.provider.WebSocketsConnectionProvider;
* such as web socket.
*
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-27
*/
public class Stomp {
+ private Stomp() {
+ }
+
+ /**
+ * StompClient
+ *
+ * @param connectionProvider
+ * @param uri
+ * @return StompClient
+ */
public static StompClient over(@NonNull ConnectionProvider connectionProvider, String uri) {
return over(connectionProvider, uri, null, null);
}
/**
+ * over
+ *
* @param connectionProvider connectionProvider method
* @param uri URI to connect
* @param connectHttpHeaders HTTP headers, will be passed with handshake query, may be null
* @return StompClient for receiving and sending messages. Call #StompClient.connect
*/
- public static StompClient over(@NonNull ConnectionProvider connectionProvider, String uri, Map connectHttpHeaders) {
+ public static StompClient over(@NonNull ConnectionProvider connectionProvider,
+ String uri, Map connectHttpHeaders) {
return over(connectionProvider, uri, connectHttpHeaders, null);
}
@@ -39,25 +54,36 @@ public class Stomp {
* {@code webSocketClient} can accept the following type of clients:
*
* - {@code org.java_websocket.WebSocket}: cannot accept an existing client
- * - {@code okhttp3.WebSocket}: can accept a non-null instance of {@code okhttp3.OkHttpClient}
+ * - {@code okhttp3.WebSocket}: can accept a non-null
+ * instance of {@code okhttp3.OkHttpClient}
+ *
*
*
* @param connectionProvider connectionProvider method
* @param uri URI to connect
* @param connectHttpHeaders HTTP headers, will be passed with handshake query, may be null
- * @param okHttpClient Existing client that will be used to open the WebSocket connection, may be null to use default client
+ * @param okHttpClient Existing client that will be used to open the WebSocket connection,
+ * may be null to use default client
+ *
* @return StompClient for receiving and sending messages. Call #StompClient.connect
+ * @throws “You cannot pass an OkHttpClient when using JWS.Use null instead.”
+ *
*/
- public static StompClient over(@NonNull ConnectionProvider connectionProvider, String uri, @Nullable Map connectHttpHeaders, @Nullable OkHttpClient okHttpClient) {
+ public static StompClient over(@NonNull ConnectionProvider connectionProvider, String uri,
+ @Nullable Map connectHttpHeaders,
+ @Nullable OkHttpClient okHttpClient) {
if (connectionProvider == ConnectionProvider.JWS) {
if (okHttpClient != null) {
- throw new IllegalArgumentException("You cannot pass an OkHttpClient when using JWS. Use null instead.");
+ IllegalArgumentException illegalArgumentException = new IllegalArgumentException("You cannot pass an"
+ + " OkHttpClient when using JWS. Use null instead.");
+ throw illegalArgumentException;
}
return createStompClient(new WebSocketsConnectionProvider(uri, connectHttpHeaders));
}
if (connectionProvider == ConnectionProvider.OKHTTP) {
- return createStompClient(new OkHttpConnectionProvider(uri, connectHttpHeaders, (okHttpClient == null) ? new OkHttpClient() : okHttpClient));
+ return createStompClient(new OkHttpConnectionProvider(uri,
+ connectHttpHeaders, (okHttpClient == null) ? new OkHttpClient() : okHttpClient));
}
throw new IllegalArgumentException("ConnectionProvider type not supported: " + connectionProvider.toString());
@@ -67,7 +93,15 @@ public class Stomp {
return new StompClient(connectionProvider);
}
+ /**
+ * ConnectionProvider
+ *
+ * @since 2021-04-27
+ */
public enum ConnectionProvider {
+ /**
+ * OKHTTP JWS
+ */
OKHTTP, JWS
}
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/StompClient.java b/lib/src/main/java/ua/naiksoftware/stomp/StompClient.java
index e4f73ccc28d68539b7e836f05fd803fbe6a7e04a..3b3877b4369b87d673c4e7d384dd63705075077b 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/StompClient.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/StompClient.java
@@ -1,41 +1,46 @@
package ua.naiksoftware.stomp;
-import android.annotation.SuppressLint;
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-
import io.reactivex.BackpressureStrategy;
import io.reactivex.Completable;
import io.reactivex.CompletableSource;
import io.reactivex.Flowable;
+import io.reactivex.annotations.NonNull;
+import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.PublishSubject;
+import ua.naiksoftware.stomp.dto.LifecycleEvent;
import ua.naiksoftware.stomp.dto.StompCommand;
+import ua.naiksoftware.stomp.dto.StompHeader;
import ua.naiksoftware.stomp.dto.StompMessage;
import ua.naiksoftware.stomp.pathmatcher.PathMatcher;
import ua.naiksoftware.stomp.pathmatcher.SimplePathMatcher;
import ua.naiksoftware.stomp.provider.ConnectionProvider;
-import ua.naiksoftware.stomp.dto.LifecycleEvent;
-import ua.naiksoftware.stomp.dto.StompHeader;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+
/**
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-27
*/
public class StompClient {
-
- private static final String TAG = StompClient.class.getSimpleName();
-
+ /**
+ * SUPPORTED_VERSIONS usr in StompHeader
+ */
public static final String SUPPORTED_VERSIONS = "1.1,1.2";
+ /**
+ * DEFAULT_ACK use in StompHeader
+ */
public static final String DEFAULT_ACK = "auto";
+
private final ConnectionProvider connectionProvider;
private ConcurrentHashMap topics;
private boolean legacyWhitespace;
@@ -50,6 +55,13 @@ public class StompClient {
private List headers;
private HeartBeatTask heartBeatTask;
+
+ /**
+ * 构造函数
+ * *
+ *
+ * @param connectionProvider
+ */
public StompClient(ConnectionProvider connectionProvider) {
this.connectionProvider = connectionProvider;
streamMap = new ConcurrentHashMap<>();
@@ -60,12 +72,20 @@ public class StompClient {
});
}
+ private synchronized PublishSubject getMessageStream() {
+ if (messageStream == null || messageStream.hasComplete()) {
+ messageStream = PublishSubject.create();
+ }
+ return messageStream;
+ }
+
/**
* Sets the heartbeat interval to request from the server.
*
* Not very useful yet, because we don't have any heartbeat logic on our side.
*
* @param ms heartbeat time in milliseconds
+ * @return StompClient
*/
public StompClient withServerHeartbeat(int ms) {
heartBeatTask.setServerHeartbeat(ms);
@@ -78,6 +98,7 @@ public class StompClient {
* Not very useful yet, because we don't have any heartbeat logic on our side.
*
* @param ms heartbeat time in milliseconds
+ * @return StompClient
*/
public StompClient withClientHeartbeat(int ms) {
heartBeatTask.setClientHeartbeat(ms);
@@ -94,45 +115,44 @@ public class StompClient {
/**
* Connect to websocket. If already connected, this will silently fail.
*
- * @param _headers HTTP headers to send in the INITIAL REQUEST, i.e. during the protocol upgrade
+ * @param headerList HTTP headers to send in the INITIAL REQUEST, i.e. during the protocol upgrade
+ * @noinspection checkstyle:HiddenField
*/
- public void connect(@Nullable List _headers) {
+ public void connect(@Nullable List headerList) {
- Log.d(TAG, "Connect");
- this.headers = _headers;
+ this.headers = headerList;
if (isConnected()) {
- Log.d(TAG, "Already connected, ignore");
return;
}
lifecycleDisposable = connectionProvider.lifecycle()
.subscribe(lifecycleEvent -> {
switch (lifecycleEvent.getType()) {
case OPENED:
- List headers = new ArrayList<>();
- headers.add(new StompHeader(StompHeader.VERSION, SUPPORTED_VERSIONS));
- headers.add(new StompHeader(StompHeader.HEART_BEAT,
+ List head = new ArrayList<>();
+ head.add(new StompHeader(StompHeader.VERSION, SUPPORTED_VERSIONS));
+ head.add(new StompHeader(StompHeader.HEART_BEAT,
heartBeatTask.getClientHeartbeat() + "," + heartBeatTask.getServerHeartbeat()));
-
- if (_headers != null) headers.addAll(_headers);
-
- connectionProvider.send(new StompMessage(StompCommand.CONNECT, headers, null).compile(legacyWhitespace))
+ if (headerList != null) {
+ head.addAll(headerList);
+ }
+ connectionProvider.send(new StompMessage(StompCommand.CONNECT, head, null)
+ .compile(legacyWhitespace))
.subscribe(() -> {
- Log.d(TAG, "Publish open");
lifecyclePublishSubject.onNext(lifecycleEvent);
});
break;
case CLOSED:
- Log.d(TAG, "Socket closed");
disconnect();
break;
case ERROR:
- Log.d(TAG, "Socket closed with error");
lifecyclePublishSubject.onNext(lifecycleEvent);
break;
+ default:
+ break;
}
});
@@ -144,28 +164,33 @@ public class StompClient {
.subscribe(stompMessage -> {
getConnectionStream().onNext(true);
}, onError -> {
- Log.e(TAG, "Error parsing message", onError);
});
}
- synchronized private BehaviorSubject getConnectionStream() {
+ private synchronized BehaviorSubject getConnectionStream() {
if (connectionStream == null || connectionStream.hasComplete()) {
connectionStream = BehaviorSubject.createDefault(false);
}
return connectionStream;
}
- synchronized private PublishSubject getMessageStream() {
- if (messageStream == null || messageStream.hasComplete()) {
- messageStream = PublishSubject.create();
- }
- return messageStream;
- }
-
+ /**
+ * send send some
+ *
+ * @param destination
+ * @return Completable
+ */
public Completable send(String destination) {
return send(destination, null);
}
+ /**
+ * send send StompMessage
+ *
+ * @param destination
+ * @param data
+ * @return Completable
+ */
public Completable send(String destination, String data) {
return send(new StompMessage(
StompCommand.SEND,
@@ -173,6 +198,12 @@ public class StompClient {
data));
}
+ /**
+ * send send Message
+ *
+ * @param stompMessage
+ * @return Completable
+ */
public Completable send(@NonNull StompMessage stompMessage) {
Completable completable = connectionProvider.send(stompMessage.compile(legacyWhitespace));
CompletableSource connectionComplete = getConnectionStream()
@@ -182,7 +213,11 @@ public class StompClient {
.startWith(connectionComplete);
}
- @SuppressLint("CheckResult")
+ /**
+ * sendHeartBeat
+ *
+ * @param pingMessage
+ */
private void sendHeartBeat(@NonNull String pingMessage) {
Completable completable = connectionProvider.send(pingMessage);
CompletableSource connectionComplete = getConnectionStream()
@@ -193,26 +228,44 @@ public class StompClient {
.subscribe();
}
- public Flowable lifecycle() {
+ /**
+ * lifecycle
+ *
+ * @return Flowable
+ */
+ public Flowable lifecycle() {
return lifecyclePublishSubject.toFlowable(BackpressureStrategy.BUFFER);
}
/**
* Disconnect from server, and then reconnect with the last-used headers
*/
- @SuppressLint("CheckResult")
public void reconnect() {
disconnectCompletable()
.subscribe(() -> connect(headers),
- e -> Log.e(TAG, "Disconnect error", e));
+ error -> {
+ });
}
- @SuppressLint("CheckResult")
- public void disconnect() {
+ /**
+ * disconnect
+ *
+ * @return boolean
+ */
+ public boolean disconnect() {
+ AtomicBoolean flag = new AtomicBoolean(false);
disconnectCompletable().subscribe(() -> {
- }, e -> Log.e(TAG, "Disconnect error", e));
+ flag.set(true);
+ }, error -> {
+ });
+ return flag.get();
}
+ /**
+ * disconnectCompletable 断开
+ *
+ * @return Completable
+ */
public Completable disconnectCompletable() {
heartBeatTask.shutdown();
@@ -226,51 +279,71 @@ public class StompClient {
return connectionProvider.disconnect()
.doFinally(() -> {
- Log.d(TAG, "Stomp disconnected");
+
getConnectionStream().onComplete();
getMessageStream().onComplete();
lifecyclePublishSubject.onNext(new LifecycleEvent(LifecycleEvent.Type.CLOSED));
});
}
+ /**
+ * tpic(String,List)
+ * *
+ *
+ * @param destinationPath
+ * @return Flowable
+ */
public Flowable topic(String destinationPath) {
return topic(destinationPath, null);
}
+ /**
+ * streamMap put
+ *
+ * @param destPath
+ * @param headerList
+ * @return Flowable
+ */
public Flowable topic(@NonNull String destPath, List headerList) {
- if (destPath == null)
+ if (destPath == null) {
return Flowable.error(new IllegalArgumentException("Topic path cannot be null"));
- else if (!streamMap.containsKey(destPath))
+ } else if (!streamMap.containsKey(destPath)) {
streamMap.put(destPath,
Completable.defer(() -> subscribePath(destPath, headerList)).andThen(
- getMessageStream()
- .filter(msg -> pathMatcher.matches(destPath, msg))
- .toFlowable(BackpressureStrategy.BUFFER)
- .doFinally(() -> unsubscribePath(destPath).subscribe())
- .share())
+ getMessageStream()
+ .filter(msg -> pathMatcher.matches(destPath, msg))
+ .toFlowable(BackpressureStrategy.BUFFER)
+ .doFinally(() -> unsubscribePath(destPath).subscribe())
+ .share())
);
+ }
return streamMap.get(destPath);
}
private Completable subscribePath(String destinationPath, @Nullable List headerList) {
String topicId = UUID.randomUUID().toString();
- if (topics == null) topics = new ConcurrentHashMap<>();
+ if (topics == null) {
+ topics = new ConcurrentHashMap<>();
+ }
- // Only continue if we don't already have a subscription to the topic
+ /**
+ * Only continue if we don't already have a subscription to the topic
+ */
if (topics.containsKey(destinationPath)) {
- Log.d(TAG, "Attempted to subscribe to already-subscribed path!");
return Completable.complete();
}
topics.put(destinationPath, topicId);
- List headers = new ArrayList<>();
- headers.add(new StompHeader(StompHeader.ID, topicId));
- headers.add(new StompHeader(StompHeader.DESTINATION, destinationPath));
- headers.add(new StompHeader(StompHeader.ACK, DEFAULT_ACK));
- if (headerList != null) headers.addAll(headerList);
+ List heads = new ArrayList<>();
+ heads.add(new StompHeader(StompHeader.ID, topicId));
+ heads.add(new StompHeader(StompHeader.DESTINATION, destinationPath));
+ heads.add(new StompHeader(StompHeader.ACK, DEFAULT_ACK));
+ if (headerList != null) {
+ heads.addAll(headerList);
+ }
return send(new StompMessage(StompCommand.SUBSCRIBE,
- headers, null))
+ heads, null))
.doOnError(throwable -> unsubscribePath(destinationPath).subscribe());
}
@@ -286,7 +359,6 @@ public class StompClient {
topics.remove(dest);
- Log.d(TAG, "Unsubscribe path: " + dest + " id: " + topicId);
return send(new StompMessage(StompCommand.UNSUBSCRIBE,
Collections.singletonList(new StompHeader(StompHeader.ID, topicId)), null)).onErrorComplete();
@@ -298,7 +370,8 @@ public class StompClient {
* Right now, the only options are simple, rmq supported.
* But you can write you own matcher by implementing {@link PathMatcher}
*
- * When set to {@link ua.naiksoftware.stomp.pathmatcher.RabbitPathMatcher}, topic subscription allows for RMQ-style wildcards.
+ * When set to {@link ua.naiksoftware.stomp.pathmatcher.RabbitPathMatcher},
+ * topic subscription allows for RMQ-style wildcards.
*
*
* @param pathMatcher Set to {@link SimplePathMatcher} by default
@@ -315,7 +388,7 @@ public class StompClient {
* Reverts to the old frame formatting, which included two newlines between the message body
* and the end-of-frame marker.
*
- * Legacy: Body\n\n^@
+ * Legacy: Body
*
* Default: Body^@
*
@@ -325,10 +398,13 @@ public class StompClient {
public void setLegacyWhitespace(boolean legacyWhitespace) {
this.legacyWhitespace = legacyWhitespace;
}
-
- /** returns the to topic (subscription id) corresponding to a given destination
+
+ /**
+ * returns the to topic (subscription id) corresponding to a given destination
+ *
* @param dest the destination
- * @return the topic (subscription id) or null if no topic corresponds to the destination */
+ * @return the topic (subscription id) or null if no topic correspon ds to the destination
+ */
public String getTopicId(String dest) {
return topics.get(dest);
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/dto/LifecycleEvent.java b/lib/src/main/java/ua/naiksoftware/stomp/dto/LifecycleEvent.java
index 019d33185b755a7fbcdf4f50c251fae6e9f205d8..a6096c613e30ab4f399e4472aba95dffdc02133d 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/dto/LifecycleEvent.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/dto/LifecycleEvent.java
@@ -5,32 +5,62 @@ import java.util.TreeMap;
/**
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-27
*/
public class LifecycleEvent {
-
+ /**
+ * Type
+ *
+ * @since 2021-04-27
+ */
public enum Type {
+ /**
+ * OPENED, CLOSED, ERROR, FAILED_SERVER_HEARTBEAT
+ */
OPENED, CLOSED, ERROR, FAILED_SERVER_HEARTBEAT
}
private final Type mType;
- //Nullable
+ /**
+ * Nullable
+ */
private Exception mException;
- //Nullable
+ /**
+ * Nullable
+ */
private String mMessage;
private TreeMap handshakeResponseHeaders = new TreeMap<>();
+ /**
+ * LifecycleEvent
+ *
+ * @param type
+ */
public LifecycleEvent(Type type) {
mType = type;
}
+ /**
+ * LifecycleEvent
+ *
+ * @param type
+ * @param exception
+ */
public LifecycleEvent(Type type, Exception exception) {
mType = type;
mException = exception;
}
+ /**
+ * LifecycleEvent
+ *
+ * @param type
+ * @param message
+ */
public LifecycleEvent(Type type, String message) {
mType = type;
mMessage = message;
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/dto/StompCommand.java b/lib/src/main/java/ua/naiksoftware/stomp/dto/StompCommand.java
index 029a1970c5f661a0820761e063f800c3f17e9c3c..69e78125ccec895eb8a4e3756fff07635c7b363f 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/dto/StompCommand.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/dto/StompCommand.java
@@ -2,15 +2,43 @@ package ua.naiksoftware.stomp.dto;
/**
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-27
*/
public class StompCommand {
+ /**
+ * CONNECT
+ */
public static final String CONNECT = "CONNECT";
+ /**
+ * CONNECTED
+ */
public static final String CONNECTED = "CONNECTED";
+ /**
+ * SEND
+ */
public static final String SEND = "SEND";
+ /**
+ * MESSAGE
+ */
public static final String MESSAGE = "MESSAGE";
+ /**
+ * SUBSCRIBE
+ */
public static final String SUBSCRIBE = "SUBSCRIBE";
+ /**
+ * UNSUBSCRIBE
+ */
public static final String UNSUBSCRIBE = "UNSUBSCRIBE";
-
+ /**
+ * UNKNOWN
+ */
public static final String UNKNOWN = "UNKNOWN";
+
+ /**
+ * 构造
+ */
+ private StompCommand() {
+ }
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/dto/StompHeader.java b/lib/src/main/java/ua/naiksoftware/stomp/dto/StompHeader.java
index 38469093a747cc82dea7776d9eadb989795593e1..8bfdcd8ed166d8fe12803e5d950c6b4d938ed86c 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/dto/StompHeader.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/dto/StompHeader.java
@@ -2,21 +2,52 @@ package ua.naiksoftware.stomp.dto;
/**
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-21
*/
public class StompHeader {
-
+ /**
+ * VERSION
+ */
public static final String VERSION = "accept-version";
+ /**
+ * HEART_BEAT
+ */
public static final String HEART_BEAT = "heart-beat";
+ /**
+ * DESTINATION
+ */
public static final String DESTINATION = "destination";
+ /**
+ * SUBSCRIPTION
+ */
public static final String SUBSCRIPTION = "subscription";
+ /**
+ * CONTENT_TYPE
+ */
public static final String CONTENT_TYPE = "content-type";
+ /**
+ * MESSAGE_ID
+ */
public static final String MESSAGE_ID = "message-id";
+ /**
+ * ID
+ */
public static final String ID = "id";
+ /**
+ * ACK
+ */
public static final String ACK = "ack";
private final String mKey;
private final String mValue;
+ /**
+ * StompHeader
+ *
+ * @param key
+ * @param value
+ */
public StompHeader(String key, String value) {
mKey = key;
mValue = value;
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/dto/StompMessage.java b/lib/src/main/java/ua/naiksoftware/stomp/dto/StompMessage.java
index 60ccb917f4ee07fb57bc747ac3d3b212754cd504..8a31224faec37476d17eae47fe6cdfedb10bd6b9 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/dto/StompMessage.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/dto/StompMessage.java
@@ -1,7 +1,7 @@
package ua.naiksoftware.stomp.dto;
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
+import io.reactivex.annotations.NonNull;
+import io.reactivex.annotations.Nullable;
import java.io.StringReader;
import java.util.ArrayList;
@@ -12,17 +12,30 @@ import java.util.regex.Pattern;
/**
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-27
*/
public class StompMessage {
-
+ /**
+ * TERMINATE_MESSAGE_SYMBOL
+ */
public static final String TERMINATE_MESSAGE_SYMBOL = "\u0000";
-
+ private static final int NUM_1 = 1;
+ private static final int NUM_2 = 2;
+ private static final String STRING = "\\n";
+ private static final String NULL_STRING = null;
private static final Pattern PATTERN_HEADER = Pattern.compile("([^:\\s]+)\\s*:\\s*([^:\\s]+)");
-
private final String mStompCommand;
private final List mStompHeaders;
private final String mPayload;
+ /**
+ * StompMessage
+ *
+ * @param stompCommand
+ * @param stompHeaders
+ * @param payload
+ */
public StompMessage(String stompCommand, List stompHeaders, String payload) {
mStompCommand = stompCommand;
mStompHeaders = stompHeaders;
@@ -41,53 +54,80 @@ public class StompMessage {
return mStompCommand;
}
+ /**
+ * findHeader
+ *
+ * @param key key
+ * @return String
+ */
@Nullable
public String findHeader(String key) {
- if (mStompHeaders == null) return null;
+ if (mStompHeaders == null) {
+ return NULL_STRING;
+ }
for (StompHeader header : mStompHeaders) {
- if (header.getKey().equals(key)) return header.getValue();
+ if (header.getKey().equals(key)) {
+ return header.getValue();
+ }
}
- return null;
+ return NULL_STRING;
}
+ /**
+ * compile
+ *
+ * @return String
+ */
@NonNull
public String compile() {
return compile(false);
}
+ /**
+ * compile
+ *
+ * @param isLegacyWhitespace
+ * @return String
+ */
@NonNull
- public String compile(boolean legacyWhitespace) {
+ public String compile(boolean isLegacyWhitespace) {
StringBuilder builder = new StringBuilder();
- builder.append(mStompCommand).append('\n');
+ builder.append(mStompCommand).append(System.lineSeparator());
for (StompHeader header : mStompHeaders) {
- builder.append(header.getKey()).append(':').append(header.getValue()).append('\n');
+ builder.append(header.getKey()).append(':').append(header.getValue()).append(System.lineSeparator());
}
- builder.append('\n');
+ builder.append(System.lineSeparator());
if (mPayload != null) {
builder.append(mPayload);
- if (legacyWhitespace) builder.append("\n\n");
+ if (isLegacyWhitespace) {
+ builder.append(System.lineSeparator());
+ }
}
builder.append(TERMINATE_MESSAGE_SYMBOL);
return builder.toString();
}
+ /**
+ * from
+ *
+ * @param data
+ * @return StompMessage return StompMessage
+ */
public static StompMessage from(@Nullable String data) {
if (data == null || data.trim().isEmpty()) {
return new StompMessage(StompCommand.UNKNOWN, null, data);
}
Scanner reader = new Scanner(new StringReader(data));
- reader.useDelimiter("\\n");
+ reader.useDelimiter(STRING);
String command = reader.next();
List headers = new ArrayList<>();
while (reader.hasNext(PATTERN_HEADER)) {
Matcher matcher = PATTERN_HEADER.matcher(reader.next());
matcher.find();
- headers.add(new StompHeader(matcher.group(1), matcher.group(2)));
+ headers.add(new StompHeader(matcher.group(NUM_1), matcher.group(NUM_2)));
}
-
- reader.skip("\n\n");
-
+ reader.skip(System.lineSeparator());
reader.useDelimiter(TERMINATE_MESSAGE_SYMBOL);
String payload = reader.hasNext() ? reader.next() : null;
@@ -96,10 +136,7 @@ public class StompMessage {
@Override
public String toString() {
- return "StompMessage{" +
- "command='" + mStompCommand + '\'' +
- ", headers=" + mStompHeaders +
- ", payload='" + mPayload + '\'' +
- '}';
+ return "StompMessage{" + "command='" + mStompCommand + '\'' + ", headers="
+ + mStompHeaders + ", payload='" + mPayload + '\'' + '}';
}
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/PathMatcher.java b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/PathMatcher.java
index e5343b6c0b57821fe3f24ffc9169cdd35259b5db..be7dd62dac0e7ce833861a711842ae82124d610c 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/PathMatcher.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/PathMatcher.java
@@ -2,7 +2,18 @@ package ua.naiksoftware.stomp.pathmatcher;
import ua.naiksoftware.stomp.dto.StompMessage;
+/**
+ * PathMatcher
+ *
+ * @since 2021-04-21
+ */
public interface PathMatcher {
-
+ /**
+ * matches
+ *
+ * @param path
+ * @param msg
+ * @return boolean
+ */
boolean matches(String path, StompMessage msg);
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/RabbitPathMatcher.java b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/RabbitPathMatcher.java
index 1ee2b25beb35313beaf8019671781c68d4c456ab..1694989871fc706bad99f31b8a26d81afa5836f1 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/RabbitPathMatcher.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/RabbitPathMatcher.java
@@ -5,8 +5,12 @@ import ua.naiksoftware.stomp.dto.StompMessage;
import java.util.ArrayList;
+/**
+ * RabbitPathMatcher
+ *
+ * @since 2021-04-27
+ */
public class RabbitPathMatcher implements PathMatcher {
-
/**
* RMQ-style wildcards.
* See more info here.
@@ -14,38 +18,45 @@ public class RabbitPathMatcher implements PathMatcher {
@Override
public boolean matches(String path, StompMessage msg) {
String dest = msg.findHeader(StompHeader.DESTINATION);
- if (dest == null) return false;
-
- // for example string "lorem.ipsum.*.sit":
-
- // split it up into ["lorem", "ipsum", "*", "sit"]
+ if (dest == null) {
+ return false;
+ }
+ /**
+ * for example string "lorem.ipsum.*.sit":
+ * split it up into ["lorem", "ipsum", "*", "sit"]
+ */
String[] split = path.split("\\.");
ArrayList transformed = new ArrayList<>();
- // check for wildcards and replace with corresponding regex
- for (String s : split) {
- switch (s) {
+ /**
+ * check for wildcards and replace with corresponding regex
+ */
+ for (String string : split) {
+ switch (string) {
case "*":
transformed.add("[^.]+");
break;
case "#":
- // TODO: make this work with zero-word
- // e.g. "lorem.#.dolor" should ideally match "lorem.dolor"
+ /**
+ * e.g. "lorem.#.dolor" should ideally match "lorem.dolor"
+ */
transformed.add(".*");
break;
default:
- transformed.add(s.replaceAll("\\*", ".*"));
+ transformed.add(string.replaceAll("\\*", ".*"));
break;
}
}
- // at this point, 'transformed' looks like ["lorem", "ipsum", "[^.]+", "sit"]
+ /**
+ * at this point, 'transformed' looks like ["lorem", "ipsum", "[^.]+", "sit"]
+ */
StringBuilder sb = new StringBuilder();
- for (String s : transformed) {
- if (sb.length() > 0) sb.append("\\.");
- sb.append(s);
+ for (String string : transformed) {
+ if (sb.length() > 0) {
+ sb.append("\\.");
+ }
+ sb.append(string);
}
String join = sb.toString();
- // join = "lorem\.ipsum\.[^.]+\.sit"
-
return dest.matches(join);
}
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SimplePathMatcher.java b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SimplePathMatcher.java
index 34611d51d3ba873cd6f35b493b94036bd9f965d6..2c41911b57700005e6c5322b3ff302e105e562ac 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SimplePathMatcher.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SimplePathMatcher.java
@@ -3,12 +3,20 @@ package ua.naiksoftware.stomp.pathmatcher;
import ua.naiksoftware.stomp.dto.StompHeader;
import ua.naiksoftware.stomp.dto.StompMessage;
+/**
+ * SimplePathMatcher
+ *
+ * @since 2021-04-27
+ */
public class SimplePathMatcher implements PathMatcher {
@Override
public boolean matches(String path, StompMessage msg) {
String dest = msg.findHeader(StompHeader.DESTINATION);
- if (dest == null) return false;
- else return path.equals(dest);
+ if (dest == null) {
+ return false;
+ } else {
+ return path.equals(dest);
+ }
}
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SubscriptionPathMatcher.java b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SubscriptionPathMatcher.java
index 88862016b828279e98bd7475b5820c72233e0cb7..648b8fcc1b630f95d69ad860d174d6011f8e9cd1 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SubscriptionPathMatcher.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/pathmatcher/SubscriptionPathMatcher.java
@@ -2,23 +2,36 @@ package ua.naiksoftware.stomp.pathmatcher;
import ua.naiksoftware.stomp.StompClient;
import ua.naiksoftware.stomp.dto.StompHeader;
-import ua.naiksoftware.stomp.dto.StompHeader.*;
import ua.naiksoftware.stomp.dto.StompMessage;
+/**
+ * SubscriptionPathMatcher
+ *
+ * @since 2021-04-21
+ */
public class SubscriptionPathMatcher implements PathMatcher {
+ private final StompClient stompClient;
- private final StompClient stompClient;
-
+ /**
+ * SubscriptionPathMatcher
+ *
+ * @param stompClient
+ */
public SubscriptionPathMatcher(StompClient stompClient) {
this.stompClient = stompClient;
}
@Override
public boolean matches(String path, StompMessage msg) {
- // Compare subscription
+ /**
+ * Compare subscription
+ */
String pathSubscription = stompClient.getTopicId(path);
- if (pathSubscription == null) return false;
- String subscription = msg.findHeader(StompHeader.SUBSCRIPTION);
- return pathSubscription.equals(subscription);
+ if (pathSubscription == null) {
+ return false;
+ } else {
+ String subscription = msg.findHeader(StompHeader.SUBSCRIPTION);
+ return pathSubscription.equals(subscription);
+ }
}
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/provider/AbstractConnectionProvider.java b/lib/src/main/java/ua/naiksoftware/stomp/provider/AbstractConnectionProvider.java
index c0f938e267f826b36211b3b886f8caf88491dfa5..6a123530e6d156458f6f9861e25fccb29c6a66aa 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/provider/AbstractConnectionProvider.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/provider/AbstractConnectionProvider.java
@@ -1,27 +1,25 @@
package ua.naiksoftware.stomp.provider;
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-import android.util.Log;
-
-import java.util.concurrent.TimeUnit;
import io.reactivex.Completable;
import io.reactivex.Observable;
-import io.reactivex.schedulers.Schedulers;
+import io.reactivex.annotations.NonNull;
+import io.reactivex.annotations.Nullable;
import io.reactivex.subjects.PublishSubject;
+import ohos.hiviewdfx.HiLog;
+import ohos.hiviewdfx.HiLogLabel;
import ua.naiksoftware.stomp.dto.LifecycleEvent;
-import ua.naiksoftware.stomp.dto.StompHeader;
-import ua.naiksoftware.stomp.dto.StompCommand;
-import ua.naiksoftware.stomp.dto.StompMessage;
+
+import java.util.Collections;
/**
* Created by forresthopkinsa on 8/8/2017.
- *
* Created because there was a lot of shared code between JWS and OkHttp connection providers.
+ *
+ * @since 2021-04-27
*/
-
public abstract class AbstractConnectionProvider implements ConnectionProvider {
+ static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "AbstractConnectionProvider");
private static final String TAG = AbstractConnectionProvider.class.getSimpleName();
@@ -30,6 +28,9 @@ public abstract class AbstractConnectionProvider implements ConnectionProvider {
@NonNull
private final PublishSubject messagesStream;
+ /**
+ * 构造函数
+ */
public AbstractConnectionProvider() {
lifecycleStream = PublishSubject.create();
messagesStream = PublishSubject.create();
@@ -76,9 +77,8 @@ public abstract class AbstractConnectionProvider implements ConnectionProvider {
if (getSocket() == null) {
throw new IllegalStateException("Not connected");
} else {
- Log.d(TAG, "Send STOMP message: " + stompMessage);
rawSend(stompMessage);
- return null;
+ return Collections.emptyList();
}
});
}
@@ -107,13 +107,23 @@ public abstract class AbstractConnectionProvider implements ConnectionProvider {
@Nullable
protected abstract Object getSocket();
+ /**
+ * emitLifecycleEvent
+ *
+ * @param lifecycleEvent
+ */
protected void emitLifecycleEvent(@NonNull LifecycleEvent lifecycleEvent) {
- Log.d(TAG, "Emit lifecycle event: " + lifecycleEvent.getType().name());
+ HiLog.error(LABEL, "Emit lifecycle event: " + lifecycleEvent.getType().name());
lifecycleStream.onNext(lifecycleEvent);
}
+ /**
+ * emitMessage
+ *
+ * @param stompMessage
+ */
protected void emitMessage(String stompMessage) {
- Log.d(TAG, "Receive STOMP message: " + stompMessage);
+ HiLog.error(LABEL, "Receive STOMP message: " + stompMessage);
messagesStream.onNext(stompMessage);
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/provider/ConnectionProvider.java b/lib/src/main/java/ua/naiksoftware/stomp/provider/ConnectionProvider.java
index bfac8ee30d424e231bf1d239a774f785f3459cf4..9c66b65f58e9dbd97721c21e20f85482b3d459a4 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/provider/ConnectionProvider.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/provider/ConnectionProvider.java
@@ -6,9 +6,10 @@ import ua.naiksoftware.stomp.dto.LifecycleEvent;
/**
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-27
*/
public interface ConnectionProvider {
-
/**
* Subscribe this for receive stomp messages
*/
@@ -17,7 +18,11 @@ public interface ConnectionProvider {
/**
* Sending stomp messages via you ConnectionProvider.
* onError if not connected or error detected will be called, or onCompleted id sending started
- * TODO: send messages with ACK
+ * send messages with ACK
+ *
+ * @param stompMessage
+ * @return
+ * @noinspection checkstyle:TodoComment
*/
Completable send(String stompMessage);
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/provider/OkHttpConnectionProvider.java b/lib/src/main/java/ua/naiksoftware/stomp/provider/OkHttpConnectionProvider.java
index 3846b492ded187c23114e85ea1975ebe04a1a040..15c641cb00e5e49932b6e4a94719cee0a574e9a3 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/provider/OkHttpConnectionProvider.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/provider/OkHttpConnectionProvider.java
@@ -1,13 +1,14 @@
package ua.naiksoftware.stomp.provider;
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
+import io.reactivex.annotations.NonNull;
+import io.reactivex.annotations.Nullable;
+import ohos.hiviewdfx.HiLog;
+import ohos.hiviewdfx.HiLogLabel;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@@ -17,9 +18,15 @@ import okhttp3.WebSocketListener;
import okio.ByteString;
import ua.naiksoftware.stomp.dto.LifecycleEvent;
+/**
+ * OkHttpConnectionProvider
+ *
+ * @since 2021-04-21
+ */
public class OkHttpConnectionProvider extends AbstractConnectionProvider {
-
- public static final String TAG = "OkHttpConnProvider";
+ static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201,
+ OkHttpConnectionProvider.class.getSimpleName());
+ private static final int NUMBER_1000 = 1000;
private final String mUri;
@NonNull
@@ -29,6 +36,13 @@ public class OkHttpConnectionProvider extends AbstractConnectionProvider {
@Nullable
private WebSocket openSocket;
+ /**
+ * OkHttpConnectionProvider
+ *
+ * @param uri
+ * @param connectHttpHeaders
+ * @param okHttpClient
+ */
public OkHttpConnectionProvider(String uri, @Nullable Map connectHttpHeaders, OkHttpClient okHttpClient) {
super();
mUri = uri;
@@ -39,7 +53,7 @@ public class OkHttpConnectionProvider extends AbstractConnectionProvider {
@Override
public void rawDisconnect() {
if (openSocket != null) {
- openSocket.close(1000, "");
+ openSocket.close(NUMBER_1000, "");
}
}
@@ -80,7 +94,8 @@ public class OkHttpConnectionProvider extends AbstractConnectionProvider {
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
- // in OkHttp, a Failure is equivalent to a JWS-Error *and* a JWS-Close
+ String message = t.getMessage();
+ debug(message);
emitLifecycleEvent(new LifecycleEvent(LifecycleEvent.Type.ERROR, new Exception(t)));
openSocket = null;
emitLifecycleEvent(new LifecycleEvent(LifecycleEvent.Type.CLOSED));
@@ -95,17 +110,33 @@ public class OkHttpConnectionProvider extends AbstractConnectionProvider {
);
}
+ /**
+ * rawSend
+ *
+ * @param stompMessage message to send
+ */
@Override
protected void rawSend(String stompMessage) {
openSocket.send(stompMessage);
}
+ /**
+ * getSocket
+ *
+ * @return
+ */
@Nullable
@Override
protected Object getSocket() {
return openSocket;
}
+ /**
+ * headersAsMap
+ *
+ * @param response
+ * @return
+ */
@NonNull
private TreeMap headersAsMap(@NonNull Response response) {
TreeMap headersAsMap = new TreeMap<>();
@@ -116,9 +147,19 @@ public class OkHttpConnectionProvider extends AbstractConnectionProvider {
return headersAsMap;
}
- private void addConnectionHeadersToBuilder(@NonNull Request.Builder requestBuilder, @NonNull Map mConnectHttpHeaders) {
- for (Map.Entry headerEntry : mConnectHttpHeaders.entrySet()) {
+ /**
+ * addConnectionHeadersToBuilder
+ *
+ * @param requestBuilder
+ * @param connMap
+ */
+ private void addConnectionHeadersToBuilder(@NonNull Request.Builder requestBuilder, @NonNull Map connMap) {
+ for (Map.Entry headerEntry : connMap.entrySet()) {
requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue());
}
}
+
+ private void debug(String message) {
+ HiLog.debug(LABEL, message);
+ }
}
diff --git a/lib/src/main/java/ua/naiksoftware/stomp/provider/WebSocketsConnectionProvider.java b/lib/src/main/java/ua/naiksoftware/stomp/provider/WebSocketsConnectionProvider.java
index 3a1e8cb172a0d4d3cf4902983897ae50c548bcce..c5c5c57346fa15bbb7a79baa190664f149430ad4 100644
--- a/lib/src/main/java/ua/naiksoftware/stomp/provider/WebSocketsConnectionProvider.java
+++ b/lib/src/main/java/ua/naiksoftware/stomp/provider/WebSocketsConnectionProvider.java
@@ -1,9 +1,9 @@
package ua.naiksoftware.stomp.provider;
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-import android.util.Log;
-
+import io.reactivex.annotations.NonNull;
+import io.reactivex.annotations.Nullable;
+import ohos.hiviewdfx.HiLog;
+import ohos.hiviewdfx.HiLogLabel;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
@@ -23,9 +23,11 @@ import javax.net.ssl.SSLSocketFactory;
/**
* Created by naik on 05.05.16.
+ *
+ * @since 2021-04-21
*/
-
public class WebSocketsConnectionProvider extends AbstractConnectionProvider {
+ static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "AbstractConnectionProvider");
private static final String TAG = WebSocketsConnectionProvider.class.getSimpleName();
@@ -34,13 +36,14 @@ public class WebSocketsConnectionProvider extends AbstractConnectionProvider {
private final Map mConnectHttpHeaders;
private WebSocketClient mWebSocketClient;
- private boolean haveConnection;
+ private boolean isisHaveConnection;
private TreeMap mServerHandshakeHeaders;
/**
* Support UIR scheme ws://host:port/path
*
* @param connectHttpHeaders may be null
+ * @param uri uri
*/
public WebSocketsConnectionProvider(String uri, @Nullable Map connectHttpHeaders) {
mUri = uri;
@@ -52,21 +55,23 @@ public class WebSocketsConnectionProvider extends AbstractConnectionProvider {
try {
mWebSocketClient.closeBlocking();
} catch (InterruptedException e) {
- Log.e(TAG, "Thread interrupted while waiting for Websocket closing: ", e);
+ HiLog.error(LABEL, "Thread interrupted while waiting for Websocket closing: ", e);
throw new RuntimeException(e);
}
}
+ /**
+ * createWebSocketConnection
+ */
@Override
protected void createWebSocketConnection() {
- if (haveConnection)
+ if (isisHaveConnection) {
throw new IllegalStateException("Already have connection to web socket");
-
+ }
mWebSocketClient = new WebSocketClient(URI.create(mUri), new Draft_6455(), mConnectHttpHeaders, 0) {
-
@Override
public void onWebsocketHandshakeReceivedAsClient(WebSocket conn, ClientHandshake request, @NonNull ServerHandshake response) throws InvalidDataException {
- Log.d(TAG, "onWebsocketHandshakeReceivedAsClient with response: " + response.getHttpStatus() + " " + response.getHttpStatusMessage());
+ HiLog.error(LABEL, "onWebsocketHandshakeReceivedAsClient with response: " + response.getHttpStatus() + " " + response.getHttpStatusMessage());
mServerHandshakeHeaders = new TreeMap<>();
Iterator keys = response.iterateHttpFields();
while (keys.hasNext()) {
@@ -77,7 +82,7 @@ public class WebSocketsConnectionProvider extends AbstractConnectionProvider {
@Override
public void onOpen(@NonNull ServerHandshake handshakeData) {
- Log.d(TAG, "onOpen with handshakeData: " + handshakeData.getHttpStatus() + " " + handshakeData.getHttpStatusMessage());
+ HiLog.error(LABEL, "onOpen with handshakeData: " + handshakeData.getHttpStatus() + " " + handshakeData.getHttpStatusMessage());
LifecycleEvent openEvent = new LifecycleEvent(LifecycleEvent.Type.OPENED);
openEvent.setHandshakeResponseHeaders(mServerHandshakeHeaders);
emitLifecycleEvent(openEvent);
@@ -85,27 +90,26 @@ public class WebSocketsConnectionProvider extends AbstractConnectionProvider {
@Override
public void onMessage(String message) {
- Log.d(TAG, "onMessage: " + message);
+ HiLog.error(LABEL, "onMessage: " + message);
emitMessage(message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
- Log.d(TAG, "onClose: code=" + code + " reason=" + reason + " remote=" + remote);
- haveConnection = false;
+ HiLog.error(LABEL, "onClose: code=" + code + " reason=" + reason + " remote=" + remote);
+ isisHaveConnection = false;
emitLifecycleEvent(new LifecycleEvent(LifecycleEvent.Type.CLOSED));
- Log.d(TAG, "Disconnect after close.");
+ HiLog.error(LABEL, "Disconnect after close.");
disconnect();
}
@Override
public void onError(Exception ex) {
- Log.e(TAG, "onError", ex);
+ HiLog.error(LABEL, ex.toString());
emitLifecycleEvent(new LifecycleEvent(LifecycleEvent.Type.ERROR, ex));
}
};
-
if (mUri.startsWith("wss")) {
try {
SSLContext sc = SSLContext.getInstance("TLS");
@@ -113,12 +117,12 @@ public class WebSocketsConnectionProvider extends AbstractConnectionProvider {
SSLSocketFactory factory = sc.getSocketFactory();
mWebSocketClient.setSocket(factory.createSocket());
} catch (Exception e) {
- e.printStackTrace();
+ String message = e.getMessage();
+ HiLog.error(LABEL,message);
}
}
-
mWebSocketClient.connect();
- haveConnection = true;
+ isisHaveConnection = true;
}
@Override
diff --git a/lib/src/main/resources/base/element/string.json b/lib/src/main/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..1176aeed47b08b7dae6c1f0934ccc9f18e7708be
--- /dev/null
+++ b/lib/src/main/resources/base/element/string.json
@@ -0,0 +1,8 @@
+{
+ "string": [
+ {
+ "name": "app_name",
+ "value": "lib"
+ }
+ ]
+}
diff --git a/settings.gradle b/settings.gradle
index 7b579774d2613da8b447ce1b2bccb234b0867362..078710bce3a642ff7b589ed5ffd99ad87d4c11b0 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1 +1 @@
-include ':example-client', ':lib', ':test-server'
+include ':entry', ':lib', ':test_server'
diff --git a/test-server/README.md b/test-server/README.md
deleted file mode 100644
index e4a5bc76fbad4babfac59a3023882931db267300..0000000000000000000000000000000000000000
--- a/test-server/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Example backend with STOMP
-
-Backend for project https://github.com/NaikSoftware/StompProtocolAndroid/tree/master/example-client
-
-You need configure MQ server before (for example RabbitMQ or ActiveMQ)
\ No newline at end of file
diff --git a/test-server/src/main/resources/application.properties b/test-server/src/main/resources/application.properties
deleted file mode 100644
index d905eeeb78401416a2d233b059e21699d212865f..0000000000000000000000000000000000000000
--- a/test-server/src/main/resources/application.properties
+++ /dev/null
@@ -1,8 +0,0 @@
-server.port=8080
-
-spring.jackson.deserialization.accept_empty_string_as_null_object=true
-spring.jackson.property-naming-strategy=CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
-spring.jackson.serialization.write_char_arrays_as_json_arrays=true
-spring.jackson.serialization-inclusion=NON_NULL
-
-logging.level.org.springframework.web=DEBUG
\ No newline at end of file
diff --git a/test_server/.gitignore b/test_server/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..796b96d1c402326528b4ba3c12ee9d92d0e212e9
--- /dev/null
+++ b/test_server/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/test_server/README.md b/test_server/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..0a790e9cbc0276c3f5c241bbd4d51e22c3de6506
--- /dev/null
+++ b/test_server/README.md
@@ -0,0 +1,7 @@
+# Example backend with STOMP
+
+
+项目后端
+https://gitee.com/chinasoft3_ohos/stomp-protocol-ohos/tree/master/example-client
+
+您需要先配置MQ服务器
\ No newline at end of file
diff --git a/test-server/build.gradle b/test_server/build.gradle
similarity index 96%
rename from test-server/build.gradle
rename to test_server/build.gradle
index ccfae21a598f2e4c98170c59dd5e037fab139450..49cc2dee0e392551cf529b43976c104ae4fc6ef2 100644
--- a/test-server/build.gradle
+++ b/test_server/build.gradle
@@ -7,7 +7,7 @@ buildscript {
springBootVersion = '2.1.1.RELEASE'
springCloudVersion = 'Finchley.SR1'
}
-
+
repositories {
mavenCentral()
}
@@ -34,12 +34,17 @@ dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.15'
}
+ohos {
+ compileSdkVersion = 5
+}
+
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
+
bootJar {
destinationDir = project.file("build/artifacts")
}
diff --git a/test-server/src/main/groovy/ua/naiksoftware/test_server/Main.groovy b/test_server/src/main/groovy/ua/naiksoftware/test_server/Main.java
similarity index 67%
rename from test-server/src/main/groovy/ua/naiksoftware/test_server/Main.groovy
rename to test_server/src/main/groovy/ua/naiksoftware/test_server/Main.java
index 1809f9d3de566858a2eadee74bb1a2479c45c386..e9a284b5298b7c6b04fe3f29155dab9ac97e35a2 100644
--- a/test-server/src/main/groovy/ua/naiksoftware/test_server/Main.groovy
+++ b/test_server/src/main/groovy/ua/naiksoftware/test_server/Main.java
@@ -1,13 +1,11 @@
-package ua.naiksoftware.test_server
+package ua.naiksoftware.test_server;
-import org.springframework.boot.SpringApplication
-import org.springframework.boot.autoconfigure.SpringBootApplication
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
class Main {
-
static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
-
}
\ No newline at end of file
diff --git a/test-server/src/main/groovy/ua/naiksoftware/test_server/config/WebSocketConfig.groovy b/test_server/src/main/groovy/ua/naiksoftware/test_server/config/WebSocketConfig.groovy
similarity index 100%
rename from test-server/src/main/groovy/ua/naiksoftware/test_server/config/WebSocketConfig.groovy
rename to test_server/src/main/groovy/ua/naiksoftware/test_server/config/WebSocketConfig.groovy
diff --git a/test-server/src/main/groovy/ua/naiksoftware/test_server/controller/SocketController.groovy b/test_server/src/main/groovy/ua/naiksoftware/test_server/controller/SocketController.groovy
similarity index 100%
rename from test-server/src/main/groovy/ua/naiksoftware/test_server/controller/SocketController.groovy
rename to test_server/src/main/groovy/ua/naiksoftware/test_server/controller/SocketController.groovy
diff --git a/test-server/src/main/groovy/ua/naiksoftware/test_server/model/EchoModel.groovy b/test_server/src/main/groovy/ua/naiksoftware/test_server/model/EchoModel.groovy
similarity index 100%
rename from test-server/src/main/groovy/ua/naiksoftware/test_server/model/EchoModel.groovy
rename to test_server/src/main/groovy/ua/naiksoftware/test_server/model/EchoModel.groovy
diff --git a/test-server/src/main/groovy/ua/naiksoftware/test_server/service/SocketService.groovy b/test_server/src/main/groovy/ua/naiksoftware/test_server/service/SocketService.groovy
similarity index 100%
rename from test-server/src/main/groovy/ua/naiksoftware/test_server/service/SocketService.groovy
rename to test_server/src/main/groovy/ua/naiksoftware/test_server/service/SocketService.groovy