From 11942512d433de0acd50851bbebc880a9683be33 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 27 Nov 2019 10:59:08 +0100 Subject: [PATCH 01/20] fix NullPointerException --- .../java/com/hivemq/cli/mqtt/MqttClientExecutor.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index 40281b441..c1826c0d1 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -151,7 +151,10 @@ else if (subscribe.isDebug()) { Logger.error("SUBSCRIBE to TOPIC '{}' failed with '{}'", topic, MqttUtils.getRootCause(throwable).getMessage()); } else { - getClientDataMap().get(subscribe.getKey()).addSubscription(MqttTopicFilter.of(topic)); + final String clientKey = MqttUtils.buildKey(client.getConfig().getClientIdentifier().get().toString(), + client.getConfig().getServerHost()); + + getClientDataMap().get(clientKey).addSubscription(MqttTopicFilter.of(topic)); if (subscribe.isVerbose()) { Logger.trace("received SUBACK: {}", subAck); @@ -199,7 +202,10 @@ else if (subscribe.isDebug()) { Logger.error("SUBSCRIBE to TOPIC '{}' failed with '{}'", topic, MqttUtils.getRootCause(throwable).getMessage()); } else { - getClientDataMap().get(subscribe.getKey()).addSubscription(MqttTopicFilter.of(topic)); + final String clientKey = MqttUtils.buildKey(client.getConfig().getClientIdentifier().get().toString(), + client.getConfig().getServerHost()); + + getClientDataMap().get(clientKey).addSubscription(MqttTopicFilter.of(topic)); if (subscribe.isVerbose()) { Logger.trace("received SUBACK: {}", subAck); From 1b8300194c3524d44ead43aeb8c9508dfa056a96 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 27 Nov 2019 11:41:40 +0100 Subject: [PATCH 02/20] fix NullPointerException --- .../java/com/hivemq/cli/commands/cli/SubscribeCommand.java | 6 ++++-- .../com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index 8dc569df9..74ec98764 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -24,6 +24,7 @@ import com.hivemq.cli.impl.MqttAction; import com.hivemq.cli.mqtt.MqttClientExecutor; import com.hivemq.cli.utils.MqttUtils; +import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; @@ -50,6 +51,7 @@ public class SubscribeCommand extends AbstractConnectFlags implements MqttAction private final MqttClientExecutor mqttClientExecutor; private final DefaultCLIProperties defaultCLIProperties; + private MqttClient subscribeClient; private MqttClientSslConfig sslConfig; @@ -112,7 +114,7 @@ public void run() { try { qos = MqttUtils.arrangeQosToMatchTopics(topics, qos); - mqttClientExecutor.subscribe(this); + subscribeClient = mqttClientExecutor.subscribe(this); } catch (final Exception ex) { if (ex instanceof ConnectionFailedException) { @@ -157,7 +159,7 @@ public void logUnusedOptions() { } private void stay() throws InterruptedException { - while (mqttClientExecutor.isConnected(this)) { + while (subscribeClient.getState().isConnectedOrReconnect()) { Thread.sleep(IDLE_TIME); } if (isVerbose()) { diff --git a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java index b88dccbce..ba3377db2 100644 --- a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java @@ -78,12 +78,14 @@ abstract class AbstractMqttClientExecutor { abstract void mqtt3Disconnect(final @NotNull Mqtt3Client client, final @NotNull Disconnect disconnect); - public void subscribe(final @NotNull SubscribeCommand subscribeCommand) { + public MqttClient subscribe(final @NotNull SubscribeCommand subscribeCommand) { final MqttClient client = connect(subscribeCommand); subscribe(client, subscribeCommand); + return client; + } public void subscribe(final @NotNull MqttClient client, final @NotNull Subscribe subscribe) { From 3dac8c8f95c5feda61805062bf3ce4382dea0220 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 27 Nov 2019 13:57:16 +0100 Subject: [PATCH 03/20] use QoS 0 as default QoS --- src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java index 9d76526fe..833155853 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java @@ -41,7 +41,7 @@ public abstract class AbstractWillFlags extends MqttCommand implements Will { @Nullable private ByteBuffer willMessage; - @CommandLine.Option(names = {"-Wq", "--willQualityOfService"}, converter = MqttQosConverter.class, description = "Quality of service level for the will message (default: 0)", order = 3) + @CommandLine.Option(names = {"-Wq", "--willQualityOfService"}, defaultValue = "0", converter = MqttQosConverter.class, description = "Quality of service level for the will message (default: 0)", order = 3) @Nullable private MqttQos willQos; From 145c63dad933746722b6e407b214e218eeb8d197 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 4 Dec 2019 10:07:37 +0100 Subject: [PATCH 04/20] remove unnecessary code --- src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index c1826c0d1..e055e196c 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -266,8 +266,6 @@ else if (publish.isDebug()) { } else { - final String p = bufferToString(publish.getMessage()); - if (publish.isVerbose()) { Logger.trace("acknowledged PUBLISH: '{}' for PUBLISH to TOPIC: '{}'", publishResult, topic); } @@ -325,8 +323,6 @@ else if (publish.isDebug()) { } else { - final String p = bufferToString(publish.getMessage()); - if (publish.isVerbose()) { Logger.trace("acknowledged PUBLISH: '{}' for PUBLISH to TOPIC: '{}'", publishResult, topic); } From 26ff0738d3f97c014b02c056aca4b45d5185087e Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 4 Dec 2019 10:38:44 +0100 Subject: [PATCH 05/20] decouple subscription callbacks --- .../shell/ContextSubscribeCommand.java | 21 ++++------ .../mqtt/SubscribeMqtt3PublishCallback.java | 39 +++++++++++++------ .../mqtt/SubscribeMqtt5PublishCallback.java | 33 +++++++++++----- 3 files changed, 59 insertions(+), 34 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java index f07f77111..2b8808553 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java @@ -143,20 +143,16 @@ private void stay() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - final Runnable waitForDisconnectRunnable = new Runnable() { - - @Override - public void run() { - while (contextClient.getState().isConnected()) { - try { - Thread.sleep(IDLE_TIME); - } - catch (final InterruptedException e) { - return; - } + final Runnable waitForDisconnectRunnable = () -> { + while (contextClient.getState().isConnected()) { + try { + Thread.sleep(IDLE_TIME); + } + catch (final InterruptedException e) { + return; } - latch.countDown(); } + latch.countDown(); }; final Runnable waitForExitCommandRunnable = new Runnable() { @@ -165,7 +161,6 @@ public void run() { final Scanner scanner = new Scanner(System.in); scanner.nextLine(); latch.countDown(); - return; } }; diff --git a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java index 4f933c762..8b7a307e6 100644 --- a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java +++ b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java @@ -21,33 +21,45 @@ import com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3Publish; import org.bouncycastle.util.encoders.Base64; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.pmw.tinylog.Logger; +import java.io.File; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.function.Consumer; public class SubscribeMqtt3PublishCallback implements Consumer { - @NotNull private final Subscribe subscribe; + @NotNull private final String identifier; + @Nullable private final File publishFile; + private final boolean printToStdout; + private final boolean isBase64; + private final boolean debug; + private final boolean verbose; - public SubscribeMqtt3PublishCallback(final @NotNull Subscribe subscribe) { - this.subscribe = subscribe; + SubscribeMqtt3PublishCallback(final @NotNull Subscribe subscribe) { + identifier = subscribe.getIdentifier(); + printToStdout = subscribe.isPrintToSTDOUT(); + publishFile = subscribe.getPublishFile(); + isBase64 = subscribe.isBase64(); + debug = subscribe.isDebug(); + verbose = subscribe.isVerbose(); } @Override public void accept(final @NotNull Mqtt3Publish mqtt3Publish) { PrintWriter fileWriter = null; - if (subscribe.getPublishFile() != null) { - fileWriter = FileUtils.createFileAppender(subscribe.getPublishFile()); + if (publishFile != null) { + fileWriter = FileUtils.createFileAppender(publishFile); } byte[] payload = mqtt3Publish.getPayloadAsBytes(); String payloadMessage = new String(payload); - if (subscribe.isBase64()) { + if (isBase64) { payloadMessage = Base64.toBase64String(payload); } @@ -57,15 +69,20 @@ public void accept(final @NotNull Mqtt3Publish mqtt3Publish) { fileWriter.close(); } - if (subscribe.isPrintToSTDOUT()) { + if (printToStdout) { System.out.println(payloadMessage); } - if (subscribe.isVerbose()) { - Logger.trace("received PUBLISH: {}, MESSAGE: '{}'", mqtt3Publish, new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); + if (verbose) { + Logger.trace("Client {} received PUBLISH: {}, MESSAGE: '{}'", + identifier, + mqtt3Publish, + new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } - else if (subscribe.isDebug()) { - Logger.debug("received PUBLISH: (Topic: '{}', MESSAGE: '{}')", mqtt3Publish.getTopic(), new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); + else if (debug) { + Logger.debug("Client {} received PUBLISH: (Topic: '{}', MESSAGE: '{}')", + identifier, + mqtt3Publish.getTopic(), new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } } diff --git a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java index 8a35195d0..7f7f096b6 100644 --- a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java +++ b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java @@ -21,33 +21,46 @@ import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish; import org.bouncycastle.util.encoders.Base64; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.pmw.tinylog.Logger; +import org.pmw.tinylog.LoggingContext; +import java.io.File; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.function.Consumer; public class SubscribeMqtt5PublishCallback implements Consumer { - @NotNull private final Subscribe subscribe; + @NotNull private final String identifier; + @Nullable private final File publishFile; + private final boolean printToStdout; + private final boolean isBase64; + private final boolean debug; + private final boolean verbose; SubscribeMqtt5PublishCallback(final @NotNull Subscribe subscribe) { - this.subscribe = subscribe; + identifier = subscribe.getIdentifier(); + printToStdout = subscribe.isPrintToSTDOUT(); + publishFile = subscribe.getPublishFile(); + isBase64 = subscribe.isBase64(); + debug = subscribe.isDebug(); + verbose = subscribe.isVerbose(); } @Override public void accept(final @NotNull Mqtt5Publish mqtt5Publish) { PrintWriter fileWriter = null; - if (subscribe.getPublishFile() != null) { - fileWriter = FileUtils.createFileAppender(subscribe.getPublishFile()); + if (publishFile != null) { + fileWriter = FileUtils.createFileAppender(publishFile); } byte[] payload = mqtt5Publish.getPayloadAsBytes(); String payloadMessage = new String(payload); - if (subscribe.isBase64()) { + if (isBase64) { payloadMessage = Base64.toBase64String(payload); } @@ -57,15 +70,15 @@ public void accept(final @NotNull Mqtt5Publish mqtt5Publish) { fileWriter.close(); } - if (subscribe.isPrintToSTDOUT()) { + if (printToStdout) { System.out.println(payloadMessage); } - if (subscribe.isVerbose()) { - Logger.trace("received PUBLISH: {}, MESSAGE: '{}'", mqtt5Publish, new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); + if (verbose) { + Logger.trace("Client {} received PUBLISH: {}, MESSAGE: '{}'", identifier, mqtt5Publish, new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } - else if (subscribe.isDebug()) { - Logger.debug("received PUBLISH: (Topic: '{}', MESSAGE: '{}')", mqtt5Publish.getTopic(), new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); + else if (debug) { + Logger.debug("Client {} received PUBLISH: (Topic: '{}', MESSAGE: '{}')", identifier, mqtt5Publish.getTopic(), new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } } From 62920a21a976627f4bacb30571b6e10840ccfac4 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 4 Dec 2019 16:59:46 +0100 Subject: [PATCH 06/20] refactor loggin --- src/main/java/com/hivemq/cli/MqttCLIMain.java | 2 +- .../cli/commands/AbstractCommonFlags.java | 12 - .../AbstractConnectRestrictionFlags.java | 31 --- .../cli/commands/AbstractWillFlags.java | 43 --- .../com/hivemq/cli/commands/MqttCommand.java | 21 -- .../commands/cli/AbstractConnectFlags.java | 12 +- .../cli/commands/cli/PublishCommand.java | 87 +----- .../cli/commands/cli/SubscribeCommand.java | 77 +----- .../commands/shell/ClearScreenCommand.java | 10 +- .../shell/ContextDisconnectCommand.java | 28 +- .../commands/shell/ContextExitCommand.java | 4 - .../commands/shell/ContextPublishCommand.java | 74 +---- .../shell/ContextSubscribeCommand.java | 56 +--- .../commands/shell/ContextSwitchCommand.java | 17 +- .../shell/ContextUnsubscribeCommand.java | 21 +- .../commands/shell/ListClientsCommand.java | 4 +- .../cli/commands/shell/ShellCommand.java | 37 +-- .../commands/shell/ShellConnectCommand.java | 43 +-- .../commands/shell/ShellContextCommand.java | 10 +- .../shell/ShellDisconnectCommand.java | 43 +-- .../cli/commands/shell/ShellExitCommand.java | 4 - .../cli/mqtt/AbstractMqttClientExecutor.java | 21 -- .../mqtt/ContextClientDisconnectListener.java | 12 +- .../hivemq/cli/mqtt/MqttClientExecutor.java | 258 ++++++++++++------ .../com/hivemq/cli/utils/LoggerUtils.java | 73 +++++ 25 files changed, 353 insertions(+), 647 deletions(-) create mode 100644 src/main/java/com/hivemq/cli/utils/LoggerUtils.java diff --git a/src/main/java/com/hivemq/cli/MqttCLIMain.java b/src/main/java/com/hivemq/cli/MqttCLIMain.java index a14cecdd8..da4d3c762 100644 --- a/src/main/java/com/hivemq/cli/MqttCLIMain.java +++ b/src/main/java/com/hivemq/cli/MqttCLIMain.java @@ -44,7 +44,7 @@ public static void main(final String[] args) { Configurator.defaultConfig() .writer(new ConsoleWriter()) - .formatPattern("{context:identifier}: {message}") + .formatPattern("{message}") .level(Level.INFO) .activate(); diff --git a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java index d8c4e2cf5..229ee5cb6 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java @@ -315,28 +315,16 @@ public ByteBuffer getPassword() { return password; } - public void setPassword(final @Nullable ByteBuffer password) { - this.password = password; - } - @Nullable public Integer getKeepAlive() { return keepAlive; } - public void setKeepAlive(final @Nullable Integer keepAlive) { - this.keepAlive = keepAlive; - } - @Nullable public Boolean getCleanStart() { return cleanStart; } - public void setCleanStart(final @Nullable Boolean cleanStart) { - this.cleanStart = cleanStart; - } - @Nullable public MqttWebSocketConfig getWebSocketConfig() { if (useWebSocket) { diff --git a/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java index f47417c0b..a296b4e41 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java @@ -113,77 +113,46 @@ public Integer getReceiveMaximum() { return receiveMaximum; } - public void setReceiveMaximum(@Nullable final Integer receiveMaximum) { - this.receiveMaximum = receiveMaximum; - } - @Nullable @Override public Integer getSendMaximum() { return sendMaximum; } - public void setSendMaximum(@Nullable final Integer sendMaximum) { - this.sendMaximum = sendMaximum; - } - @Nullable @Override public Integer getMaximumPacketSize() { return maximumPacketSize; } - public void setMaximumPacketSize(@Nullable final Integer maximumPacketSize) { - this.maximumPacketSize = maximumPacketSize; - } - @Nullable @Override public Integer getSendMaximumPacketSize() { return sendMaximumPacketSize; } - public void setSendMaximumPacketSize(@Nullable final Integer sendMaximumPacketSize) { - this.sendMaximumPacketSize = sendMaximumPacketSize; - } - @Nullable @Override public Integer getTopicAliasMaximum() { return topicAliasMaximum; } - public void setTopicAliasMaximum(@Nullable final Integer topicAliasMaximum) { - this.topicAliasMaximum = topicAliasMaximum; - } - @Nullable @Override public Integer getSendTopicAliasMaximum() { return sendTopicAliasMaximum; } - public void setSendTopicAliasMaximum(@Nullable final Integer sendTopicAliasMaximum) { - this.sendTopicAliasMaximum = sendTopicAliasMaximum; - } - @Nullable @Override public Boolean getRequestProblemInformation() { return requestProblemInformation; } - public void setRequestProblemInformation(@Nullable final Boolean requestProblemInformation) { - this.requestProblemInformation = requestProblemInformation; - } - @Nullable @Override public Boolean getRequestResponseInformation() { return requestResponseInformation; } - public void setRequestResponseInformation(@Nullable final Boolean requestResponseInformation) { - this.requestResponseInformation = requestResponseInformation; - } } diff --git a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java index 833155853..aeeafd250 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java @@ -124,107 +124,64 @@ public String getWillTopic() { return willTopic; } - public void setWillTopic(@Nullable final String willTopic) { - this.willTopic = willTopic; - } - @Nullable @Override public ByteBuffer getWillMessage() { return willMessage; } - public void setWillMessage(@Nullable final ByteBuffer willMessage) { - this.willMessage = willMessage; - } - @Nullable @Override public MqttQos getWillQos() { return willQos; } - public void setWillQos(@Nullable final MqttQos willQos) { - this.willQos = willQos; - } - @Nullable @Override public Boolean getWillRetain() { return willRetain; } - public void setWillRetain(final @Nullable Boolean willRetain) { - this.willRetain = willRetain; - } - @Nullable @Override public Long getWillMessageExpiryInterval() { return willMessageExpiryInterval; } - public void setWillMessageExpiryInterval(@Nullable final Long willMessageExpiryInterval) { - this.willMessageExpiryInterval = willMessageExpiryInterval; - } - @Nullable @Override public Long getWillDelayInterval() { return willDelayInterval; } - public void setWillDelayInterval(final long willDelayInterval) { - this.willDelayInterval = willDelayInterval; - } - @Nullable @Override public Mqtt5PayloadFormatIndicator getWillPayloadFormatIndicator() { return willPayloadFormatIndicator; } - public void setWillPayloadFormatIndicator(@Nullable final Mqtt5PayloadFormatIndicator willPayloadFormatIndicator) { - this.willPayloadFormatIndicator = willPayloadFormatIndicator; - } - @Nullable @Override public String getWillContentType() { return willContentType; } - public void setWillContentType(@Nullable final String willContentType) { - this.willContentType = willContentType; - } - @Nullable @Override public String getWillResponseTopic() { return willResponseTopic; } - public void setWillResponseTopic(@Nullable final String willResponseTopic) { - this.willResponseTopic = willResponseTopic; - } - @Nullable @Override public ByteBuffer getWillCorrelationData() { return willCorrelationData; } - public void setWillCorrelationData(@Nullable final ByteBuffer willCorrelationData) { - this.willCorrelationData = willCorrelationData; - } - @Nullable @Override public Mqtt5UserProperties getWillUserProperties() { return MqttUtils.convertToMqtt5UserProperties(willUserProperties); } - public void setWillUserProperties(@Nullable final Mqtt5UserProperty... willUserProperties) { - this.willUserProperties = willUserProperties; - } } diff --git a/src/main/java/com/hivemq/cli/commands/MqttCommand.java b/src/main/java/com/hivemq/cli/commands/MqttCommand.java index 21539d246..dbd373bab 100644 --- a/src/main/java/com/hivemq/cli/commands/MqttCommand.java +++ b/src/main/java/com/hivemq/cli/commands/MqttCommand.java @@ -34,7 +34,6 @@ @CommandLine.Command() public abstract class MqttCommand extends AbstractCommand implements Context { - @CommandLine.Option(names = {"-V", "--mqttVersion"}, converter = MqttVersionConverter.class, description = "The mqtt version used by the client (default: 5)", order = 1) private MqttVersion version; @@ -154,34 +153,14 @@ public String getHost() { return host; } - public void setHost(final String host) { - this.host = host; - } - public int getPort() { return port; } - public void setPort(final int port) { - this.port = port; - } - @NotNull @Override public String getIdentifier() { return identifier; } - public void setIdentifier(final @Nullable String identifier) { - this.identifier = identifier; - } - - @Nullable - public String getIdentifierPrefix() { - return identifierPrefix; - } - - public void setIdentifierPrefix(final String identifierPrefix) { - this.identifierPrefix = identifierPrefix; - } } diff --git a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java index 57624dfaf..b70bb9f6e 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java +++ b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java @@ -28,6 +28,8 @@ import org.pmw.tinylog.Logger; import picocli.CommandLine; +import java.util.Arrays; + public abstract class AbstractConnectFlags extends AbstractCommonFlags implements Connect { @CommandLine.Option(names = {"-se", "--sessionExpiryInterval"}, converter = UnsignedIntConverter.class, description = "The lifetime of the session of the connected client", order = 2) @@ -42,7 +44,7 @@ public abstract class AbstractConnectFlags extends AbstractCommonFlags implement String connectOptions() { return commonOptions() + ", sessionExpiryInterval= " + sessionExpiryInterval + - ", userProperties=" + connectUserProperties + + ", userProperties=" + (connectUserProperties == null? null : Arrays.toString(connectUserProperties)) + ", " + connectRestrictionOptions(); } @@ -66,17 +68,9 @@ public Long getSessionExpiryInterval() { return sessionExpiryInterval; } - public void setSessionExpiryInterval(@Nullable final Long sessionExpiryInterval) { - this.sessionExpiryInterval = sessionExpiryInterval; - } - @Nullable public Mqtt5UserProperties getConnectUserProperties() { return MqttUtils.convertToMqtt5UserProperties(connectUserProperties); } - public void setConnectUserProperties(@Nullable final Mqtt5UserProperty... connectUserProperties) { - this.connectUserProperties = connectUserProperties; - } - } diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index d4f180277..1fc6fbbfc 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -21,6 +21,7 @@ import com.hivemq.cli.converters.*; import com.hivemq.cli.impl.MqttAction; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; @@ -69,55 +70,38 @@ public PublishCommand(final @NotNull MqttClientExecutor mqttClientExecutor) { boolean usageHelpRequested; @CommandLine.Option(names = {"-t", "--topic"}, required = true, description = "The topics to publish to", order = 1) - @NotNull - private String[] topics; + @NotNull private String[] topics; @CommandLine.Option(names = {"-q", "--qos"}, converter = MqttQosConverter.class, defaultValue = "0", description = "Quality of service for the corresponding topic (default for all: 0)", order = 1) - @NotNull - private MqttQos[] qos; + @NotNull private MqttQos[] qos; @CommandLine.Option(names = {"-m", "--message"}, converter = ByteBufferConverter.class, required = true, description = "The message to publish", order = 1) - @NotNull - private ByteBuffer message; + @NotNull private ByteBuffer message; @CommandLine.Option(names = {"-r", "--retain"}, negatable = true, description = "The message will be retained (default: false)", order = 1) - @Nullable - private Boolean retain; + @Nullable private Boolean retain; @CommandLine.Option(names = {"-e", "--messageExpiryInterval"}, converter = UnsignedIntConverter.class, description = "The lifetime of the publish message in seconds (default: no message expiry)", order = 1) - @Nullable - private Long messageExpiryInterval; + @Nullable private Long messageExpiryInterval; @CommandLine.Option(names = {"-pf", "--payloadFormatIndicator"}, converter = PayloadFormatIndicatorConverter.class, description = "The payload format indicator of the publish message", order = 1) - @Nullable - private Mqtt5PayloadFormatIndicator payloadFormatIndicator; + @Nullable private Mqtt5PayloadFormatIndicator payloadFormatIndicator; @CommandLine.Option(names = {"-ct", "--contentType"}, description = "A description of publish message's content", order = 1) - @Nullable - private String contentType; + @Nullable private String contentType; @CommandLine.Option(names = {"-rt", "--responseTopic"}, description = "The topic name for the publish message`s response message", order = 1) - @Nullable - private String responseTopic; + @Nullable private String responseTopic; @CommandLine.Option(names = {"-cd", "--correlationData"}, converter = ByteBufferConverter.class, description = "The correlation data of the publish message", order = 1) - @Nullable - private ByteBuffer correlationData; - + @Nullable private ByteBuffer correlationData; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property of the publish message", order = 1) - @Nullable - private Mqtt5UserProperty[] userProperties; + @Nullable private Mqtt5UserProperty[] userProperties; @Override public void run() { - LoggingContext.put("identifier", "PUBLISH"); - - if (isVerbose()) { - Logger.trace("Command: {} ", this); - } - setDefaultOptions(); sslConfig = buildSslConfig(); @@ -128,19 +112,7 @@ public void run() { mqttClientExecutor.publish(this); } catch (final Exception ex) { - if (ex instanceof ConnectionFailedException) { - LoggingContext.put("identifier", "CONNECT ERROR:"); - } - else { - LoggingContext.put("identifier", "PUBLISH ERROR:"); - } - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logOnRightLevels(this, ex); } } @@ -195,20 +167,12 @@ public String[] getTopics() { return topics; } - public void setTopics(final String[] topics) { - this.topics = topics; - } - @NotNull @Override public MqttQos[] getQos() { return qos; } - public void setQos(final MqttQos[] qos) { - this.qos = qos; - } - @NotNull @Override public ByteBuffer getMessage() { @@ -225,60 +189,36 @@ public Boolean getRetain() { return retain; } - public void setRetain(final @Nullable Boolean retain) { - this.retain = retain; - } - @Override @Nullable public Long getMessageExpiryInterval() { return messageExpiryInterval; } - public void setMessageExpiryInterval(@Nullable final Long messageExpiryInterval) { - this.messageExpiryInterval = messageExpiryInterval; - } - @Nullable @Override public Mqtt5PayloadFormatIndicator getPayloadFormatIndicator() { return payloadFormatIndicator; } - public void setPayloadFormatIndicator(@Nullable final Mqtt5PayloadFormatIndicator payloadFormatIndicator) { - this.payloadFormatIndicator = payloadFormatIndicator; - } - @Nullable @Override public String getContentType() { return contentType; } - public void setContentType(@Nullable final String contentType) { - this.contentType = contentType; - } - @Nullable @Override public String getResponseTopic() { return responseTopic; } - public void setResponseTopic(@Nullable final String responseTopic) { - this.responseTopic = responseTopic; - } - @Nullable @Override public ByteBuffer getCorrelationData() { return correlationData; } - public void setCorrelationData(@Nullable final ByteBuffer correlationData) { - this.correlationData = correlationData; - } - @Nullable @Override public Mqtt5UserProperties getUserProperties() { @@ -295,7 +235,4 @@ public MqttClientSslConfig getSslConfig() { return sslConfig; } - public void setSslConfig(final MqttClientSslConfig sslConfig) { - this.sslConfig = sslConfig; - } } diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index 74ec98764..6c3c52a2c 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -23,6 +23,7 @@ import com.hivemq.cli.converters.MqttQosConverter; import com.hivemq.cli.impl.MqttAction; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.MqttClientSslConfig; @@ -59,7 +60,7 @@ public class SubscribeCommand extends AbstractConnectFlags implements MqttAction //needed for pico cli - reflection code generation public SubscribeCommand() { - this(null,null); + this(null, null); } @Inject @@ -76,19 +77,16 @@ public SubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecutor, boolean usageHelpRequested; @CommandLine.Option(names = {"-t", "--topic"}, required = true, description = "The topics to subscribe to", order = 1) - @NotNull - private String[] topics; + @NotNull private String[] topics; @CommandLine.Option(names = {"-q", "--qos"}, converter = MqttQosConverter.class, defaultValue = "2", description = "Quality of service for the corresponding topics (default for all: 2)", order = 1) - @NotNull - private MqttQos[] qos; + @NotNull private MqttQos[] qos; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property of the subscribe message", order = 1) - @Nullable Mqtt5UserProperty[] userProperties; + @Nullable private Mqtt5UserProperty[] userProperties; @CommandLine.Option(names = {"-of", "--outputToFile"}, description = "A file to which the received publish messages will be written", order = 1) - @Nullable - private File publishFile; + @Nullable private File publishFile; @CommandLine.Option(names = {"-oc", "--outputToConsole"}, hidden = true, defaultValue = "true", description = "The received messages will be written to the console (default: true)", order = 1) private boolean printToSTDOUT; @@ -98,18 +96,8 @@ public SubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecutor, @Override public void run() { - - LoggingContext.put("identifier", "SUBSCRIBE"); - - - if (isVerbose()) { - Logger.trace("Command: {} ", this); - } - setDefaultOptions(); - sslConfig = buildSslConfig(); - logUnusedOptions(); try { @@ -117,32 +105,14 @@ public void run() { subscribeClient = mqttClientExecutor.subscribe(this); } catch (final Exception ex) { - if (ex instanceof ConnectionFailedException) { - LoggingContext.put("identifier", "CONNECT ERROR:"); - } - else { - LoggingContext.put("identifier", "SUBSCRIBE ERROR:"); - } - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logOnRightLevels(this, ex); } try { stay(); } catch (final InterruptedException ex) { - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logOnRightLevels(this, ex); } @@ -163,7 +133,7 @@ private void stay() throws InterruptedException { Thread.sleep(IDLE_TIME); } if (isVerbose()) { - Logger.trace("Client disconnected."); + Logger.trace("Client disconnected"); } } @@ -200,65 +170,38 @@ public String[] getTopics() { return topics; } - public void setTopics(final String[] topics) { - this.topics = topics; - } - @NotNull @Override public MqttQos[] getQos() { return qos; } - public void setQos(final MqttQos[] qos) { - this.qos = qos; - } - @Nullable @Override public File getPublishFile() { return publishFile; } - public void setPublishFile(@Nullable final File publishFile) { - this.publishFile = publishFile; - } - public boolean isPrintToSTDOUT() { return printToSTDOUT; } - public void setPrintToSTDOUT(final boolean printToSTDOUT) { - this.printToSTDOUT = printToSTDOUT; - } - public boolean isBase64() { return base64; } - public void setBase64(final boolean base64) { - this.base64 = base64; - } - @Nullable @Override - public Mqtt5UserProperties getUserProperties() { - - return MqttUtils.convertToMqtt5UserProperties(userProperties); - } + public Mqtt5UserProperties getUserProperties() { return MqttUtils.convertToMqtt5UserProperties(userProperties); } public void setUserProperties(@Nullable final Mqtt5UserProperty... userProperties) { this.userProperties = userProperties; } - @Nullable @Override public MqttClientSslConfig getSslConfig() { return sslConfig; } - public void setSslConfig(final MqttClientSslConfig sslConfig) { - this.sslConfig = sslConfig; - } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java index 9f88a6553..9b0e9c21a 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java @@ -37,18 +37,12 @@ public class ClearScreenCommand implements CliCommand, Callable { @Inject - ClearScreenCommand() { - } + ClearScreenCommand() {} @CommandLine.Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message") boolean usageHelpRequested; - public Void call() throws IOException { - - if (isVerbose()) { - Logger.trace("Command: {}", this); - } - + public Void call() { ShellCommand.clearScreen(); return null; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java index 84b48a6f4..49a9bd6f4 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java @@ -20,6 +20,7 @@ import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; import com.hivemq.cli.converters.UnsignedIntConverter; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; @@ -55,20 +56,18 @@ public ContextDisconnectCommand(final @NotNull MqttClientExecutor executor) { private boolean disconnectAll; @CommandLine.Option(names = {"-e", "--sessionExpiryInterval"}, converter = UnsignedIntConverter.class, description = "The session expiry of the disconnect (default: 0)") - @Nullable - private Long sessionExpiryInterval; + @Nullable private Long sessionExpiryInterval; @CommandLine.Option(names = {"-r", "--reason"}, description = "The reason of the disconnect") - @Nullable - private String reasonString; + @Nullable private String reasonString; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property of the disconnect message") - @Nullable - private Mqtt5UserProperty[] userProperties; + @Nullable private Mqtt5UserProperty[] userProperties; @Override public void run() { + // TODO if (isVerbose()) { Logger.trace("Command: {} ", this); } @@ -84,14 +83,7 @@ public void run() { } } catch (final Exception ex) { - LoggingContext.put("identifier", "DISCONNECT"); - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logWithCurrentContext(this, ex); } } @@ -125,20 +117,12 @@ public Long getSessionExpiryInterval() { return sessionExpiryInterval; } - public void setSessionExpiryInterval(@Nullable final Long sessionExpiryInterval) { - this.sessionExpiryInterval = sessionExpiryInterval; - } - @Nullable @Override public String getReasonString() { return reasonString; } - public void setReasonString(@Nullable final String reasonString) { - this.reasonString = reasonString; - } - @Nullable @Override public Mqtt5UserProperties getUserProperties() { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java index 145e94e4f..c0cf1ecd3 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java @@ -42,10 +42,6 @@ public ContextExitCommand(@NotNull MqttClientExecutor mqttClientExecutor) { @Override public void run() { - if (isVerbose()) { - Logger.trace("Command: {} ", this); - } - removeContext(); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java index 80ad4af3c..d9a255854 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java @@ -19,6 +19,7 @@ import com.hivemq.cli.commands.Publish; import com.hivemq.cli.converters.*; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; @@ -57,45 +58,34 @@ public ContextPublishCommand(final @NotNull MqttClientExecutor executor) { boolean usageHelpRequested; @CommandLine.Option(names = {"-t", "--topic"}, required = true, description = "The topics to publish to") - @NotNull - private String[] topics; + @NotNull private String[] topics; @CommandLine.Option(names = {"-q", "--qos"}, converter = MqttQosConverter.class, defaultValue = "0", description = "Quality of service for the corresponding topic (default for all: 0)") - @NotNull - private MqttQos[] qos; + @NotNull private MqttQos[] qos; @CommandLine.Option(names = {"-m", "--message"}, converter = ByteBufferConverter.class, required = true, description = "The message to publish") - @NotNull - private ByteBuffer message; + @NotNull private ByteBuffer message; @CommandLine.Option(names = {"-r", "--retain"}, negatable = true, defaultValue = "false", description = "The message will be retained (default: false)") - @Nullable - private Boolean retain; + @Nullable private Boolean retain; @CommandLine.Option(names = {"-e", "--messageExpiryInterval"}, converter = UnsignedIntConverter.class, description = "The lifetime of the publish message in seconds (default: no message expiry)") - @Nullable - private Long messageExpiryInterval; + @Nullable private Long messageExpiryInterval; @CommandLine.Option(names = {"-pf", "--payloadFormatIndicator"}, converter = PayloadFormatIndicatorConverter.class, description = "The payload format indicator of the publish message") - @Nullable - private Mqtt5PayloadFormatIndicator payloadFormatIndicator; + @Nullable private Mqtt5PayloadFormatIndicator payloadFormatIndicator; @CommandLine.Option(names = {"-ct", "--contentType"}, description = "A description of publish message's content") - @Nullable - private String contentType; + @Nullable private String contentType; @CommandLine.Option(names = {"-rt", "--responseTopic"}, description = "The topic name for the publish message`s response message") - @Nullable - private String responseTopic; + @Nullable private String responseTopic; @CommandLine.Option(names = {"-cd", "--correlationData"}, converter = ByteBufferConverter.class, description = "The correlation data of the publish message") - @Nullable - private ByteBuffer correlationData; + @Nullable private ByteBuffer correlationData; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property of the publish message") - @Nullable - private Mqtt5UserProperty[] userProperties; - + @Nullable private Mqtt5UserProperty[] userProperties; @Override public void run() { @@ -110,17 +100,11 @@ public void run() { mqttClientExecutor.publish(contextClient, this); } catch (final Exception ex) { - LoggingContext.put("identifier", "PUBLISH"); - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logWithCurrentContext(this, ex); } } + //TODO private void logUnusedOptions() { if (contextClient.getConfig().getMqttVersion() == MqttVersion.MQTT_3_1_1) { if (messageExpiryInterval != null) { @@ -166,20 +150,12 @@ public String[] getTopics() { return topics; } - public void setTopics(final String[] topics) { - this.topics = topics; - } - @NotNull @Override public MqttQos[] getQos() { return qos; } - public void setQos(final MqttQos[] qos) { - this.qos = qos; - } - @NotNull @Override public ByteBuffer getMessage() { @@ -196,60 +172,36 @@ public Boolean getRetain() { return retain; } - public void setRetain(final @Nullable Boolean retain) { - this.retain = retain; - } - @Nullable @Override public Long getMessageExpiryInterval() { return messageExpiryInterval; } - public void setMessageExpiryInterval(@Nullable final Long messageExpiryInterval) { - this.messageExpiryInterval = messageExpiryInterval; - } - @Nullable @Override public Mqtt5PayloadFormatIndicator getPayloadFormatIndicator() { return payloadFormatIndicator; } - public void setPayloadFormatIndicator(@Nullable final Mqtt5PayloadFormatIndicator payloadFormatIndicator) { - this.payloadFormatIndicator = payloadFormatIndicator; - } - @Nullable @Override public String getContentType() { return contentType; } - public void setContentType(@Nullable final String contentType) { - this.contentType = contentType; - } - @Nullable @Override public String getResponseTopic() { return responseTopic; } - public void setResponseTopic(@Nullable final String responseTopic) { - this.responseTopic = responseTopic; - } - @Nullable @Override public ByteBuffer getCorrelationData() { return correlationData; } - public void setCorrelationData(@Nullable final ByteBuffer correlationData) { - this.correlationData = correlationData; - } - @Nullable @Override public Mqtt5UserProperties getUserProperties() { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java index 2b8808553..bd0a00e3b 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java @@ -22,6 +22,7 @@ import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; import com.hivemq.cli.converters.MqttQosConverter; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; @@ -31,7 +32,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; import picocli.CommandLine; import javax.inject.Inject; @@ -48,7 +48,6 @@ public class ContextSubscribeCommand extends ShellContextCommand implements Runnable, Subscribe, Unsubscribe { public static final int IDLE_TIME = 1000; - private final DefaultCLIProperties defaultCLIProperties; //needed for pico cli - reflection code generation @@ -63,24 +62,20 @@ public ContextSubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecu this.defaultCLIProperties = defaultCLIProperties; } - @CommandLine.Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message") boolean usageHelpRequested; @CommandLine.Option(names = {"-t", "--topic"}, required = true, description = "The topics to subscribe to") - @NotNull - private String[] topics; + @NotNull private String[] topics; @CommandLine.Option(names = {"-q", "--qos"}, converter = MqttQosConverter.class, defaultValue = "2", description = "Quality of service for the corresponding topics (default for all: 2)") - @NotNull - private MqttQos[] qos; + @NotNull private MqttQos[] qos; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property of the subscribe message") @Nullable Mqtt5UserProperty[] userProperties; @CommandLine.Option(names = {"-of", "--outputToFile"}, description = "A file to which the received publish messages will be written") - @Nullable - private File publishFile; + @Nullable private File publishFile; @CommandLine.Option(names = {"-oc", "--outputToConsole"}, defaultValue = "false", description = "The received messages will be written to the console (default: false)") private boolean printToSTDOUT; @@ -93,8 +88,7 @@ public ContextSubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecu @Override public void run() { - - + //TODO if (isVerbose()) { Logger.trace("Command: {} ", this); } @@ -107,20 +101,12 @@ public void run() { printToSTDOUT = true; } - try { qos = MqttUtils.arrangeQosToMatchTopics(topics, qos); mqttClientExecutor.subscribe(contextClient, this); } catch (final Exception ex) { - LoggingContext.put("identifier", "SUBSCRIBE"); - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logWithCurrentContext(this, ex); } if (stay) { @@ -128,13 +114,7 @@ else if (isDebug()) { stay(); } catch (final InterruptedException ex) { - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logWithCurrentContext(this, ex); } } } @@ -174,7 +154,7 @@ public void run() { WORKER_THREADS.shutdownNow(); if (!contextClient.getState().isConnectedOrReconnect()) { - Logger.info("Client disconnected."); + Logger.info("{} : Client disconnected", LoggerUtils.getShellContextClientPrefix()); removeContext(); } else { @@ -220,44 +200,24 @@ public String[] getTopics() { return topics; } - public void setTopics(final String[] topics) { - this.topics = topics; - } - @NotNull public MqttQos[] getQos() { return qos; } - public void setQos(final MqttQos[] qos) { - this.qos = qos; - } - @Nullable public File getPublishFile() { return publishFile; } - public void setPublishFile(@Nullable final File publishFile) { - this.publishFile = publishFile; - } - public boolean isPrintToSTDOUT() { return printToSTDOUT; } - public void setPrintToSTDOUT(final boolean printToSTDOUT) { - this.printToSTDOUT = printToSTDOUT; - } - public boolean isBase64() { return base64; } - public void setBase64(final boolean base64) { - this.base64 = base64; - } - @Override @Nullable public Mqtt5UserProperties getUserProperties() { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java index 075c9e015..334bd0575 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java @@ -18,6 +18,7 @@ import com.hivemq.cli.commands.Context; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClient; import org.jetbrains.annotations.NotNull; @@ -70,17 +71,12 @@ public void run() { extractKeyFromContextName(contextName); } catch (final IllegalArgumentException ex) { - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + Logger.error(ex.getMessage()); return; } } + //TODO if (isVerbose()) { Logger.trace("Command: {} ", this); } @@ -90,9 +86,6 @@ else if (isDebug()) { if (client != null) { updateContext(client); } else { - if (isVerbose()) { - Logger.trace("Client with key: {} not in Cache", getKey()); - } Logger.error("Context {}@{} not found", identifier, host); } } @@ -131,10 +124,6 @@ public String getHost() { return host; } - public void setHost(final String host) { - this.host = host; - } - @Override @NotNull public String getIdentifier() { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java index 74e2b6f4b..df06099eb 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java @@ -19,6 +19,7 @@ import com.hivemq.cli.commands.Unsubscribe; import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; @@ -52,32 +53,26 @@ public ContextUnsubscribeCommand(@NotNull MqttClientExecutor mqttClientExecutor) boolean usageHelpRequested; @CommandLine.Option(names = {"-t", "--topic"}, required = true, description = "The topics to publish to") - @NotNull - private String[] topics; + @NotNull private String[] topics; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property for the unsubscribe message") @Nullable private Mqtt5UserProperty[] userProperties; - @Override public void run() { + //TODO if (isVerbose()) { Logger.trace("Command {} ", this); } + logUnusedUnsubscribeOptions(); + try { mqttClientExecutor.unsubscribe(contextClient, this); } catch (final Exception ex) { - LoggingContext.put("identifier", "UNSUBSCRIBE"); - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logWithCurrentContext(this, ex); } } @@ -104,10 +99,6 @@ public String[] getTopics() { return topics; } - public void setTopics(final String[] topics) { - this.topics = topics; - } - @Override @Nullable public Mqtt5UserProperties getUserProperties() { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java index d5c88e629..8a30618c8 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java @@ -66,12 +66,10 @@ public ListClientsCommand() { @CommandLine.Option(names = {"-s", "--subscriptions"}, defaultValue = "false", description = "list subscribed topics of clients") private boolean listSubscriptions; - - - @Override public void run() { + //TODO if (isVerbose()) { Logger.trace("Command: {}", this); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index 32abdf0e3..03ad42f9c 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -115,7 +115,7 @@ public void run() { final File dirFile = new File(dir); dirFile.mkdirs(); - final String logfileFormatPattern = "{date:yyyy-MM-dd HH:mm:ss}: {{level}:|min-size=6} {context:identifier}: {message}"; + final String logfileFormatPattern = "{date: HH:mm:ss} {{level}|min-size=7} {method} {line} : {message}"; final RollingFileWriter logfileWriter = new RollingFileWriter(dir + "hmq-cli.log", 30, false, new TimestampLabeler("yyyy-MM-dd"), new SizePolicy(1024 * 10)); @@ -128,15 +128,8 @@ public void run() { "{message}") .activate(); - LoggingContext.put("identifier", "SHELL"); - logfilePath = logfileWriter.getFilename(); - if (VERBOSE) { - Logger.trace("Command: {} ", this); - } - - interact(); } @@ -192,23 +185,8 @@ private void interact() { Logger.trace("User interrupted shell: {}", e); } return; - } catch (final EndOfFileException e) { - if (VERBOSE) { - Logger.trace(e); - } - else if (DEBUG) { - Logger.debug(e.getMessage()); - } - Logger.error(MqttUtils.getRootCause(e).getMessage()); - return; - } catch (final Exception all) { - if (DEBUG) { - Logger.trace(all); - } - else if (VERBOSE) { - Logger.debug(all.getMessage()); - } - Logger.error(MqttUtils.getRootCause(all).getMessage()); + } catch (final Exception ex) { + logOnRightLevels(ex); } } } catch (final Throwable t) { @@ -252,6 +230,15 @@ static void readFromShell() { .toAnsi(); } + private static void logOnRightLevels(final @NotNull Exception ex) { + if (VERBOSE) { + Logger.trace(ex); + } + else if (DEBUG) { + Logger.debug(ex.getMessage()); + } + Logger.error(MqttUtils.getRootCause(ex).getMessage()); + } static void usage(Object command) { currentCommandLine.usage(command, System.out); diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java index 345ec9fb0..96017f576 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java @@ -21,6 +21,7 @@ import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; import com.hivemq.cli.converters.UnsignedIntConverter; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.MqttClientSslConfig; @@ -43,9 +44,7 @@ public class ShellConnectCommand extends AbstractCommonFlags implements Runnable, Connect { private final MqttClientExecutor mqttClientExecutor; - - @Nullable - private MqttClientSslConfig sslConfig; + @Nullable private MqttClientSslConfig sslConfig; //needed for pico cli - reflection code generation public ShellConnectCommand() { @@ -54,7 +53,6 @@ public ShellConnectCommand() { @Inject public ShellConnectCommand(@NotNull final MqttClientExecutor mqttClientExecutor) { - this.mqttClientExecutor = mqttClientExecutor; } @@ -62,47 +60,31 @@ public ShellConnectCommand(@NotNull final MqttClientExecutor mqttClientExecutor) boolean usageHelpRequested; @CommandLine.Option(names = {"-se", "--sessionExpiryInterval"}, converter = UnsignedIntConverter.class, description = "The lifetime of the session of the connected client'") - @Nullable - private Long sessionExpiryInterval; + @Nullable private Long sessionExpiryInterval; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property of the connect message") - @Nullable - private Mqtt5UserProperty[] connectUserProperties; - + @Nullable private Mqtt5UserProperty[] connectUserProperties; public void run() { - setDefaultOptions(); - sslConfig = buildSslConfig(); - logUnusedOptions(); - final MqttClient client = connect(); - sslConfig = null; - ShellContextCommand.updateContext(client); } private @Nullable MqttClient connect() { + //TODO if (isVerbose()) { Logger.trace("Command: {} ", this); } try { - MqttClient client = mqttClientExecutor.connect(this); - return client; + return mqttClientExecutor.connect(this); } catch (final Exception ex) { - LoggingContext.put("identifier", "CONNECT"); - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logOnRightLevels(this, ex); } return null; } @@ -149,26 +131,15 @@ public Long getSessionExpiryInterval() { return sessionExpiryInterval; } - public void setSessionExpiryInterval(@Nullable final Long sessionExpiryInterval) { - this.sessionExpiryInterval = sessionExpiryInterval; - } - @Nullable public Mqtt5UserProperties getConnectUserProperties() { return MqttUtils.convertToMqtt5UserProperties(connectUserProperties); } - public void setConnectUserProperties(@Nullable final Mqtt5UserProperty... connectUserProperties) { - this.connectUserProperties = connectUserProperties; - } - @Nullable @Override public MqttClientSslConfig getSslConfig() { return sslConfig; } - public void setSslConfig(final MqttClientSslConfig sslConfig) { - this.sslConfig = sslConfig; - } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java index 0360691f8..f4a4f21dc 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java @@ -53,22 +53,14 @@ public ShellContextCommand(final @NotNull MqttClientExecutor mqttClientExecutor) this.mqttClientExecutor = mqttClientExecutor; } - public static void updateContext(final @Nullable MqttClient client) { + static void updateContext(final @Nullable MqttClient client) { if (client != null && client.getConfig().getState().isConnectedOrReconnect()) { - if (ShellCommand.isVerbose()) { - Logger.trace("Update context to {}@{}", client.getConfig().getClientIdentifier().get(), client.getConfig().getServerHost()); - } - LoggingContext.put("identifier", "CLIENT " + client.getConfig().getClientIdentifier().get()); contextClient = client; ShellCommand.readFromContext(); } } public static void removeContext() { - if (ShellCommand.isVerbose()) { - Logger.trace("Remove context"); - } - LoggingContext.put("identifier", "SHELL"); contextClient = null; ShellCommand.readFromShell(); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java index 5defd3832..f85cf957b 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java @@ -23,6 +23,7 @@ import com.hivemq.cli.converters.UnsignedIntConverter; import com.hivemq.cli.impl.MqttAction; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; @@ -64,24 +65,19 @@ public ShellDisconnectCommand() { private boolean disconnectAll; @CommandLine.Option(names = {"-i", "--identifier"}, description = "The client identifier UTF-8 String (default randomly generated string)") - @Nullable - private String identifier; + @Nullable private String identifier; @CommandLine.Option(names = {"-h", "--host"}, description = "The hostname of the message broker (default 'localhost')") - @Nullable - private String host; + @Nullable private String host; @CommandLine.Option(names = {"-e", "--sessionExpiryInterval"}, converter = UnsignedIntConverter.class, description = "The session expiry of the disconnect (default: 0)") - @Nullable - private Long sessionExpiryInterval; + @Nullable private Long sessionExpiryInterval; @CommandLine.Option(names = {"-r", "--reason"}, description = "The reason of the disconnect") - @Nullable - private String reasonString; + @Nullable private String reasonString; @CommandLine.Option(names = {"-up", "--userProperty"}, converter = Mqtt5UserPropertyConverter.class, description = "A user property of the disconnect message") - @Nullable - private Mqtt5UserProperty[] userProperties; + @Nullable private Mqtt5UserProperty[] userProperties; @Override public void run() { @@ -90,6 +86,7 @@ public void run() { host = defaultCLIProperties.getHost(); } + //TODO if (isVerbose()) { Logger.trace("Command: {} ", this); } @@ -108,14 +105,7 @@ public void run() { } } catch (final Exception ex) { - LoggingContext.put("identifier", "DISCONNECT"); - if (isVerbose()) { - Logger.trace(ex); - } - else if (isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); + LoggerUtils.logOnRightLevels(this, ex); } } @@ -158,23 +148,6 @@ public String getHost() { return MqttUtils.convertToMqtt5UserProperties(userProperties); } - public void setSessionExpiryInterval(final @Nullable Long sessionExpiryInterval) { - this.sessionExpiryInterval = sessionExpiryInterval; - } - - public void setReasonString(final @Nullable String reasonString) { - this.reasonString = reasonString; - } - - public void setIdentifier(@NotNull final String identifier) { - this.identifier = identifier; - } - - - public void setHost(@NotNull final String host) { - this.host = host; - } - public void setUserProperties(final @Nullable Mqtt5UserProperty... userProperties) { this.userProperties = userProperties; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java index 57faaf5bd..263bcada3 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java @@ -36,10 +36,6 @@ public ShellExitCommand() { @Override public void run() { - if (isVerbose()) { - Logger.trace("Command: {} ", this); - } - ShellCommand.exitShell(); } diff --git a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java index ba3377db2..6eee2b7f9 100644 --- a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java @@ -89,8 +89,6 @@ public MqttClient subscribe(final @NotNull SubscribeCommand subscribeCommand) { } public void subscribe(final @NotNull MqttClient client, final @NotNull Subscribe subscribe) { - LoggingContext.put("identifier", "CLIENT " + client.getConfig().getClientIdentifier().get()); - for (int i = 0; i < subscribe.getTopics().length; i++) { final String topic = subscribe.getTopics()[i]; @@ -117,8 +115,6 @@ public void publish(final @NotNull PublishCommand publishCommand) { } public void publish(final @NotNull MqttClient client, final @NotNull Publish publish) { - LoggingContext.put("identifier", "CLIENT " + client.getConfig().getClientIdentifier().get()); - for (int i = 0; i < publish.getTopics().length; i++) { final String topic = publish.getTopics()[i]; int qosI = i < publish.getQos().length ? i: publish.getQos().length-1; @@ -137,9 +133,6 @@ public void publish(final @NotNull MqttClient client, final @NotNull Publish pub } public void disconnect(final @NotNull Disconnect disconnect) { - - LoggingContext.put("identifier", "CLIENT " + disconnect.getIdentifier()); - final String clientKey = disconnect.getKey(); if (clientKeyToClientData.containsKey(clientKey)) { @@ -163,12 +156,8 @@ else if (disconnect.isDebug()) { } public void disconnectAllClients(final @NotNull Disconnect disconnect) { - - final String context = LoggingContext.get("identifier"); - for (Map.Entry entry: clientKeyToClientData.entrySet()) { final MqttClient client = entry.getValue().getClient(); - LoggingContext.put("identifier", "CLIENT " + client.getConfig().getClientIdentifier().get()); switch (client.getConfig().getMqttVersion()) { case MQTT_5_0: mqtt5Disconnect((Mqtt5Client) client, disconnect); @@ -178,16 +167,10 @@ public void disconnectAllClients(final @NotNull Disconnect disconnect) { break; } } - clientKeyToClientData.clear(); - - LoggingContext.put("identifier", context); } public void unsubscribe(final @NotNull MqttClient client, final @NotNull Unsubscribe unsubscribe) { - - LoggingContext.put("identifier", "CLIENT " + unsubscribe.getIdentifier()); - switch (client.getConfig().getMqttVersion()) { case MQTT_5_0: mqtt5Unsubscribe((Mqtt5Client) client, unsubscribe); @@ -201,7 +184,6 @@ public void unsubscribe(final @NotNull MqttClient client, final @NotNull Unsubsc public boolean isConnected(final @NotNull Context context) { - if (clientKeyToClientData.containsKey(context.getKey())) { final MqttClient client = clientKeyToClientData.get(context.getKey()).getClient(); final MqttClientState state = client.getState(); @@ -212,9 +194,6 @@ public boolean isConnected(final @NotNull Context context) { public @NotNull MqttClient connect(final @NotNull Connect connect) { - - LoggingContext.put("identifier", "CLIENT " + connect.getIdentifier()); - if (isConnected(connect)) { if (connect.isVerbose()) { Logger.trace("Client is already connected ({})", connect.getKey()); diff --git a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java index fd7b781ae..d1b0795f1 100644 --- a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java +++ b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java @@ -18,6 +18,7 @@ import com.hivemq.cli.commands.shell.ShellCommand; import com.hivemq.cli.commands.shell.ShellContextCommand; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClientConfig; import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedContext; @@ -32,18 +33,15 @@ public class ContextClientDisconnectListener implements MqttClientDisconnectedLi @Override public void onDisconnected(final @NotNull MqttClientDisconnectedContext context) { - final String contextBefore = LoggingContext.get("identifier"); - - LoggingContext.put("identifier", "CLIENT " + context.getClientConfig().getClientIdentifier().orElse(null)); - if (context.getSource() != MqttDisconnectSource.USER) { final Throwable cause = context.getCause(); if (ShellCommand.VERBOSE) { - Logger.trace(cause); + Logger.trace("{} {}", LoggerUtils.getClientPrefix(context.getClientConfig()), cause); } else if (ShellCommand.DEBUG) { - Logger.debug(cause.getMessage()); + Logger.debug("{} {}", LoggerUtils.getClientPrefix(context.getClientConfig()), + cause.getMessage()); } // If the currently active shell client gets disconnected from the server prompt the user to enter @@ -60,9 +58,9 @@ else if (contextEqualsShellContext(context)){ MqttClientExecutor.getClientDataMap().remove(getKeyFromConfig(context.getClientConfig())); - LoggingContext.put("identifier", contextBefore); } + private String getKeyFromConfig(final @NotNull MqttClientConfig clientConfig) { return MqttUtils.buildKey(clientConfig.getClientIdentifier().get().toString(), clientConfig.getServerHost()); } diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index e055e196c..9f5237ba7 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -17,13 +17,11 @@ package com.hivemq.cli.mqtt; import com.hivemq.cli.commands.*; -import com.hivemq.cli.commands.cli.PublishCommand; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; import com.hivemq.client.mqtt.datatypes.MqttTopicFilter; -import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient; -import com.hivemq.client.mqtt.mqtt3.Mqtt3BlockingClient; import com.hivemq.client.mqtt.mqtt3.Mqtt3Client; import com.hivemq.client.mqtt.mqtt3.message.connect.Mqtt3Connect; import com.hivemq.client.mqtt.mqtt3.message.connect.connack.Mqtt3ConnAck; @@ -33,14 +31,9 @@ import com.hivemq.client.mqtt.mqtt3.message.subscribe.Mqtt3Subscribe; import com.hivemq.client.mqtt.mqtt3.message.subscribe.Mqtt3SubscribeBuilder; import com.hivemq.client.mqtt.mqtt3.message.unsubscribe.Mqtt3Unsubscribe; -import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient; -import com.hivemq.client.mqtt.mqtt5.Mqtt5BlockingClient; import com.hivemq.client.mqtt.mqtt5.Mqtt5Client; -import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5MessageException; -import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5PubAckException; import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect; import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck; - import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5Disconnect; import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5DisconnectBuilder; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish; @@ -58,7 +51,6 @@ import javax.inject.Singleton; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.concurrent.CompletableFuture; import org.bouncycastle.util.encoders.Base64; @@ -71,11 +63,15 @@ public class MqttClientExecutor extends AbstractMqttClientExecutor { void mqtt5Connect(final @NotNull Mqtt5Client client, final @NotNull Mqtt5Connect connectMessage, final @NotNull Connect connect) { + String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); + if (connect.isVerbose()) { - Logger.trace("sending CONNECT with Mqtt5Connect: {}", connectMessage); + Logger.trace("{} sending CONNECT with Mqtt5Connect: {}", + clientLogPrefix, + connectMessage); } else if (connect.isDebug()) { - Logger.debug("sending CONNECT"); + Logger.debug("{} sending CONNECT", clientLogPrefix); } final Mqtt5ConnAck connAck = client @@ -83,22 +79,26 @@ else if (connect.isDebug()) { .connect(connectMessage); if (connect.isVerbose()) { - Logger.trace("received CONNACK: {} ", connAck); - Logger.trace("now in State: {}", client.getConfig().getState()); + Logger.trace("{} received CONNACK: {} ", clientLogPrefix, connAck); } else if (connect.isDebug()) { - Logger.debug("received CONNACK {}", connAck.getReasonCode()); + Logger.debug("{} received CONNACK {}", clientLogPrefix, + connAck.getReasonCode()); } } void mqtt3Connect(final @NotNull Mqtt3Client client, final @NotNull Mqtt3Connect connectMessage, final @NotNull Connect connect) { + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); + if (connect.isVerbose()) { - Logger.trace("sending CONNECT with Mqtt3Connect: {}", connectMessage); + Logger.trace("{} sending CONNECT with Mqtt3Connect: {}", + clientLogPrefix, + connectMessage); } else if (connect.isDebug()) { - Logger.debug("sending CONNECT"); + Logger.debug("{} sending CONNECT", clientLogPrefix); } final Mqtt3ConnAck connAck = client @@ -106,17 +106,19 @@ else if (connect.isDebug()) { .connect(connectMessage); if (connect.isVerbose()) { - Logger.trace("received CONNACK: {} ", connAck); - Logger.trace("now in State: {}", client.getConfig().getState()); + Logger.trace("{} received CONNACK {} ", clientLogPrefix, connAck); } else if (connect.isDebug()) { - Logger.debug("received CONNACK {}", connAck.getReturnCode()); + Logger.debug("{} received CONNACK {}", clientLogPrefix, + connAck.getReturnCode()); } } void mqtt5Subscribe(final @NotNull Mqtt5Client client, final @NotNull Subscribe subscribe, final @NotNull String topic, final @NotNull MqttQos qos) { + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); + final Mqtt5SubscribeBuilder.Start.Complete builder = Mqtt5Subscribe.builder() .topicFilter(topic) .qos(qos); @@ -129,10 +131,15 @@ void mqtt5Subscribe(final @NotNull Mqtt5Client client, final @NotNull Subscribe final Mqtt5Subscribe subscribeMessage = builder.build(); if (subscribe.isVerbose()) { - Logger.trace("sending SUBSCRIBE with Mqtt5Subscribe: {}", subscribeMessage); + Logger.trace("{} sending SUBSCRIBE with Mqtt5Subscribe {}", + clientLogPrefix, + subscribeMessage); } else if (subscribe.isDebug()) { - Logger.debug("sending SUBSCRIBE: (Topic: {}, QoS: '{}')", topic, qos); + Logger.debug("{} sending SUBSCRIBE: (Topic: {}, QoS: '{}')", + clientLogPrefix, + topic, + qos); } @@ -142,13 +149,22 @@ else if (subscribe.isDebug()) { if (throwable != null) { if (subscribe.isVerbose()) { - Logger.trace("SUBSCRIBE to TOPIC '{}' failed: {}", topic, throwable); + Logger.trace("{} failed SUBSCRIBE to TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable); } else if (subscribe.isDebug()) { - Logger.debug("SUBSCRIBE to TOPIC '{}' failed: {} ", topic, throwable.getMessage()); + Logger.debug("{} failed SUBSCRIBE to TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable.getMessage()); } - Logger.error("SUBSCRIBE to TOPIC '{}' failed with '{}'", topic, MqttUtils.getRootCause(throwable).getMessage()); + Logger.error("{} failed SUBSCRIBE to TOPIC '{}': {}", + clientLogPrefix, + topic, + MqttUtils.getRootCause(throwable).getMessage()); } else { final String clientKey = MqttUtils.buildKey(client.getConfig().getClientIdentifier().get().toString(), @@ -157,10 +173,14 @@ else if (subscribe.isDebug()) { getClientDataMap().get(clientKey).addSubscription(MqttTopicFilter.of(topic)); if (subscribe.isVerbose()) { - Logger.trace("received SUBACK: {}", subAck); + Logger.trace("{} received SUBACK {}", + clientLogPrefix, + subAck); } else if (subscribe.isDebug()) { - Logger.debug("received SUBACK: {}", subAck.getReasonCodes()); + Logger.debug("{} received SUBACK: {}", + clientLogPrefix, + subAck.getReasonCodes()); } } @@ -172,6 +192,8 @@ else if (subscribe.isDebug()) { void mqtt3Subscribe(final @NotNull Mqtt3Client client, final @NotNull Subscribe subscribe, final @NotNull String topic, final @NotNull MqttQos qos) { + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); + final Mqtt3SubscribeBuilder.Start.Complete builder = Mqtt3Subscribe.builder() .topicFilter(topic) .qos(qos); @@ -180,10 +202,10 @@ void mqtt3Subscribe(final @NotNull Mqtt3Client client, final @NotNull Subscribe final Mqtt3Subscribe subscribeMessage = builder.build(); if (subscribe.isVerbose()) { - Logger.trace("sending SUBSCRIBE with Mqtt3Subscribe: {}", subscribeMessage); + Logger.trace("{} sending SUBSCRIBE with Mqtt3Subscribe: {}", clientLogPrefix, subscribeMessage); } else if (subscribe.isDebug()) { - Logger.debug("sending SUBSCRIBE: (Topic: {}, QoS: '{}')", topic, qos); + Logger.debug("{} sending SUBSCRIBE: (Topic: {}, QoS: '{}')", clientLogPrefix, topic, qos); } @@ -193,13 +215,22 @@ else if (subscribe.isDebug()) { if (throwable != null) { if (subscribe.isVerbose()) { - Logger.trace("SUBSCRIBE to TOPIC '{}' failed: {}", topic, throwable); + Logger.trace("{} failed SUBSCRIBE to TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable); } else if (subscribe.isDebug()) { - Logger.debug("SUBSCRIBE to TOPIC '{}' failed: {} ", topic, throwable.getMessage()); + Logger.debug("{} failed SUBSCRIBE to TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable.getMessage()); } - Logger.error("SUBSCRIBE to TOPIC '{}' failed with '{}'", topic, MqttUtils.getRootCause(throwable).getMessage()); + Logger.error("{} failed SUBSCRIBE to TOPIC '{}': {}", + clientLogPrefix, + topic, + MqttUtils.getRootCause(throwable).getMessage()); } else { final String clientKey = MqttUtils.buildKey(client.getConfig().getClientIdentifier().get().toString(), @@ -208,10 +239,10 @@ else if (subscribe.isDebug()) { getClientDataMap().get(clientKey).addSubscription(MqttTopicFilter.of(topic)); if (subscribe.isVerbose()) { - Logger.trace("received SUBACK: {}", subAck); + Logger.trace("{} received SUBACK: {}", clientLogPrefix, subAck); } else if (subscribe.isDebug()) { - Logger.debug("received SUBACK: {}", subAck.getReturnCodes()); + Logger.debug("{} received SUBACK: {}", clientLogPrefix, subAck.getReturnCodes()); } } @@ -221,6 +252,8 @@ else if (subscribe.isDebug()) { void mqtt5Publish(final @NotNull Mqtt5Client client, final @NotNull Publish publish, final @NotNull String topic, final @NotNull MqttQos qos) { + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); + final Mqtt5PublishBuilder.Complete publishBuilder = Mqtt5Publish.builder() .topic(topic) .qos(qos) @@ -243,10 +276,14 @@ void mqtt5Publish(final @NotNull Mqtt5Client client, final @NotNull Publish publ final Mqtt5Publish publishMessage = publishBuilder.build(); if (publish.isVerbose()) { - Logger.trace("sending PUBLISH with Mqtt5Publish: {}", publishMessage); + Logger.trace("{} sending PUBLISH with Mqtt5Publish: {}", clientLogPrefix, publishMessage); } else if (publish.isDebug()) { - Logger.debug("sending PUBLISH: (Topic: '{}', QoS: '{}', Message: '{}')", topic, qos, bufferToString(publish.getMessage())); + Logger.debug("{} sending PUBLISH: (Topic: '{}', QoS: '{}', Message: '{}')", + clientLogPrefix, + topic, + qos, + bufferToString(publish.getMessage())); } @@ -254,32 +291,36 @@ else if (publish.isDebug()) { .publish(publishMessage) .whenComplete((publishResult, throwable) -> { if (throwable != null) { - - if (publish.isVerbose()) { - Logger.trace("PUBLISH to TOPIC '{}' failed: {}", topic, throwable); - } - else if (publish.isDebug()) { - Logger.debug("PUBLISH to TOPIC '{}' failed: {} ", topic, throwable.getMessage()); - } - Logger.error("PUBLISH to TOPIC '{}' failed with '{}'", topic, MqttUtils.getRootCause(throwable).getMessage()); - + //TODO } else { if (publish.isVerbose()) { - Logger.trace("acknowledged PUBLISH: '{}' for PUBLISH to TOPIC: '{}'", publishResult, topic); + Logger.trace("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + publishResult); } else if (publish.isDebug()) { TypeSwitch.when(publishResult) .is(Mqtt5PublishResult.Mqtt5Qos1Result.class, qos1Result -> { - Logger.debug("received PUBACK: '{}' for PUBLISH to TOPIC: '{}'", qos1Result.getPubAck(), topic); + Logger.debug("{} received PUBACK for PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + qos1Result.getPubAck()); }) .is(Mqtt5PublishResult.Mqtt5Qos2Result.class, qos2Result -> { - Logger.debug("received PUBREC: '{}' for PUBLISH to TOPIC: '{}'", qos2Result.getPubRec(), topic); + Logger.debug("{} received PUBREC for PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + qos2Result.getPubRec(), + topic); }) .is(Mqtt5PublishResult.Mqtt5Qos2CompleteResult.class, qos2CompleteResult -> { - Logger.debug("received PUBCOMP: '{}' for PUBLISH to TOPIC: '{}'", qos2CompleteResult.getPubComp(), topic); + Logger.debug("{} received PUBCOMP for PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + qos2CompleteResult.getPubComp()); }); } } @@ -290,6 +331,7 @@ else if (publish.isDebug()) { void mqtt3Publish(final @NotNull Mqtt3Client client, final @NotNull Publish publish, final @NotNull String topic, final @NotNull MqttQos qos) { + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); final Mqtt3PublishBuilder.Complete publishBuilder = Mqtt3Publish.builder() .topic(topic) @@ -303,10 +345,14 @@ void mqtt3Publish(final @NotNull Mqtt3Client client, final @NotNull Publish publ final Mqtt3Publish publishMessage = publishBuilder.build(); if (publish.isVerbose()) { - Logger.trace("sending PUBLISH with Mqtt3Publish: {}", publishMessage); + Logger.trace("{} sending PUBLISH with Mqtt3Publish: {}", clientLogPrefix, publishMessage); } else if (publish.isDebug()) { - Logger.debug("sending PUBLISH: (TOPIC: '{}', QoS: '{}', Message: '{}')", topic, qos, bufferToString(publish.getMessage())); + Logger.debug("{} sending PUBLISH: (TOPIC: '{}', QoS: '{}', Message: '{}')", + clientLogPrefix, + topic, + qos, + bufferToString(publish.getMessage())); } client.toAsync().publish(publishMessage) @@ -314,24 +360,40 @@ else if (publish.isDebug()) { if (throwable != null) { if (publish.isVerbose()) { - Logger.trace("PUBLISH to TOPIC '{}' failed: {}", topic, throwable); + Logger.trace("{} PUBLISH to TOPIC '{}' failed: {}", + clientLogPrefix, + topic, + throwable); } else if (publish.isDebug()) { - Logger.debug("PUBLISH to TOPIC '{}' failed: {} ", topic, throwable.getMessage()); + Logger.debug("{} PUBLISH to TOPIC '{}' failed: {} ", + clientLogPrefix, + topic, + throwable.getMessage()); } - Logger.error("PUBLISH to TOPIC '{}' failed with '{}'", topic, MqttUtils.getRootCause(throwable).getMessage()); + Logger.error("{} PUBLISH to TOPIC '{}' failed with '{}'", + clientLogPrefix, + topic, + MqttUtils.getRootCause(throwable).getMessage()); } else { if (publish.isVerbose()) { - Logger.trace("acknowledged PUBLISH: '{}' for PUBLISH to TOPIC: '{}'", publishResult, topic); + Logger.trace("{} PUBLISH acknowledged '{}' for PUBLISH to TOPIC: '{}'", + clientLogPrefix, + publishResult, + topic); } else if (publish.isDebug()) { if (publishResult.getQos().equals(MqttQos.AT_LEAST_ONCE)) { - Logger.debug("received PUBACK for PUBLISH to TOPIC: '{}'", topic); + Logger.debug("{} received PUBACK for PUBLISH to TOPIC: '{}'", + clientLogPrefix, + topic); } else if (publishResult.getQos().equals(MqttQos.EXACTLY_ONCE)) { - Logger.debug("received PUBREC for PUBLISH to TOPIC: '{}'", topic); + Logger.debug("{} received PUBREC for PUBLISH to TOPIC: '{}'", + clientLogPrefix, + topic); } } } @@ -341,8 +403,7 @@ else if (publishResult.getQos().equals(MqttQos.EXACTLY_ONCE)) { @Override void mqtt5Unsubscribe(@NotNull final Mqtt5Client client, @NotNull final Unsubscribe unsubscribe) { - - + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); for (String topic : unsubscribe.getTopics()) { @@ -351,10 +412,15 @@ void mqtt5Unsubscribe(@NotNull final Mqtt5Client client, @NotNull final Unsubscr .build(); if (unsubscribe.isVerbose()) { - Logger.trace("Sending UNSUBSCRIBE with Mqtt5Unsubscribe: {}", unsubscribeMessage); + Logger.trace("{} sending UNSUBSCRIBE with Mqtt5Unsubscribe: {}", + clientLogPrefix, + unsubscribeMessage); } else if (unsubscribe.isDebug()) { - Logger.debug("sending UNSUBSCRIBE: (TOPIC: '{}', userProperties: {})", topic, unsubscribe.getUserProperties()); + Logger.debug("{} sending UNSUBSCRIBE: (TOPIC: '{}', userProperties: {})", + clientLogPrefix, + topic, + unsubscribe.getUserProperties()); } client.toAsync() @@ -365,21 +431,34 @@ else if (unsubscribe.isDebug()) { if (unsubscribe.isVerbose()) { - Logger.trace("UNSUBSCRIBE of TOPIC '{}' failed: {}", topic, throwable); + Logger.trace("{} failed UNSUBSCRIBE from TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable); } else if (unsubscribe.isDebug()) { - Logger.debug("UNSUBSCRIBE of TOPIC '{}' failed: {}", topic, throwable.getMessage()); + Logger.debug("{} failed UNSUBSCRIBE from TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable.getMessage()); } - Logger.error("UNSUBSCRIBE to {} failed with ()", topic, MqttUtils.getRootCause(throwable).getMessage()); + Logger.error("{} failed UNSUBSCRIBE from TOPIC '{}': {}", + clientLogPrefix, + topic, + MqttUtils.getRootCause(throwable).getMessage()); } else { getClientDataMap().get(unsubscribe.getKey()).removeSubscription(MqttTopicFilter.of(topic)); if (unsubscribe.isVerbose()) { - Logger.trace("received UNSUBACK: {}", unsubAck); + Logger.trace("{} received UNSUBACK {}", + clientLogPrefix, + unsubAck); } else if (unsubscribe.isDebug()) { - Logger.debug("received UNSUBACK: {}", unsubAck.getReasonCodes()); + Logger.debug("{} received UNSUBACK {}", + clientLogPrefix, + unsubAck.getReasonCodes()); } } @@ -390,7 +469,7 @@ else if (unsubscribe.isDebug()) { @Override void mqtt3Unsubscribe(@NotNull final Mqtt3Client client, @NotNull final Unsubscribe unsubscribe) { - + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); for (String topic : unsubscribe.getTopics()) { @@ -399,10 +478,15 @@ void mqtt3Unsubscribe(@NotNull final Mqtt3Client client, @NotNull final Unsubscr .build(); if (unsubscribe.isVerbose()) { - Logger.trace("Sending UNSUBSCRIBE with Mqtt3Unsubscribe: {}", unsubscribeMessage); + Logger.trace("{} Sending UNSUBSCRIBE with Mqtt3Unsubscribe: {}", + clientLogPrefix, + unsubscribeMessage); } else if (unsubscribe.isDebug()) { - Logger.debug("Sending UNSUBSCRIBE: (TOPIC: '{}', userProperties: {})", topic, unsubscribe.getUserProperties()); + Logger.debug("{} Sending UNSUBSCRIBE: (TOPIC: '{}', userProperties: {})", + clientLogPrefix, + topic, + unsubscribe.getUserProperties()); } client.toAsync() @@ -411,22 +495,31 @@ else if (unsubscribe.isDebug()) { if (throwable != null) { if (unsubscribe.isVerbose()) { - Logger.trace("UNSUBSCRIBE of TOPIC '{}' failed: {}", topic, throwable); + Logger.trace("{} failed UNSUBSCRIBE from TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable); } else if (unsubscribe.isDebug()) { - Logger.debug("UNSUBSCRIBE of TOPIC '{}' failed: {}", topic, throwable.getMessage()); + Logger.debug("{} failed UNSUBSCRIBE from TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable.getMessage()); } - Logger.error("UNSUBSCRIBE to {} failed with ()", topic, MqttUtils.getRootCause(throwable).getMessage()); + Logger.error("{} failed UNSUBSCRIBE from TOPIC '{}': {}", + clientLogPrefix, + topic, + MqttUtils.getRootCause(throwable).getMessage()); } else { getClientDataMap().get(unsubscribe.getKey()).removeSubscription(MqttTopicFilter.of(topic)); if (unsubscribe.isVerbose()) { - Logger.trace("received UNSUBACK"); + Logger.trace("{} received UNSUBACK", clientLogPrefix ); } else if (unsubscribe.isDebug()) { - Logger.debug("received UNSUBACK"); + Logger.debug("{} received UNSUBACK", clientLogPrefix); } } @@ -437,6 +530,8 @@ else if (unsubscribe.isDebug()) { @Override void mqtt5Disconnect(@NotNull final Mqtt5Client client, @NotNull final Disconnect disconnect) { + final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); + final Mqtt5DisconnectBuilder disconnectBuilder = Mqtt5Disconnect.builder(); @@ -455,10 +550,14 @@ void mqtt5Disconnect(@NotNull final Mqtt5Client client, @NotNull final Disconnec final Mqtt5Disconnect disconnectMessage = disconnectBuilder.build(); if (disconnect.isVerbose()) { - Logger.trace("Sending DISCONNECT with Mqtt5Disconnect: {}", disconnectMessage); + Logger.trace("{} sending DISCONNECT with Mqtt5Disconnect: {}", clientLogPrefix, disconnectMessage); } else if (disconnect.isDebug()) { - Logger.debug("Sending DISCONNECT (Reason: {}, sessionExpiryInterval: {}, userProperties: {})", disconnect.getReasonString(), disconnect.getSessionExpiryInterval(), disconnect.getUserProperties()); + Logger.debug("{} sending DISCONNECT (Reason: {}, sessionExpiryInterval: {}, userProperties: {})", + clientLogPrefix, + disconnect.getReasonString(), + disconnect.getSessionExpiryInterval(), + disconnect.getUserProperties()); } client.toBlocking() @@ -483,7 +582,7 @@ void mqtt3Disconnect(@NotNull final Mqtt3Client client, @NotNull final Disconnec Logger.trace("Sending DISCONNECT with Mqtt3Disconnect: {}", Mqtt3Disconnect.class); } else if (disconnect.isDebug()) { - Logger.debug("Sending DISCONNECT"); + Logger.debug("{} Sending DISCONNECT"); } client.toBlocking() @@ -508,6 +607,13 @@ else if (disconnect.isDebug()) { } + private void logFailedPublish(final @NotNull Throwable t, + final @NotNull String topic, + final @NotNull String clientLogPrefix) { + + + } + private @NotNull String bufferToString(ByteBuffer b) { return new String(b.array(), StandardCharsets.UTF_8); } diff --git a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java new file mode 100644 index 000000000..3cbc4abd1 --- /dev/null +++ b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java @@ -0,0 +1,73 @@ +/* + * Copyright 2019 HiveMQ and the HiveMQ Community + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.hivemq.cli.utils; + +import com.hivemq.cli.commands.CliCommand; +import com.hivemq.cli.commands.shell.ShellContextCommand; +import com.hivemq.client.mqtt.MqttClientConfig; +import com.hivemq.client.mqtt.datatypes.MqttClientIdentifier; +import org.jetbrains.annotations.NotNull; +import org.pmw.tinylog.Logger; + +import java.util.Objects; +import java.util.Optional; + +public class LoggerUtils { + + public static void logOnRightLevels(final @NotNull CliCommand cmd, final @NotNull Exception ex) { + if (cmd.isVerbose()) { + Logger.trace(ex); + } + else if (cmd.isDebug()) { + Logger.debug(ex.getMessage()); + } + Logger.error(MqttUtils.getRootCause(ex).getMessage()); + } + + public static void logWithCurrentContext(final @NotNull CliCommand cmd, final @NotNull Exception ex) { + if (cmd.isVerbose()) { + Logger.trace("{} : ", getShellContextClientPrefix(), ex); + } + else if (cmd.isDebug()) { + Logger.debug("{} : ", getShellContextClientPrefix(), ex.getMessage()); + } + Logger.error(MqttUtils.getRootCause(ex).getMessage()); + } + + public static String getShellContextClientPrefix() { + if (ShellContextCommand.contextClient != null) { + final MqttClientConfig config = ShellContextCommand.contextClient.getConfig(); + return getClientPrefix(config); + } + else { + return ""; + } + } + + public static String getClientPrefix(final @NotNull MqttClientConfig config) { + Optional optId = config.getClientIdentifier(); + String id = optId.map(Objects::toString).orElse("UNKNOWN"); + if (id.isEmpty()) { + id = "UNKNOWN"; + } + return "Client '" + + id + + "@" + + config.getServerHost() + + "'"; + } +} From f1351605b99b0a53c88f4a9a67c242fe07f3800c Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Thu, 5 Dec 2019 14:17:36 +0100 Subject: [PATCH 07/20] do not log null values --- .../cli/commands/AbstractCommonFlags.java | 12 ++--- .../AbstractConnectRestrictionFlags.java | 18 +++---- .../cli/commands/AbstractWillFlags.java | 26 +++++----- .../com/hivemq/cli/commands/MqttCommand.java | 2 +- .../commands/cli/AbstractConnectFlags.java | 2 +- .../commands/shell/ClearScreenCommand.java | 2 +- .../shell/ContextDisconnectCommand.java | 10 ++-- .../commands/shell/ContextExitCommand.java | 2 +- .../commands/shell/ContextPublishCommand.java | 16 ++++--- .../shell/ContextSubscribeCommand.java | 10 ++-- .../commands/shell/ContextSwitchCommand.java | 8 ++-- .../shell/ContextUnsubscribeCommand.java | 4 +- .../commands/shell/ListClientsCommand.java | 10 ++-- .../cli/commands/shell/ShellCommand.java | 4 +- .../commands/shell/ShellConnectCommand.java | 13 ++--- .../shell/ShellDisconnectCommand.java | 14 ++++-- .../cli/commands/shell/ShellExitCommand.java | 2 +- .../hivemq/cli/mqtt/MqttClientExecutor.java | 47 ++++++++++++------- 18 files changed, 120 insertions(+), 82 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java index 229ee5cb6..74ee050f8 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java @@ -285,14 +285,14 @@ public String toString() { public String commonOptions() { return super.toString() + - ", user='" + user + '\'' + - ", keepAlive=" + keepAlive + - ", cleanStart=" + cleanStart + + (user != null ? (", user=" + user) : "") + + (keepAlive != null ? (", keepAlive=" + keepAlive) : "") + + (cleanStart != null ? (", cleanStart=" + cleanStart) : "") + ", useDefaultSsl=" + useSsl + - ", sslConfig=" + (getSslConfig() != null) + + (getSslConfig() != null ? (", sslConfig=" + getSslConfig()) : "") + ", useWebSocket=" + useWebSocket + - ", webSocketPath=" + webSocketPath + - ", " + getWillOptions(); + (webSocketPath != null ? (", webSocketPath=" + webSocketPath) : "") + + getWillOptions(); } // GETTER AND SETTER diff --git a/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java index a296b4e41..7de737446 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java @@ -22,6 +22,8 @@ import org.pmw.tinylog.Logger; import picocli.CommandLine; +import java.util.Arrays; + public abstract class AbstractConnectRestrictionFlags extends AbstractWillFlags implements ConnectRestrictions { @CommandLine.Option(names = {"--rcvMax"}, description = "The maximum amount of not acknowledged publishes with QoS 1 or 2 the client accepts from the server concurrently. (default: " + Mqtt5ConnectRestrictions.DEFAULT_RECEIVE_MAXIMUM + ")", order = 3) @@ -97,14 +99,14 @@ public void logUnusedOptions() { } public String connectRestrictionOptions() { - return "receiveMaximum=" + receiveMaximum + - ", sendMaximum=" + sendMaximum + - ", maximumPacketSize=" + maximumPacketSize + - ", sendMaximumPacketSize=" + sendMaximumPacketSize + - ", topicAliasMaximum=" + topicAliasMaximum + - ", sendTopicAliasMaximum=" + sendTopicAliasMaximum + - ", requestProblemInformation=" + requestProblemInformation + - ", requestResponseInformation=" + requestResponseInformation; + return (receiveMaximum != null ? (", receiveMaximum=" + receiveMaximum) : "") + + (sendMaximum != null ? (", sendMaximum=" + sendMaximum) : "") + + (maximumPacketSize != null ? (", maximumPacketSize=" + maximumPacketSize) : "") + + (sendMaximumPacketSize != null ? (", sendMaximumPacketSize=" + sendMaximumPacketSize) : "") + + (topicAliasMaximum != null ? (", topicAliasMaximum=" + topicAliasMaximum) : "") + + (sendTopicAliasMaximum != null ? (", sendTopicAliasMaximum=" + sendTopicAliasMaximum) : "") + + (requestProblemInformation != null ? (", requestProblemInformation=" + requestProblemInformation) : "") + + (requestResponseInformation != null ? (", requestResponseInformation=" + requestResponseInformation) : ""); } @Nullable diff --git a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java index aeeafd250..fc80f5020 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java @@ -29,6 +29,7 @@ import picocli.CommandLine; import java.nio.ByteBuffer; +import java.util.Arrays; @CommandLine.Command public abstract class AbstractWillFlags extends MqttCommand implements Will { @@ -79,17 +80,20 @@ public abstract class AbstractWillFlags extends MqttCommand implements Will { String getWillOptions() { - return "willTopic='" + willTopic + '\'' + - ", willQos=" + willQos + - ", willMessage='" + willMessage + '\'' + - ", willRetain=" + willRetain + - ", willMessageExpiryInterval=" + willMessageExpiryInterval + - ", willDelayInterval=" + willDelayInterval + - ", willPayloadFormatIndicator=" + willPayloadFormatIndicator + - ", willContentType='" + willContentType + '\'' + - ", willResponseTopic='" + willResponseTopic + '\'' + - ", willCorrelationData=" + willCorrelationData + - ", willUserProperties=" + willUserProperties; + if (willTopic == null) { + return ""; + } + return ", willTopic=" + willTopic + + (willQos != null ? (", willQos=" + willQos) : "") + + (willMessage != null ? (", willMessage=" + willMessage) : "") + + (willRetain != null ? (", willRetain=" + willRetain) : "") + + (willMessageExpiryInterval != null ? (", willMessageExpiryInterval=" + willMessageExpiryInterval) : "") + + (willDelayInterval != null ? (", willDelayInterval=" + willDelayInterval) : "") + + (willPayloadFormatIndicator != null ? (", willPayloadFormatIndicator=" + willPayloadFormatIndicator) : "") + + (willContentType != null ? (", willContentType=" + willContentType) : "") + + (willResponseTopic != null ? (", willResponseTopic=" + willResponseTopic) : "") + + (willCorrelationData != null ? (", willCorrelationData=" + willCorrelationData) : "") + + (willUserProperties != null ? (", willUserProperties=" + Arrays.toString(willUserProperties)) : ""); } public void logUnusedOptions() { diff --git a/src/main/java/com/hivemq/cli/commands/MqttCommand.java b/src/main/java/com/hivemq/cli/commands/MqttCommand.java index dbd373bab..93d0a38a5 100644 --- a/src/main/java/com/hivemq/cli/commands/MqttCommand.java +++ b/src/main/java/com/hivemq/cli/commands/MqttCommand.java @@ -129,7 +129,7 @@ public String toString() { return "host=" + host + ", port=" + port + ", version=" + version + - ", identifier=" + identifier; + (identifier != null && !identifier.isEmpty() ? (", identifier=" + identifier) : ""); } @Override diff --git a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java index b70bb9f6e..2d5e62bff 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java +++ b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java @@ -45,7 +45,7 @@ String connectOptions() { return commonOptions() + ", sessionExpiryInterval= " + sessionExpiryInterval + ", userProperties=" + (connectUserProperties == null? null : Arrays.toString(connectUserProperties)) + - ", " + connectRestrictionOptions(); + connectRestrictionOptions(); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java index 9b0e9c21a..b8f2f576e 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java @@ -49,7 +49,7 @@ public Void call() { @Override public String toString() { - return "ClearScreen::"; + return this.getClass().getSimpleName(); } @Override diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java index 49a9bd6f4..5dee13158 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java @@ -32,6 +32,7 @@ import picocli.CommandLine; import javax.inject.Inject; +import java.util.Arrays; @CommandLine.Command(name = "dis", aliases = "disconnect", @@ -67,9 +68,8 @@ public ContextDisconnectCommand(final @NotNull MqttClientExecutor executor) { @Override public void run() { - // TODO if (isVerbose()) { - Logger.trace("Command: {} ", this); + Logger.trace("Command {} ", this); } logUnusedDisconnectOptions(); @@ -106,8 +106,12 @@ private void logUnusedDisconnectOptions() { @Override public String toString() { - return "ContextDisconnect:: {" + + return getClass().getSimpleName() + "{" + "key=" + getKey() + + ", all=" + disconnectAll + + (sessionExpiryInterval != null ? (", sessionExpiryInterval=" + sessionExpiryInterval) : "") + + (reasonString != null ? (", reasonString=" + reasonString) : "") + + (userProperties != null ? (", userProperties=" + Arrays.toString(userProperties)) : "") + "}"; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java index c0cf1ecd3..ce95e0afe 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java @@ -47,7 +47,7 @@ public void run() { @Override public String toString() { - return "ContextExit::"; + return getClass().getSimpleName(); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java index d9a255854..25f3a7a01 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java @@ -34,6 +34,7 @@ import javax.inject.Inject; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -130,17 +131,18 @@ private void logUnusedOptions() { @Override public String toString() { - return "ContextPublish:: {" + + return getClass().getSimpleName() + "{" + "key=" + getKey() + ", topics=" + Arrays.toString(topics) + ", qos=" + Arrays.toString(qos) + + ", message=" + new String(message.array(), StandardCharsets.UTF_8) + ", retain=" + retain + - ", messageExpiryInterval=" + messageExpiryInterval + - ", payloadFormatIndicator=" + payloadFormatIndicator + - ", contentType=" + contentType + - ", responseTopic=" + responseTopic + - ", correlationData=" + correlationData + - ", userProperties=" + userProperties + + (messageExpiryInterval != null ? (", messageExpiryInterval=" + messageExpiryInterval) : "") + + (payloadFormatIndicator != null ? (", payloadFormatIndicator=" + payloadFormatIndicator) : "") + + (contentType != null ? (", contentType=" + contentType) : "") + + (responseTopic != null ? (", responseTopic=" + responseTopic) : "") + + (correlationData != null ? (", correlationData=" + new String(correlationData.array(), StandardCharsets.UTF_8)) : "") + + (userProperties != null ? (", userProperties=" + Arrays.toString(userProperties)) : "") + '}'; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java index bd0a00e3b..f961d5655 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java @@ -88,9 +88,9 @@ public ContextSubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecu @Override public void run() { - //TODO + if (isVerbose()) { - Logger.trace("Command: {} ", this); + Logger.trace("Command {} ", this); } setDefaultOptions(); @@ -165,14 +165,14 @@ public void run() { @Override public String toString() { - return "ContextSubscribe:: {" + + return getClass().getSimpleName() + "{" + "key=" + getKey() + ", topics=" + Arrays.toString(topics) + ", qos=" + Arrays.toString(qos) + - ", userProperties=" + userProperties + - ", toFile=" + publishFile + ", outputToConsole=" + printToSTDOUT + ", base64=" + base64 + + (userProperties != null ? (", userProperties=" + Arrays.toString(userProperties)) : "") + + (publishFile != null ? (", publishFile=" + publishFile.getAbsolutePath()) : "") + '}'; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java index 334bd0575..e918ba10d 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java @@ -78,7 +78,7 @@ public void run() { //TODO if (isVerbose()) { - Logger.trace("Command: {} ", this); + Logger.trace("Command {} ", this); } final MqttClient client = mqttClientExecutor.getMqttClient(this); @@ -113,9 +113,9 @@ public String getKey() { @Override public String toString() { - return "ContextSwitch:: {" + - "contextName='" + contextName + '\'' + - ", key=" + getKey() + + return getClass().getSimpleName() + "{" + + "identifier=" + identifier + + ", host=" + host + '}'; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java index df06099eb..86d5298e5 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java @@ -61,7 +61,7 @@ public ContextUnsubscribeCommand(@NotNull MqttClientExecutor mqttClientExecutor) @Override public void run() { - //TODO + if (isVerbose()) { Logger.trace("Command {} ", this); } @@ -89,7 +89,7 @@ public String toString() { return "ContextUnsubscribe:: {" + "key=" + getKey() + ", topics=" + Arrays.toString(topics) + - ", userProperties=" + userProperties + + (userProperties != null ? (", userProperties=" + Arrays.toString(userProperties)) : "") + '}'; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java index 8a30618c8..f5bf4ba56 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java @@ -69,9 +69,8 @@ public ListClientsCommand() { @Override public void run() { - //TODO if (isVerbose()) { - Logger.trace("Command: {}", this); + Logger.trace("Command {}", this); } final List sortedClientData = getSortedClientData(); @@ -188,9 +187,12 @@ public List getSortedClientData() { @Override public String toString() { - return "List:: {" + + return getClass().getSimpleName() + "{" + "sortByTime=" + sortByTime + - ", detailedOutput=" + longOutput + + ", doNotSort=" + doNotSort + + ", reverse=" + reverse + + ", listSubscriptions" + listSubscriptions + + ", longOutput=" + longOutput + '}'; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index 03ad42f9c..17866a992 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -115,7 +115,7 @@ public void run() { final File dirFile = new File(dir); dirFile.mkdirs(); - final String logfileFormatPattern = "{date: HH:mm:ss} {{level}|min-size=7} {method} {line} : {message}"; + final String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{class_name}|min-size=25} | {{level}|min-size=7} | {message}"; final RollingFileWriter logfileWriter = new RollingFileWriter(dir + "hmq-cli.log", 30, false, new TimestampLabeler("yyyy-MM-dd"), new SizePolicy(1024 * 10)); @@ -262,7 +262,7 @@ static boolean isDebug() { @Override public String toString() { - return "Shell:: {" + + return getClass().getSimpleName() + "{" + "logfilePath=" + logfilePath + ", debug=" + DEBUG + ", verbose=" + VERBOSE + diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java index 96017f576..023f1e040 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java @@ -35,6 +35,7 @@ import picocli.CommandLine; import javax.inject.Inject; +import java.util.Arrays; @CommandLine.Command(name = "con", aliases = "connect", @@ -75,9 +76,9 @@ public void run() { } private @Nullable MqttClient connect() { - //TODO + if (isVerbose()) { - Logger.trace("Command: {} ", this); + Logger.trace("Command {} ", this); } try { @@ -105,15 +106,15 @@ public void logUnusedOptions() { String connectOptions() { return commonOptions() + - ", sessionExpiryInterval= " + sessionExpiryInterval + - ", userProperties=" + connectUserProperties + - ", " + connectRestrictionOptions(); + (sessionExpiryInterval != null ? (", sessionExpiryInterval=" + sessionExpiryInterval) : "") + + (connectUserProperties != null ? (", userProperties=" + Arrays.toString(connectUserProperties)) : "") + + connectRestrictionOptions(); } @Override public String toString() { - return "ShellConnectCommand:: {" + connectOptions() + "}"; + return getClass().getSimpleName() + "{" + connectOptions() + "}"; } @Override diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java index f85cf957b..da75f5383 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java @@ -34,6 +34,7 @@ import picocli.CommandLine; import javax.inject.Inject; +import java.util.Arrays; @CommandLine.Command(name = "dis", aliases = "disconnect", @@ -86,9 +87,8 @@ public void run() { host = defaultCLIProperties.getHost(); } - //TODO if (isVerbose()) { - Logger.trace("Command: {} ", this); + Logger.trace("Command {} ", this); } try { @@ -125,7 +125,15 @@ public String getKey() { @Override public String toString() { - return "Disconnect::" + getKey(); + return getClass().getSimpleName() + "{" + + "disconnectAll=" + disconnectAll + + (identifier != null ? (", identifier=" + identifier) : "") + + (host != null ? (", host=" + host) : "") + + (sessionExpiryInterval != null ? (", sessionExpiryInterval=" + host) : "") + + (reasonString != null ? (", reasonString=" + reasonString) : "") + + (userProperties != null ? (", userProperties=" + Arrays.toString(userProperties)) : "") + + "}"; + } @Override diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java index 263bcada3..ca7a96c3e 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java @@ -41,7 +41,7 @@ public void run() { @Override public String toString() { - return "ShellExit::"; + return getClass().getSimpleName(); } @Override diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index 9f5237ba7..f2036d391 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -291,7 +291,22 @@ else if (publish.isDebug()) { .publish(publishMessage) .whenComplete((publishResult, throwable) -> { if (throwable != null) { - //TODO + if (publish.isVerbose()) { + Logger.trace("{} failed PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable); + } + else if (publish.isDebug()) { + Logger.debug("{} failed PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + throwable.getMessage()); + } + Logger.error("{} failed PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + MqttUtils.getRootCause(throwable).getMessage()); } else { @@ -313,8 +328,8 @@ else if (publish.isDebug()) { .is(Mqtt5PublishResult.Mqtt5Qos2Result.class, qos2Result -> { Logger.debug("{} received PUBREC for PUBLISH to TOPIC '{}': {}", clientLogPrefix, - qos2Result.getPubRec(), - topic); + topic, + qos2Result.getPubRec()); }) .is(Mqtt5PublishResult.Mqtt5Qos2CompleteResult.class, qos2CompleteResult -> { Logger.debug("{} received PUBCOMP for PUBLISH to TOPIC '{}': {}", @@ -360,18 +375,18 @@ else if (publish.isDebug()) { if (throwable != null) { if (publish.isVerbose()) { - Logger.trace("{} PUBLISH to TOPIC '{}' failed: {}", + Logger.trace("{} failed PUBLISH to TOPIC '{}': {}", clientLogPrefix, topic, throwable); } else if (publish.isDebug()) { - Logger.debug("{} PUBLISH to TOPIC '{}' failed: {} ", + Logger.debug("{} failed PUBLISH to TOPIC '{}': {}", clientLogPrefix, topic, throwable.getMessage()); } - Logger.error("{} PUBLISH to TOPIC '{}' failed with '{}'", + Logger.error("{} failed PUBLISH to TOPIC '{}': {}", clientLogPrefix, topic, MqttUtils.getRootCause(throwable).getMessage()); @@ -379,19 +394,19 @@ else if (publish.isDebug()) { } else { if (publish.isVerbose()) { - Logger.trace("{} PUBLISH acknowledged '{}' for PUBLISH to TOPIC: '{}'", + Logger.trace("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", clientLogPrefix, - publishResult, - topic); + topic, + publishResult); } else if (publish.isDebug()) { if (publishResult.getQos().equals(MqttQos.AT_LEAST_ONCE)) { - Logger.debug("{} received PUBACK for PUBLISH to TOPIC: '{}'", + Logger.debug("{} received PUBACK for PUBLISH to TOPIC '{}'", clientLogPrefix, topic); } else if (publishResult.getQos().equals(MqttQos.EXACTLY_ONCE)) { - Logger.debug("{} received PUBREC for PUBLISH to TOPIC: '{}'", + Logger.debug("{} received PUBREC for PUBLISH to TOPIC '{}'", clientLogPrefix, topic); } @@ -417,7 +432,7 @@ void mqtt5Unsubscribe(@NotNull final Mqtt5Client client, @NotNull final Unsubscr unsubscribeMessage); } else if (unsubscribe.isDebug()) { - Logger.debug("{} sending UNSUBSCRIBE: (TOPIC: '{}', userProperties: {})", + Logger.debug("{} sending UNSUBSCRIB (TOPIC: '{}', userProperties: {})", clientLogPrefix, topic, unsubscribe.getUserProperties()); @@ -451,12 +466,12 @@ else if (unsubscribe.isDebug()) { getClientDataMap().get(unsubscribe.getKey()).removeSubscription(MqttTopicFilter.of(topic)); if (unsubscribe.isVerbose()) { - Logger.trace("{} received UNSUBACK {}", + Logger.trace("{} received UNSUBACK: {}", clientLogPrefix, unsubAck); } else if (unsubscribe.isDebug()) { - Logger.debug("{} received UNSUBACK {}", + Logger.debug("{} received UNSUBACK: {}", clientLogPrefix, unsubAck.getReasonCodes()); } @@ -483,7 +498,7 @@ void mqtt3Unsubscribe(@NotNull final Mqtt3Client client, @NotNull final Unsubscr unsubscribeMessage); } else if (unsubscribe.isDebug()) { - Logger.debug("{} Sending UNSUBSCRIBE: (TOPIC: '{}', userProperties: {})", + Logger.debug("{} Sending UNSUBSCRIBE (TOPIC: '{}', userProperties: {})", clientLogPrefix, topic, unsubscribe.getUserProperties()); @@ -553,7 +568,7 @@ void mqtt5Disconnect(@NotNull final Mqtt5Client client, @NotNull final Disconnec Logger.trace("{} sending DISCONNECT with Mqtt5Disconnect: {}", clientLogPrefix, disconnectMessage); } else if (disconnect.isDebug()) { - Logger.debug("{} sending DISCONNECT (Reason: {}, sessionExpiryInterval: {}, userProperties: {})", + Logger.debug("{} sending DISCONNECT (Reason: {}, SessionExpiryInterval: {}, UserProperties: {})", clientLogPrefix, disconnect.getReasonString(), disconnect.getSessionExpiryInterval(), From 45bde355b111b9f1c0527271249ee1bdfa25a854 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Thu, 5 Dec 2019 15:12:08 +0100 Subject: [PATCH 08/20] do not log null values on non-shell commands --- .../commands/cli/AbstractConnectFlags.java | 4 +- .../cli/commands/cli/PublishCommand.java | 26 ++++++----- .../cli/commands/cli/SubscribeCommand.java | 13 ++++-- .../commands/shell/ContextSwitchCommand.java | 1 - .../shell/ContextUnsubscribeCommand.java | 2 +- .../hivemq/cli/mqtt/MqttClientExecutor.java | 44 +++++++++---------- 6 files changed, 50 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java index 2d5e62bff..e1383fbca 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java +++ b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java @@ -43,8 +43,8 @@ public abstract class AbstractConnectFlags extends AbstractCommonFlags implement String connectOptions() { return commonOptions() + - ", sessionExpiryInterval= " + sessionExpiryInterval + - ", userProperties=" + (connectUserProperties == null? null : Arrays.toString(connectUserProperties)) + + (sessionExpiryInterval != null ? (", sessionExpiryInterval=" + sessionExpiryInterval) : "") + + (connectUserProperties != null ? (", userProperties=" + Arrays.toString(connectUserProperties)) : "") + connectRestrictionOptions(); } diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index 1fc6fbbfc..ce19a2101 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -38,6 +38,7 @@ import javax.inject.Inject; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.Arrays; @CommandLine.Command(name = "pub", @@ -105,6 +106,10 @@ public void run() { setDefaultOptions(); sslConfig = buildSslConfig(); + if (isVerbose()) { + Logger.trace("Command {} ", this); + } + logUnusedOptions(); try { @@ -146,17 +151,18 @@ public void logUnusedOptions() { @Override public String toString() { - return "Publish:: {" + - "topics=" + Arrays.toString(topics) + + return getClass().getSimpleName() + "{" + + connectOptions() + + ", topics=" + Arrays.toString(topics) + ", qos=" + Arrays.toString(qos) + - ", retain=" + retain + - ", messageExpiryInterval=" + messageExpiryInterval + - ", payloadFormatIndicator=" + payloadFormatIndicator + - ", contentType=" + contentType + - ", responseTopic=" + responseTopic + - ", correlationData=" + correlationData + - ", userProperties=" + getUserProperties() + - ", Connect:: {" + connectOptions() + "}" + + ", message=" + new String(message.array(), StandardCharsets.UTF_8) + + (retain != null ? (", retain=" + retain) : "") + + (messageExpiryInterval != null ? (", messageExpiryInterval=" + messageExpiryInterval) : "") + + (payloadFormatIndicator != null ? (", payloadFormatIndicator=" + payloadFormatIndicator) : "") + + (contentType != null ? (", contentType=" + contentType) : "") + + (responseTopic != null ? (", responseTopic=" + responseTopic) : "") + + (correlationData != null ? (", correlationData=" + new String(correlationData.array(), StandardCharsets.UTF_8)) : "") + + (userProperties != null ? (", userProperties=" + getUserProperties()) : "") + '}'; } diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index 6c3c52a2c..5cc40b9b9 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -98,6 +98,11 @@ public SubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecutor, public void run() { setDefaultOptions(); sslConfig = buildSslConfig(); + + if (isVerbose()) { + Logger.trace("Command {} ", this); + } + logUnusedOptions(); try { @@ -152,14 +157,14 @@ public void setDefaultOptions() { @Override public String toString() { - return "Subscribe:: {" + + return getClass().getSimpleName() + "{" + + connectOptions() + "topics=" + Arrays.toString(topics) + ", qos=" + Arrays.toString(qos) + - ", userProperties=" + userProperties + - ", toFile=" + publishFile + + (userProperties != null ? (", userProperties=" + Arrays.toString(userProperties)) : "") + + (publishFile != null ? (", publishFile=" + publishFile.getAbsolutePath()) : "") + ", outputToConsole=" + printToSTDOUT + ", base64=" + base64 + - ", Connect:: {" + commonOptions() + "}" + '}'; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java index e918ba10d..181605852 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java @@ -76,7 +76,6 @@ public void run() { } } - //TODO if (isVerbose()) { Logger.trace("Command {} ", this); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java index 86d5298e5..b1f98d4bb 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java @@ -86,7 +86,7 @@ private void logUnusedUnsubscribeOptions() { @Override public String toString() { - return "ContextUnsubscribe:: {" + + return getClass().getSimpleName() + "{" + "key=" + getKey() + ", topics=" + Arrays.toString(topics) + (userProperties != null ? (", userProperties=" + Arrays.toString(userProperties)) : "") + diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index f2036d391..83ee5772e 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -66,7 +66,7 @@ void mqtt5Connect(final @NotNull Mqtt5Client client, final @NotNull Mqtt5Connect String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); if (connect.isVerbose()) { - Logger.trace("{} sending CONNECT with Mqtt5Connect: {}", + Logger.trace("{} sending CONNECT {}", clientLogPrefix, connectMessage); } @@ -79,10 +79,10 @@ else if (connect.isDebug()) { .connect(connectMessage); if (connect.isVerbose()) { - Logger.trace("{} received CONNACK: {} ", clientLogPrefix, connAck); + Logger.trace("{} received CONNACK {} ", clientLogPrefix, connAck); } else if (connect.isDebug()) { - Logger.debug("{} received CONNACK {}", clientLogPrefix, + Logger.debug("{} received CONNACK ({})", clientLogPrefix, connAck.getReasonCode()); } @@ -93,7 +93,7 @@ void mqtt3Connect(final @NotNull Mqtt3Client client, final @NotNull Mqtt3Connect final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); if (connect.isVerbose()) { - Logger.trace("{} sending CONNECT with Mqtt3Connect: {}", + Logger.trace("{} sending CONNECT {}", clientLogPrefix, connectMessage); } @@ -109,7 +109,7 @@ else if (connect.isDebug()) { Logger.trace("{} received CONNACK {} ", clientLogPrefix, connAck); } else if (connect.isDebug()) { - Logger.debug("{} received CONNACK {}", clientLogPrefix, + Logger.debug("{} received CONNACK ({})", clientLogPrefix, connAck.getReturnCode()); } @@ -131,12 +131,12 @@ void mqtt5Subscribe(final @NotNull Mqtt5Client client, final @NotNull Subscribe final Mqtt5Subscribe subscribeMessage = builder.build(); if (subscribe.isVerbose()) { - Logger.trace("{} sending SUBSCRIBE with Mqtt5Subscribe {}", + Logger.trace("{} sending SUBSCRIBE {}", clientLogPrefix, subscribeMessage); } else if (subscribe.isDebug()) { - Logger.debug("{} sending SUBSCRIBE: (Topic: {}, QoS: '{}')", + Logger.debug("{} sending SUBSCRIBE (Topic: {}, QoS: '{}')", clientLogPrefix, topic, qos); @@ -178,7 +178,7 @@ else if (subscribe.isDebug()) { subAck); } else if (subscribe.isDebug()) { - Logger.debug("{} received SUBACK: {}", + Logger.debug("{} received SUBACK ({})", clientLogPrefix, subAck.getReasonCodes()); } @@ -202,10 +202,10 @@ void mqtt3Subscribe(final @NotNull Mqtt3Client client, final @NotNull Subscribe final Mqtt3Subscribe subscribeMessage = builder.build(); if (subscribe.isVerbose()) { - Logger.trace("{} sending SUBSCRIBE with Mqtt3Subscribe: {}", clientLogPrefix, subscribeMessage); + Logger.trace("{} sending SUBSCRIBE {}", clientLogPrefix, subscribeMessage); } else if (subscribe.isDebug()) { - Logger.debug("{} sending SUBSCRIBE: (Topic: {}, QoS: '{}')", clientLogPrefix, topic, qos); + Logger.debug("{} sending SUBSCRIBE (Topic: {}, QoS: '{}')", clientLogPrefix, topic, qos); } @@ -239,10 +239,10 @@ else if (subscribe.isDebug()) { getClientDataMap().get(clientKey).addSubscription(MqttTopicFilter.of(topic)); if (subscribe.isVerbose()) { - Logger.trace("{} received SUBACK: {}", clientLogPrefix, subAck); + Logger.trace("{} received SUBACK {}", clientLogPrefix, subAck); } else if (subscribe.isDebug()) { - Logger.debug("{} received SUBACK: {}", clientLogPrefix, subAck.getReturnCodes()); + Logger.debug("{} received SUBACK ({})", clientLogPrefix, subAck.getReturnCodes()); } } @@ -276,10 +276,10 @@ void mqtt5Publish(final @NotNull Mqtt5Client client, final @NotNull Publish publ final Mqtt5Publish publishMessage = publishBuilder.build(); if (publish.isVerbose()) { - Logger.trace("{} sending PUBLISH with Mqtt5Publish: {}", clientLogPrefix, publishMessage); + Logger.trace("{} sending PUBLISH {}", clientLogPrefix, publishMessage); } else if (publish.isDebug()) { - Logger.debug("{} sending PUBLISH: (Topic: '{}', QoS: '{}', Message: '{}')", + Logger.debug("{} sending PUBLISH (Topic: '{}', QoS: '{}', Message: '{}')", clientLogPrefix, topic, qos, @@ -360,10 +360,10 @@ void mqtt3Publish(final @NotNull Mqtt3Client client, final @NotNull Publish publ final Mqtt3Publish publishMessage = publishBuilder.build(); if (publish.isVerbose()) { - Logger.trace("{} sending PUBLISH with Mqtt3Publish: {}", clientLogPrefix, publishMessage); + Logger.trace("{} sending PUBLISH {}", clientLogPrefix, publishMessage); } else if (publish.isDebug()) { - Logger.debug("{} sending PUBLISH: (TOPIC: '{}', QoS: '{}', Message: '{}')", + Logger.debug("{} sending PUBLISH (TOPIC: '{}', QoS: '{}', Message: '{}')", clientLogPrefix, topic, qos, @@ -427,12 +427,12 @@ void mqtt5Unsubscribe(@NotNull final Mqtt5Client client, @NotNull final Unsubscr .build(); if (unsubscribe.isVerbose()) { - Logger.trace("{} sending UNSUBSCRIBE with Mqtt5Unsubscribe: {}", + Logger.trace("{} sending UNSUBSCRIBE {}", clientLogPrefix, unsubscribeMessage); } else if (unsubscribe.isDebug()) { - Logger.debug("{} sending UNSUBSCRIB (TOPIC: '{}', userProperties: {})", + Logger.debug("{} sending UNSUBSCRIBE (TOPIC: '{}', userProperties: {})", clientLogPrefix, topic, unsubscribe.getUserProperties()); @@ -466,12 +466,12 @@ else if (unsubscribe.isDebug()) { getClientDataMap().get(unsubscribe.getKey()).removeSubscription(MqttTopicFilter.of(topic)); if (unsubscribe.isVerbose()) { - Logger.trace("{} received UNSUBACK: {}", + Logger.trace("{} received UNSUBACK {}", clientLogPrefix, unsubAck); } else if (unsubscribe.isDebug()) { - Logger.debug("{} received UNSUBACK: {}", + Logger.debug("{} received UNSUBACK ({})", clientLogPrefix, unsubAck.getReasonCodes()); } @@ -493,7 +493,7 @@ void mqtt3Unsubscribe(@NotNull final Mqtt3Client client, @NotNull final Unsubscr .build(); if (unsubscribe.isVerbose()) { - Logger.trace("{} Sending UNSUBSCRIBE with Mqtt3Unsubscribe: {}", + Logger.trace("{} Sending UNSUBSCRIBE {}", clientLogPrefix, unsubscribeMessage); } @@ -565,7 +565,7 @@ void mqtt5Disconnect(@NotNull final Mqtt5Client client, @NotNull final Disconnec final Mqtt5Disconnect disconnectMessage = disconnectBuilder.build(); if (disconnect.isVerbose()) { - Logger.trace("{} sending DISCONNECT with Mqtt5Disconnect: {}", clientLogPrefix, disconnectMessage); + Logger.trace("{} sending DISCONNECT {}", clientLogPrefix, disconnectMessage); } else if (disconnect.isDebug()) { Logger.debug("{} sending DISCONNECT (Reason: {}, SessionExpiryInterval: {}, UserProperties: {})", From 6d1e6e172faa093286383129168e4fb71601c706 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Thu, 5 Dec 2019 15:12:25 +0100 Subject: [PATCH 09/20] add todo --- .../com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java index 8b7a307e6..a7411c51b 100644 --- a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java +++ b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java @@ -73,14 +73,14 @@ public void accept(final @NotNull Mqtt3Publish mqtt3Publish) { System.out.println(payloadMessage); } - if (verbose) { - Logger.trace("Client {} received PUBLISH: {}, MESSAGE: '{}'", + if (verbose) { //TODO unified logging + Logger.trace("Client {} received PUBLISH {}, MESSAGE: '{}'", identifier, mqtt3Publish, new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } else if (debug) { - Logger.debug("Client {} received PUBLISH: (Topic: '{}', MESSAGE: '{}')", + Logger.debug("Client {} received PUBLISH (topic={}, message={})", identifier, mqtt3Publish.getTopic(), new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } From 5d8ec984a0ff32aa2fe42fba3923084c58013055 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 11 Dec 2019 16:14:35 +0100 Subject: [PATCH 10/20] update to tinylog version 2.0.1 --- build.gradle | 5 +- .../com/hivemq/cli/DefaultCLIProperties.java | 2 +- src/main/java/com/hivemq/cli/MqttCLIMain.java | 12 +---- .../hivemq/cli/commands/AbstractCommand.java | 5 -- .../cli/commands/AbstractCommonFlags.java | 2 +- .../AbstractConnectRestrictionFlags.java | 4 +- .../cli/commands/AbstractWillFlags.java | 2 +- .../com/hivemq/cli/commands/MqttCommand.java | 2 +- .../commands/cli/AbstractConnectFlags.java | 2 +- .../cli/commands/cli/PublishCommand.java | 16 +++++- .../cli/commands/cli/SubscribeCommand.java | 19 +++++-- .../commands/shell/ClearScreenCommand.java | 2 - .../shell/ContextDisconnectCommand.java | 3 +- .../commands/shell/ContextExitCommand.java | 1 - .../commands/shell/ContextPublishCommand.java | 3 +- .../shell/ContextSubscribeCommand.java | 2 +- .../commands/shell/ContextSwitchCommand.java | 4 +- .../shell/ContextUnsubscribeCommand.java | 3 +- .../commands/shell/ListClientsCommand.java | 3 +- .../cli/commands/shell/ShellCommand.java | 54 +++++++++++-------- .../commands/shell/ShellConnectCommand.java | 3 +- .../commands/shell/ShellContextCommand.java | 2 - .../shell/ShellDisconnectCommand.java | 3 +- .../cli/commands/shell/ShellExitCommand.java | 1 - .../converters/FileToPrivateKeyConverter.java | 2 - .../cli/mqtt/AbstractMqttClientExecutor.java | 4 +- .../mqtt/ContextClientDisconnectListener.java | 3 +- .../hivemq/cli/mqtt/MqttClientExecutor.java | 2 +- .../mqtt/SubscribeMqtt3PublishCallback.java | 6 +-- .../mqtt/SubscribeMqtt5PublishCallback.java | 7 ++- .../java/com/hivemq/cli/utils/FileUtils.java | 2 +- .../com/hivemq/cli/utils/LoggerUtils.java | 2 +- .../hivemq/cli/DefaultCLIPropertiesTest.java | 2 +- 33 files changed, 93 insertions(+), 92 deletions(-) diff --git a/build.gradle b/build.gradle index fb475de94..21f7909be 100644 --- a/build.gradle +++ b/build.gradle @@ -121,7 +121,7 @@ ext { daggerVersion = '2.21' guavaVersion ='27.0.1-jre' hivemqclientVersion = '1.1.1' - tinylogVersion = '1.3.6' + tinylogVersion = '2.0.1' jcToolsVersion = '2.1.2' jetbrainsAnnotationsVersion = '17.0.0' bouncycastleVersion='1.62' @@ -146,7 +146,8 @@ dependencies { implementation group: 'info.picocli', name: 'picocli-codegen', version: picocliVersion implementation group: 'com.google.guava', name: 'guava', version: guavaVersion - implementation group: 'org.tinylog', name: 'tinylog', version: tinylogVersion + implementation "org.tinylog:tinylog-api:$tinylogVersion" + implementation "org.tinylog:tinylog-impl:$tinylogVersion" implementation group: 'org.jetbrains', name: 'annotations', version: jetbrainsAnnotationsVersion implementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: bouncycastleVersion diff --git a/src/main/java/com/hivemq/cli/DefaultCLIProperties.java b/src/main/java/com/hivemq/cli/DefaultCLIProperties.java index 0a665b9d3..26e8a4d72 100644 --- a/src/main/java/com/hivemq/cli/DefaultCLIProperties.java +++ b/src/main/java/com/hivemq/cli/DefaultCLIProperties.java @@ -24,7 +24,7 @@ import com.hivemq.client.mqtt.MqttVersion; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Level; +import org.tinylog.Level; import javax.inject.Singleton; import java.io.*; diff --git a/src/main/java/com/hivemq/cli/MqttCLIMain.java b/src/main/java/com/hivemq/cli/MqttCLIMain.java index da4d3c762..78b5d780d 100644 --- a/src/main/java/com/hivemq/cli/MqttCLIMain.java +++ b/src/main/java/com/hivemq/cli/MqttCLIMain.java @@ -23,10 +23,6 @@ import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.mqtt3.Mqtt3Client; import com.hivemq.client.mqtt.mqtt5.Mqtt5Client; -import org.pmw.tinylog.Configurator; -import org.pmw.tinylog.Level; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.writers.ConsoleWriter; import picocli.CommandLine; import java.security.Security; @@ -42,12 +38,6 @@ public static void main(final String[] args) { Security.setProperty("crypto.policy", "unlimited"); - Configurator.defaultConfig() - .writer(new ConsoleWriter()) - .formatPattern("{message}") - .level(Level.INFO) - .activate(); - MQTTCLI = DaggerMqttCLI.create(); final CommandLine commandLine = MQTTCLI.cli(); final DefaultCLIProperties defaultCLIProperties = MQTTCLI.defaultCLIProperties(); @@ -55,7 +45,7 @@ public static void main(final String[] args) { try { defaultCLIProperties.init(); } catch (Exception e) { - Logger.error(e.getMessage()); + System.err.println(e.getMessage()); System.exit(-1); } diff --git a/src/main/java/com/hivemq/cli/commands/AbstractCommand.java b/src/main/java/com/hivemq/cli/commands/AbstractCommand.java index 6ef9da1ad..03831373d 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractCommand.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractCommand.java @@ -17,9 +17,6 @@ package com.hivemq.cli.commands; -import com.hivemq.cli.commands.CliCommand; -import org.pmw.tinylog.Configurator; -import org.pmw.tinylog.Level; import picocli.CommandLine; @CommandLine.Command(sortOptions = false, @@ -39,7 +36,6 @@ private void activateDebugMode(final boolean debug) { if (debug && !verbose) { this.debug = true; - Configurator.currentConfig().level(Level.DEBUG).activate(); } } @@ -49,7 +45,6 @@ private void activateVerboseMode(final boolean verbose) { if (verbose) { this.verbose = true; debug = true; - Configurator.currentConfig().level(Level.TRACE).activate(); } else { this.verbose = false; } diff --git a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java index 74ee050f8..b6e429be8 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java @@ -24,7 +24,7 @@ import com.hivemq.client.mqtt.MqttWebSocketConfig; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; import javax.net.ssl.KeyManagerFactory; diff --git a/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java index 7de737446..af6fdc11e 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractConnectRestrictionFlags.java @@ -19,11 +19,9 @@ import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5ConnectRestrictions; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; -import java.util.Arrays; - public abstract class AbstractConnectRestrictionFlags extends AbstractWillFlags implements ConnectRestrictions { @CommandLine.Option(names = {"--rcvMax"}, description = "The maximum amount of not acknowledged publishes with QoS 1 or 2 the client accepts from the server concurrently. (default: " + Mqtt5ConnectRestrictions.DEFAULT_RECEIVE_MAXIMUM + ")", order = 3) diff --git a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java index fc80f5020..e95b96fcf 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractWillFlags.java @@ -25,7 +25,7 @@ import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PayloadFormatIndicator; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5WillPublish; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; import java.nio.ByteBuffer; diff --git a/src/main/java/com/hivemq/cli/commands/MqttCommand.java b/src/main/java/com/hivemq/cli/commands/MqttCommand.java index 93d0a38a5..3ee2b19dd 100644 --- a/src/main/java/com/hivemq/cli/commands/MqttCommand.java +++ b/src/main/java/com/hivemq/cli/commands/MqttCommand.java @@ -26,7 +26,7 @@ import com.hivemq.client.mqtt.MqttVersion; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; import java.util.List; diff --git a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java index e1383fbca..9265542e9 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java +++ b/src/main/java/com/hivemq/cli/commands/cli/AbstractConnectFlags.java @@ -25,7 +25,7 @@ import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; import java.util.Arrays; diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index ce19a2101..ea7f58930 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -32,14 +32,16 @@ import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PayloadFormatIndicator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; +import org.tinylog.configuration.Configuration; import picocli.CommandLine; import javax.inject.Inject; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; @CommandLine.Command(name = "pub", versionProvider = MqttCLIMain.CLIVersionProvider.class, @@ -103,6 +105,16 @@ public PublishCommand(final @NotNull MqttClientExecutor mqttClientExecutor) { @Override public void run() { + // TinyLog configuration + Map configurationMap = new HashMap<>(); + configurationMap.put("writer", "console"); + configurationMap.put("writer.format", "{tag} {message}"); + configurationMap.put("writer.level", "off"); + if (isDebug()) { configurationMap.put("writer.level", "debug"); } + if (isVerbose()) { configurationMap.put("writer.level", "trace"); } + + Configuration.replace(configurationMap); + setDefaultOptions(); sslConfig = buildSslConfig(); diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index 5cc40b9b9..a0524a8a6 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -29,18 +29,19 @@ import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; -import com.hivemq.client.mqtt.exceptions.ConnectionFailedException; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; +import org.tinylog.configuration.Configuration; import picocli.CommandLine; import javax.inject.Inject; import java.io.File; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; @CommandLine.Command(name = "sub", versionProvider = MqttCLIMain.CLIVersionProvider.class, @@ -96,6 +97,17 @@ public SubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecutor, @Override public void run() { + + // TinyLog configuration + Map configurationMap = new HashMap<>(); + configurationMap.put("writer", "console"); + configurationMap.put("writer.format", "{tag} {message}"); + configurationMap.put("writer.level", "off"); + if (isDebug()) { configurationMap.put("writer.level", "debug"); } + if (isVerbose()) { configurationMap.put("writer.level", "trace"); } + + Configuration.replace(configurationMap); + setDefaultOptions(); sslConfig = buildSslConfig(); @@ -111,6 +123,7 @@ public void run() { } catch (final Exception ex) { LoggerUtils.logOnRightLevels(this, ex); + return; } try { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java index b8f2f576e..d0d49930c 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ClearScreenCommand.java @@ -18,11 +18,9 @@ import com.hivemq.cli.commands.CliCommand; -import org.pmw.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; -import java.io.IOException; import java.util.concurrent.Callable; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java index 5dee13158..d1e13e1e7 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java @@ -27,8 +27,7 @@ import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java index ce95e0afe..51dc6bd6b 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextExitCommand.java @@ -19,7 +19,6 @@ import com.hivemq.cli.mqtt.MqttClientExecutor; import org.jetbrains.annotations.NotNull; -import org.pmw.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java index 25f3a7a01..e540564f2 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java @@ -28,8 +28,7 @@ import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PayloadFormatIndicator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java index f961d5655..95b197bc7 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java @@ -31,7 +31,7 @@ import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java index 181605852..cdc357fef 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java @@ -18,12 +18,10 @@ import com.hivemq.cli.commands.Context; import com.hivemq.cli.mqtt.MqttClientExecutor; -import com.hivemq.cli.utils.LoggerUtils; -import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClient; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java index b1f98d4bb..2f3442e8d 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java @@ -26,8 +26,7 @@ import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java index f5bf4ba56..46a70e63c 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java @@ -20,9 +20,8 @@ import com.hivemq.cli.mqtt.ClientData; import com.hivemq.cli.mqtt.MqttClientExecutor; import com.hivemq.client.mqtt.MqttClient; -import com.hivemq.client.mqtt.MqttClientState; import org.jetbrains.annotations.NotNull; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index 17866a992..53f23b455 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -28,20 +28,21 @@ import org.jline.terminal.TerminalBuilder; import org.jline.utils.AttributedStringBuilder; import org.jline.utils.AttributedStyle; -import org.pmw.tinylog.Configurator; -import org.pmw.tinylog.Level; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; -import org.pmw.tinylog.labelers.TimestampLabeler; -import org.pmw.tinylog.policies.SizePolicy; -import org.pmw.tinylog.writers.ConsoleWriter; -import org.pmw.tinylog.writers.RollingFileWriter; +import org.tinylog.Level; +import org.tinylog.Logger; +import org.tinylog.configuration.Configuration; import picocli.CommandLine; import picocli.shell.jline3.PicocliJLineCompleter; +import sun.security.krb5.Config; import javax.inject.Inject; import java.io.File; import java.io.PrintWriter; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; @CommandLine.Command(name = "shell", aliases = "sh", versionProvider = MqttCLIMain.CLIVersionProvider.class, @@ -94,6 +95,8 @@ public class ShellCommand implements Runnable { @Override public void run() { + final String dir = defaultCLIProperties.getLogfilePath(); + final Level debugLevel = defaultCLIProperties.getShellDebugLevel(); switch (debugLevel) { case TRACE: @@ -110,25 +113,34 @@ public void run() { break; } - final String dir = defaultCLIProperties.getLogfilePath(); - final File dirFile = new File(dir); dirFile.mkdirs(); - final String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{class_name}|min-size=25} | {{level}|min-size=7} | {message}"; + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + Date date = new Date(); + + logfilePath = dir + "mqtt_cli_" + dateFormat.format(date) + ".log"; + + final String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{tag}|min-size=25} | {{level}|min-size=7} | {message}"; + + // TinyLog configuration + Map configurationMap = new HashMap<>(); + configurationMap.put("writer1", "file"); + configurationMap.put("writer1.format", logfileFormatPattern); + configurationMap.put("writer1.file", logfilePath); + configurationMap.put("writer1.append", "true"); + configurationMap.put("writer1.level", "off"); + if (isDebug()) { configurationMap.put("writer1.level", "debug"); } + if (isVerbose()) { configurationMap.put("writer1.level", "trace"); } - final RollingFileWriter logfileWriter = new RollingFileWriter(dir + "hmq-cli.log", 30, false, new TimestampLabeler("yyyy-MM-dd"), new SizePolicy(1024 * 10)); + // Writer inside shell + configurationMap.put("writer2", "console"); + configurationMap.put("writer2.format", "{tag} {message}"); + configurationMap.put("writer2.level", "info"); - Configurator.defaultConfig() - .writer(logfileWriter, - debugLevel, - logfileFormatPattern) - .addWriter(new ConsoleWriter(), - Level.INFO, - "{message}") - .activate(); + Configuration.replace(configurationMap); - logfilePath = logfileWriter.getFilename(); + logfilePath = Configuration.get("writer1.file"); interact(); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java index 023f1e040..8caf926f4 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java @@ -30,8 +30,7 @@ import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java index f4a4f21dc..7350825e9 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java @@ -22,8 +22,6 @@ import com.hivemq.client.mqtt.MqttClient; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java index da75f5383..9fdfb851d 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java @@ -29,8 +29,7 @@ import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java index ca7a96c3e..c5f685539 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellExitCommand.java @@ -17,7 +17,6 @@ package com.hivemq.cli.commands.shell; import com.hivemq.cli.commands.CliCommand; -import org.pmw.tinylog.Logger; import picocli.CommandLine; import javax.inject.Inject; diff --git a/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java b/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java index 68e57b0c7..33e6e00fb 100644 --- a/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java +++ b/src/main/java/com/hivemq/cli/converters/FileToPrivateKeyConverter.java @@ -29,7 +29,6 @@ import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; import org.bouncycastle.pkcs.PKCSException; import org.jetbrains.annotations.NotNull; -import org.pmw.tinylog.Logger; import picocli.CommandLine; import java.io.File; @@ -58,7 +57,6 @@ private PrivateKey getPrivateKeyFromFile(final @NotNull File keyFile) throws Exc try { object = pemParser.readObject(); } catch (PEMException pe) { - Logger.debug(pe); throw new Exception(MALFORMED_KEY); } diff --git a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java index 6eee2b7f9..d41829201 100644 --- a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java @@ -42,12 +42,10 @@ import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5WillPublishBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; diff --git a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java index d1b0795f1..cba104522 100644 --- a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java +++ b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java @@ -25,8 +25,7 @@ import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedListener; import com.hivemq.client.mqtt.lifecycle.MqttDisconnectSource; import org.jetbrains.annotations.NotNull; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; public class ContextClientDisconnectListener implements MqttClientDisconnectedListener { diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index 83ee5772e..8f5d468c6 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -45,7 +45,6 @@ import com.hivemq.client.mqtt.mqtt5.message.unsubscribe.unsuback.Mqtt5UnsubAck; import com.hivemq.client.util.TypeSwitch; import org.jetbrains.annotations.NotNull; -import org.pmw.tinylog.Logger; import javax.inject.Inject; import javax.inject.Singleton; @@ -53,6 +52,7 @@ import java.nio.charset.StandardCharsets; import org.bouncycastle.util.encoders.Base64; +import org.tinylog.Logger; @Singleton public class MqttClientExecutor extends AbstractMqttClientExecutor { diff --git a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java index a7411c51b..914cf8acf 100644 --- a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java +++ b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java @@ -22,7 +22,7 @@ import org.bouncycastle.util.encoders.Base64; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import java.io.File; import java.io.PrintWriter; @@ -74,13 +74,13 @@ public void accept(final @NotNull Mqtt3Publish mqtt3Publish) { } if (verbose) { //TODO unified logging - Logger.trace("Client {} received PUBLISH {}, MESSAGE: '{}'", + Logger.trace("{} received PUBLISH {}, (message={})", identifier, mqtt3Publish, new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } else if (debug) { - Logger.debug("Client {} received PUBLISH (topic={}, message={})", + Logger.debug("{} received PUBLISH (topic={}, message={})", identifier, mqtt3Publish.getTopic(), new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } diff --git a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java index 7f7f096b6..a03cb03dd 100644 --- a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java +++ b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java @@ -22,8 +22,7 @@ import org.bouncycastle.util.encoders.Base64; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.pmw.tinylog.Logger; -import org.pmw.tinylog.LoggingContext; +import org.tinylog.Logger; import java.io.File; import java.io.PrintWriter; @@ -75,10 +74,10 @@ public void accept(final @NotNull Mqtt5Publish mqtt5Publish) { } if (verbose) { - Logger.trace("Client {} received PUBLISH: {}, MESSAGE: '{}'", identifier, mqtt5Publish, new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); + Logger.trace("{} received PUBLISH {} (topic={})", identifier, mqtt5Publish, new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } else if (debug) { - Logger.debug("Client {} received PUBLISH: (Topic: '{}', MESSAGE: '{}')", identifier, mqtt5Publish.getTopic(), new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); + Logger.debug("{} received PUBLISH (topic={}, message={})", identifier, mqtt5Publish.getTopic(), new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); } } diff --git a/src/main/java/com/hivemq/cli/utils/FileUtils.java b/src/main/java/com/hivemq/cli/utils/FileUtils.java index 1749306c5..de346ca8e 100644 --- a/src/main/java/com/hivemq/cli/utils/FileUtils.java +++ b/src/main/java/com/hivemq/cli/utils/FileUtils.java @@ -17,7 +17,7 @@ package com.hivemq.cli.utils; import org.jetbrains.annotations.NotNull; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import java.io.*; diff --git a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java index 3cbc4abd1..9d1b39aab 100644 --- a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java +++ b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java @@ -21,7 +21,7 @@ import com.hivemq.client.mqtt.MqttClientConfig; import com.hivemq.client.mqtt.datatypes.MqttClientIdentifier; import org.jetbrains.annotations.NotNull; -import org.pmw.tinylog.Logger; +import org.tinylog.Logger; import java.util.Objects; import java.util.Optional; diff --git a/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java b/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java index 78572ffa0..2e62f82b6 100644 --- a/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java +++ b/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.pmw.tinylog.Level; +import org.tinylog.Level; import java.io.File; import java.io.IOException; From 6d6eef02190330265e7974865bce2812c783a21b Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 11 Dec 2019 17:23:04 +0100 Subject: [PATCH 11/20] begin refactoring error to serr printing --- .../hivemq/cli/commands/cli/PublishCommand.java | 4 +++- .../cli/commands/cli/SubscribeCommand.java | 7 +++++-- .../hivemq/cli/commands/shell/ShellCommand.java | 17 ++++++++--------- .../cli/commands/shell/ShellConnectCommand.java | 4 +++- .../commands/shell/ShellDisconnectCommand.java | 4 +++- .../java/com/hivemq/cli/utils/LoggerUtils.java | 11 +---------- 6 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index ea7f58930..35e9ab2cf 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.cli; +import com.google.common.base.Throwables; import com.hivemq.cli.MqttCLIMain; import com.hivemq.cli.commands.Publish; import com.hivemq.cli.converters.*; @@ -129,7 +130,8 @@ public void run() { mqttClientExecutor.publish(this); } catch (final Exception ex) { - LoggerUtils.logOnRightLevels(this, ex); + Logger.error(ex.getMessage()); + System.err.println(Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index a0524a8a6..d4ae3c46b 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.cli; +import com.google.common.base.Throwables; import com.hivemq.cli.DefaultCLIProperties; import com.hivemq.cli.MqttCLIMain; import com.hivemq.cli.commands.Subscribe; @@ -122,7 +123,8 @@ public void run() { subscribeClient = mqttClientExecutor.subscribe(this); } catch (final Exception ex) { - LoggerUtils.logOnRightLevels(this, ex); + Logger.error(ex.getMessage()); + System.err.println(Throwables.getRootCause(ex).getMessage()); return; } @@ -130,7 +132,8 @@ public void run() { stay(); } catch (final InterruptedException ex) { - LoggerUtils.logOnRightLevels(this, ex); + Logger.error(ex.getMessage()); + System.err.println(Throwables.getRootCause(ex).getMessage()); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index 53f23b455..d3aab8e9c 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -121,7 +121,11 @@ public void run() { logfilePath = dir + "mqtt_cli_" + dateFormat.format(date) + ".log"; - final String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{tag}|min-size=25} | {{level}|min-size=7} | {message}"; + String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{tag}|min-size=10} | {{level}|min-size=7} | {message}"; + if (isVerbose() || isDebug()) { + logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{level}|min-size=7} | {{class-name}.{method}:{line}|min-size=20} | {{tag}|min-size=10} | {message}"; + } + // TinyLog configuration Map configurationMap = new HashMap<>(); @@ -133,11 +137,6 @@ public void run() { if (isDebug()) { configurationMap.put("writer1.level", "debug"); } if (isVerbose()) { configurationMap.put("writer1.level", "trace"); } - // Writer inside shell - configurationMap.put("writer2", "console"); - configurationMap.put("writer2.format", "{tag} {message}"); - configurationMap.put("writer2.level", "info"); - Configuration.replace(configurationMap); logfilePath = Configuration.get("writer1.file"); @@ -175,13 +174,13 @@ private void interact() { TERMINAL_WRITER.println(shellCommandLine.getUsageMessage()); TERMINAL_WRITER.flush(); - Logger.info("Using default values from properties file {}:", defaultCLIProperties.getFile().getPath()); - Logger.info("Host: {}, Port: {}, Mqtt-Version {}, Shell-Debug-Level: {}", + Logger.tag("Shell").info("Using default values from properties file {}:", defaultCLIProperties.getFile().getPath()); + Logger.tag("Shell").info("Host: {}, Port: {}, Mqtt-Version {}, Shell-Debug-Level: {}", defaultCLIProperties.getHost(), defaultCLIProperties.getPort(), defaultCLIProperties.getMqttVersion(), defaultCLIProperties.getShellDebugLevel()); - Logger.info("Writing Logfile to {}", logfilePath); + Logger.tag("Shell").info("Writing Logfile to {}", logfilePath); String line; while (!exitShell) { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java index 8caf926f4..83ca7eb1f 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.AbstractCommonFlags; import com.hivemq.cli.commands.Connect; import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; @@ -84,7 +85,8 @@ public void run() { return mqttClientExecutor.connect(this); } catch (final Exception ex) { - LoggerUtils.logOnRightLevels(this, ex); + Logger.error(ex); + System.err.println(Throwables.getRootCause(ex).getMessage()); } return null; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java index 9fdfb851d..cc9ac5e8e 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java @@ -17,6 +17,7 @@ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.DefaultCLIProperties; import com.hivemq.cli.commands.Disconnect; import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; @@ -104,7 +105,8 @@ public void run() { } } catch (final Exception ex) { - LoggerUtils.logOnRightLevels(this, ex); + Logger.error(ex.getMessage()); + System.err.println(Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java index 9d1b39aab..92f4980f3 100644 --- a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java +++ b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.utils; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.CliCommand; import com.hivemq.cli.commands.shell.ShellContextCommand; import com.hivemq.client.mqtt.MqttClientConfig; @@ -28,16 +29,6 @@ public class LoggerUtils { - public static void logOnRightLevels(final @NotNull CliCommand cmd, final @NotNull Exception ex) { - if (cmd.isVerbose()) { - Logger.trace(ex); - } - else if (cmd.isDebug()) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); - } - public static void logWithCurrentContext(final @NotNull CliCommand cmd, final @NotNull Exception ex) { if (cmd.isVerbose()) { Logger.trace("{} : ", getShellContextClientPrefix(), ex); From e740875f4f08267454600cfa197e2f83cf8c70c6 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Thu, 12 Dec 2019 10:20:19 +0100 Subject: [PATCH 12/20] match correct severity levels with logger --- .../cli/commands/AbstractCommonFlags.java | 37 +- .../com/hivemq/cli/commands/MqttCommand.java | 17 +- .../cli/commands/cli/PublishCommand.java | 6 +- .../cli/commands/cli/SubscribeCommand.java | 8 +- .../shell/ContextDisconnectCommand.java | 4 +- .../commands/shell/ContextPublishCommand.java | 8 +- .../shell/ContextSubscribeCommand.java | 12 +- .../commands/shell/ContextSwitchCommand.java | 6 +- .../shell/ContextUnsubscribeCommand.java | 8 +- .../commands/shell/ListClientsCommand.java | 4 +- .../cli/commands/shell/ShellCommand.java | 22 +- .../commands/shell/ShellConnectCommand.java | 4 +- .../shell/ShellDisconnectCommand.java | 4 +- .../cli/mqtt/AbstractMqttClientExecutor.java | 61 +-- .../mqtt/ContextClientDisconnectListener.java | 8 +- .../hivemq/cli/mqtt/MqttClientExecutor.java | 384 ++++-------------- .../mqtt/SubscribeMqtt3PublishCallback.java | 42 +- .../mqtt/SubscribeMqtt5PublishCallback.java | 36 +- 18 files changed, 167 insertions(+), 504 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java index b6e429be8..648a97d62 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands; +import com.google.common.base.Throwables; import com.hivemq.cli.DefaultCLIProperties; import com.hivemq.cli.MqttCLIMain; import com.hivemq.cli.converters.*; @@ -111,7 +112,8 @@ public void setDefaultOptions() { try { password = defaultCLIProperties.getPassword(); } catch (Exception e) { - logPropertiesException(e, "Default password could not be loaded."); + Logger.error(e); + System.err.printf("Default password could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); } } @@ -119,7 +121,8 @@ public void setDefaultOptions() { try { clientCertificate = defaultCLIProperties.getClientCertificate(); } catch (Exception e) { - logPropertiesException(e, "Default client certificate could not be loaded."); + Logger.error(e); + System.err.printf("Default client certificate could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); } } @@ -127,7 +130,8 @@ public void setDefaultOptions() { try { clientPrivateKey = defaultCLIProperties.getClientPrivateKey(); } catch (Exception e) { - logPropertiesException(e, "Default client private key could not be loaded."); + Logger.error(e); + System.err.printf("Default client private key could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); } } @@ -141,7 +145,8 @@ public void setDefaultOptions() { certificates.add(defaultServerCertificate); } } catch (Exception e) { - logPropertiesException(e, "Default server certificate could not be loaded."); + Logger.error(e); + System.err.printf("Default server certificate could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); } } @@ -154,34 +159,14 @@ public void setDefaultOptions() { return doBuildSslConfig(); } catch (Exception e) { - logPropertiesException(e); + Logger.error(e); + System.err.println(Throwables.getRootCause(e).getMessage()); } } return null; } - private void logPropertiesException(final @NotNull Exception e) { - if (isVerbose()) { - Logger.trace(e); - } - else if (isDebug()) { - Logger.debug(e.getMessage()); - } - Logger.error(MqttUtils.getRootCause(e).getMessage()); - } - - private void logPropertiesException(final @NotNull Exception e, final @NotNull String message) { - if (isVerbose()) { - Logger.trace(e); - } - else if (isDebug()) { - Logger.debug(e.getMessage()); - } - Logger.error(message + " ({})", MqttUtils.getRootCause(e).getMessage()); - } - - private boolean useBuiltSslConfig() { return certificates != null || certificatesFromDir != null || diff --git a/src/main/java/com/hivemq/cli/commands/MqttCommand.java b/src/main/java/com/hivemq/cli/commands/MqttCommand.java index 3ee2b19dd..ef998dea3 100644 --- a/src/main/java/com/hivemq/cli/commands/MqttCommand.java +++ b/src/main/java/com/hivemq/cli/commands/MqttCommand.java @@ -53,24 +53,19 @@ public abstract class MqttCommand extends AbstractCommand implements Context { public void setDefaultOptions() { final DefaultCLIProperties defaultCLIProperties = MqttCLIMain.MQTTCLI.defaultCLIProperties(); if (version == null) { - if (isVerbose()) { - Logger.trace("Setting value of 'version' to default value: {}", defaultCLIProperties.getMqttVersion()); - } version = defaultCLIProperties.getMqttVersion(); + Logger.trace("Setting value of 'version' to default value: {}", version); } if (host == null) { - if (isVerbose()) { - Logger.trace("Setting value of 'host' to default value: {}", defaultCLIProperties.getHost()); - } host = defaultCLIProperties.getHost(); + Logger.trace("Setting value of 'host' to default value: {}", host); + } if (port == null) { - if (isVerbose()) { - Logger.trace("Setting value of 'port' to default value: {}", defaultCLIProperties.getPort()); - } port = defaultCLIProperties.getPort(); + Logger.trace("Setting value of 'port' to default value: {}", port); } if (identifierPrefix == null) { @@ -85,9 +80,7 @@ public void setDefaultOptions() { else { final String rndID = MqttUtils.buildRandomClientID(defaultCLIProperties.getClientLength()); identifier = identifierPrefix + rndID; - if (isVerbose()) { - Logger.trace("Created 'identifier': {}", identifier); - } + Logger.trace("Created 'identifier' ({})", identifier); } } diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index 35e9ab2cf..2f0937a21 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -109,7 +109,7 @@ public void run() { // TinyLog configuration Map configurationMap = new HashMap<>(); configurationMap.put("writer", "console"); - configurationMap.put("writer.format", "{tag} {message}"); + configurationMap.put("writer.format", "{tag} {message|indent=4}"); configurationMap.put("writer.level", "off"); if (isDebug()) { configurationMap.put("writer.level", "debug"); } if (isVerbose()) { configurationMap.put("writer.level", "trace"); } @@ -119,9 +119,7 @@ public void run() { setDefaultOptions(); sslConfig = buildSslConfig(); - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); logUnusedOptions(); diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index d4ae3c46b..a59afc842 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -112,9 +112,7 @@ public void run() { setDefaultOptions(); sslConfig = buildSslConfig(); - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); logUnusedOptions(); @@ -163,9 +161,7 @@ public void setDefaultOptions() { super.setDefaultOptions(); if (publishFile == null && defaultCLIProperties.getClientSubscribeOutputFile() != null) { - if (isVerbose()) { - Logger.trace("Setting value of 'toFile' to {}", defaultCLIProperties.getClientSubscribeOutputFile()); - } + Logger.trace("Setting value of 'toFile' to {}", defaultCLIProperties.getClientSubscribeOutputFile()); publishFile = new File(defaultCLIProperties.getClientSubscribeOutputFile()); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java index d1e13e1e7..5e31a1e07 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java @@ -67,9 +67,7 @@ public ContextDisconnectCommand(final @NotNull MqttClientExecutor executor) { @Override public void run() { - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); logUnusedDisconnectOptions(); diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java index e540564f2..6816fadb4 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.Publish; import com.hivemq.cli.converters.*; import com.hivemq.cli.mqtt.MqttClientExecutor; @@ -91,16 +92,15 @@ public ContextPublishCommand(final @NotNull MqttClientExecutor executor) { public void run() { logUnusedOptions(); - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); try { qos = MqttUtils.arrangeQosToMatchTopics(topics, qos); mqttClientExecutor.publish(contextClient, this); } catch (final Exception ex) { - LoggerUtils.logWithCurrentContext(this, ex); + Logger.error(ex); + System.err.println(Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java index 95b197bc7..608eb9a83 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.DefaultCLIProperties; import com.hivemq.cli.commands.Subscribe; import com.hivemq.cli.commands.Unsubscribe; @@ -89,9 +90,7 @@ public ContextSubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecu @Override public void run() { - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); setDefaultOptions(); @@ -106,7 +105,8 @@ public void run() { mqttClientExecutor.subscribe(contextClient, this); } catch (final Exception ex) { - LoggerUtils.logWithCurrentContext(this, ex); + Logger.error(ex); + System.err.println(Throwables.getRootCause(ex).getMessage()); } if (stay) { @@ -114,7 +114,8 @@ public void run() { stay(); } catch (final InterruptedException ex) { - LoggerUtils.logWithCurrentContext(this, ex); + Logger.error(ex); + System.err.println(Throwables.getRootCause(ex).getMessage()); } } } @@ -154,7 +155,6 @@ public void run() { WORKER_THREADS.shutdownNow(); if (!contextClient.getState().isConnectedOrReconnect()) { - Logger.info("{} : Client disconnected", LoggerUtils.getShellContextClientPrefix()); removeContext(); } else { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java index cdc357fef..5877f8965 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java @@ -74,16 +74,14 @@ public void run() { } } - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); final MqttClient client = mqttClientExecutor.getMqttClient(this); if (client != null) { updateContext(client); } else { - Logger.error("Context {}@{} not found", identifier, host); + Logger.debug("Context {}@{} not found", identifier, host); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java index 2f3442e8d..021e8f732 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.Unsubscribe; import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; import com.hivemq.cli.mqtt.MqttClientExecutor; @@ -61,9 +62,7 @@ public ContextUnsubscribeCommand(@NotNull MqttClientExecutor mqttClientExecutor) @Override public void run() { - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); logUnusedUnsubscribeOptions(); @@ -71,7 +70,8 @@ public void run() { mqttClientExecutor.unsubscribe(contextClient, this); } catch (final Exception ex) { - LoggerUtils.logWithCurrentContext(this, ex); + Logger.error(ex); + System.err.println(Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java index 46a70e63c..b1db6abdf 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java @@ -68,9 +68,7 @@ public ListClientsCommand() { @Override public void run() { - if (isVerbose()) { - Logger.trace("Command {}", this); - } + Logger.trace("Command {}", this); final List sortedClientData = getSortedClientData(); diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index d3aab8e9c..6619f3a54 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -17,6 +17,7 @@ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.DefaultCLIProperties; import com.hivemq.cli.MqttCLIMain; import com.hivemq.cli.utils.MqttUtils; @@ -174,13 +175,13 @@ private void interact() { TERMINAL_WRITER.println(shellCommandLine.getUsageMessage()); TERMINAL_WRITER.flush(); - Logger.tag("Shell").info("Using default values from properties file {}:", defaultCLIProperties.getFile().getPath()); - Logger.tag("Shell").info("Host: {}, Port: {}, Mqtt-Version {}, Shell-Debug-Level: {}", + TERMINAL_WRITER.printf("Using default values from properties file %s:\n", defaultCLIProperties.getFile().getPath()); + TERMINAL_WRITER.printf("Host: %s, Port: %d, Mqtt-Version %s, Shell-Debug-Level: %s\n", defaultCLIProperties.getHost(), defaultCLIProperties.getPort(), defaultCLIProperties.getMqttVersion(), defaultCLIProperties.getShellDebugLevel()); - Logger.tag("Shell").info("Writing Logfile to {}", logfilePath); + TERMINAL_WRITER.printf("Writing Logfile to %s\n", logfilePath); String line; while (!exitShell) { @@ -197,18 +198,13 @@ private void interact() { } return; } catch (final Exception ex) { - logOnRightLevels(ex); + Logger.error(ex); + System.err.println(Throwables.getRootCause(ex).getMessage()); } } - } catch (final Throwable t) { - if (VERBOSE) { - Logger.trace(t); - } - else if (DEBUG) { - Logger.debug(t.getMessage()); - } - Logger.error(MqttUtils.getRootCause(t).getMessage()); - + } catch (final Exception ex) { + Logger.error(ex); + System.err.println(Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java index 83ca7eb1f..80a5267db 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java @@ -77,9 +77,7 @@ public void run() { private @Nullable MqttClient connect() { - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); try { return mqttClientExecutor.connect(this); diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java index cc9ac5e8e..715a70069 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java @@ -87,9 +87,7 @@ public void run() { host = defaultCLIProperties.getHost(); } - if (isVerbose()) { - Logger.trace("Command {} ", this); - } + Logger.trace("Command {} ", this); try { if (disconnectAll) { diff --git a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java index d41829201..b3cef2d84 100644 --- a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java @@ -20,6 +20,7 @@ import com.hivemq.cli.commands.cli.PublishCommand; import com.hivemq.cli.commands.cli.SubscribeCommand; import com.hivemq.cli.utils.MqttUtils; +import com.hivemq.client.internal.mqtt.message.connect.MqttConnectRestrictions; import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.MqttClientBuilder; import com.hivemq.client.mqtt.MqttClientState; @@ -148,7 +149,7 @@ public void disconnect(final @NotNull Disconnect disconnect) { } else if (disconnect.isDebug()) { - Logger.debug("client to disconnect is not connected: {} ", clientKey); + Logger.debug("client to disconnect is not connected ({}) ", clientKey); } } @@ -193,12 +194,8 @@ public boolean isConnected(final @NotNull Context context) { public @NotNull MqttClient connect(final @NotNull Connect connect) { if (isConnected(connect)) { - if (connect.isVerbose()) { - Logger.trace("Client is already connected ({})", connect.getKey()); - } else if (connect.isDebug()) { - Logger.debug("Client is already connected"); - } - Logger.info("Using already connected client with key: {}", connect.getKey()); + Logger.debug("Client is already connected ({})", connect.getKey()); + Logger.info("Using already connected ({})", connect.getKey()); return clientKeyToClientData.get(connect.getKey()).getClient(); } @@ -220,28 +217,22 @@ public boolean isConnected(final @NotNull Context context) { final @NotNull Mqtt5ConnectRestrictions connectRestrictions = createMqtt5ConnectRestrictions(connect); final Mqtt5ConnectBuilder connectBuilder = Mqtt5Connect.builder() - .willPublish(willPublish) - .restrictions(connectRestrictions); + .willPublish(willPublish); - if (connect.getCleanStart() != null) { - connectBuilder.cleanStart(connect.getCleanStart()); + // Workaround : if the built connect restrictions are the default ones do not append them to the connect builder + // -> Else the connectMessage.toString() method will flood the logging output + if (!connectRestrictions.equals(Mqtt5ConnectRestrictions.builder().build())) { + connectBuilder.restrictions(connectRestrictions); } - if (connect.getKeepAlive() != null) { - connectBuilder.keepAlive(connect.getKeepAlive()); - } - - if (connect.getSessionExpiryInterval() != null) { - connectBuilder.sessionExpiryInterval(connect.getSessionExpiryInterval()); - } - - if (connect.getConnectUserProperties() != null) { - connectBuilder.userProperties(connect.getConnectUserProperties()); - } + if (connect.getCleanStart() != null) { connectBuilder.cleanStart(connect.getCleanStart()); } + if (connect.getKeepAlive() != null) { connectBuilder.keepAlive(connect.getKeepAlive()); } + if (connect.getSessionExpiryInterval() != null) { connectBuilder.sessionExpiryInterval(connect.getSessionExpiryInterval()); } + if (connect.getConnectUserProperties() != null) { connectBuilder.userProperties(connect.getConnectUserProperties()); } connectBuilder.simpleAuth(buildMqtt5Authentication(connect)); - client.toAsync().publishes(MqttGlobalPublishFilter.REMAINING, buildRemainingMqtt5PublishesCallback(connect)); + client.toAsync().publishes(MqttGlobalPublishFilter.REMAINING, buildRemainingMqtt5PublishesCallback(connect, client)); mqtt5Connect(client, connectBuilder.build(), connect); @@ -273,7 +264,7 @@ public boolean isConnected(final @NotNull Context context) { connectBuilder.simpleAuth(buildMqtt3Authentication(connect)); - client.toAsync().publishes(MqttGlobalPublishFilter.REMAINING, buildRemainingMqtt3PublishesCallback(connect)); + client.toAsync().publishes(MqttGlobalPublishFilter.REMAINING, buildRemainingMqtt3PublishesCallback(connect, client)); mqtt3Connect(client, connectBuilder.build(), connect); @@ -444,34 +435,24 @@ else if (connect.getPassword() != null) { return client; } - @NotNull private Consumer buildRemainingMqtt5PublishesCallback(final @NotNull Connect connect) { + @NotNull private Consumer buildRemainingMqtt5PublishesCallback(final @NotNull Connect connect, final @NotNull Mqtt5Client client) { if (connect instanceof Subscribe) { - return new SubscribeMqtt5PublishCallback((Subscribe) connect); + return new SubscribeMqtt5PublishCallback((Subscribe) connect, client); } else { return mqtt5Publish -> { - if (connect.isVerbose()) { - Logger.trace("received PUBLISH: {}, MESSAGE: '{}'", mqtt5Publish, new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } - else if (connect.isDebug()) { - Logger.debug("received PUBLISH: (Topic: '{}', MESSAGE: '{}')", mqtt5Publish.getTopic(), new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } + Logger.debug("received PUBLISH: {}, MESSAGE: '{}'", mqtt5Publish, new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); }; } } - @NotNull private Consumer buildRemainingMqtt3PublishesCallback(final @NotNull Connect connect) { + @NotNull private Consumer buildRemainingMqtt3PublishesCallback(final @NotNull Connect connect, final @NotNull Mqtt3Client client) { if (connect instanceof Subscribe) { - return new SubscribeMqtt3PublishCallback((Subscribe) connect); + return new SubscribeMqtt3PublishCallback((Subscribe) connect, client); } else { return mqtt3Publish -> { - if (connect.isVerbose()) { - Logger.trace("received PUBLISH: {}, MESSAGE: '{}'", mqtt3Publish, new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } - else if (connect.isDebug()) { - Logger.debug("received PUBLISH: (Topic: '{}', MESSAGE: '{}')", mqtt3Publish.getTopic(), new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } + Logger.debug("received PUBLISH: {}, MESSAGE: '{}'", mqtt3Publish, new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); }; } } diff --git a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java index cba104522..079b3eec0 100644 --- a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java +++ b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java @@ -35,13 +35,7 @@ public void onDisconnected(final @NotNull MqttClientDisconnectedContext context) if (context.getSource() != MqttDisconnectSource.USER) { final Throwable cause = context.getCause(); - if (ShellCommand.VERBOSE) { - Logger.trace("{} {}", LoggerUtils.getClientPrefix(context.getClientConfig()), cause); - } - else if (ShellCommand.DEBUG) { - Logger.debug("{} {}", LoggerUtils.getClientPrefix(context.getClientConfig()), - cause.getMessage()); - } + Logger.debug("{} {}", LoggerUtils.getClientPrefix(context.getClientConfig()), cause); // If the currently active shell client gets disconnected from the server prompt the user to enter if (contextEqualsShellContext(context)) { diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index 8f5d468c6..dc1db1d4b 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.mqtt; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.*; import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; @@ -38,12 +39,10 @@ import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5DisconnectBuilder; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PublishBuilder; -import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PublishResult; import com.hivemq.client.mqtt.mqtt5.message.subscribe.Mqtt5Subscribe; import com.hivemq.client.mqtt.mqtt5.message.subscribe.Mqtt5SubscribeBuilder; import com.hivemq.client.mqtt.mqtt5.message.unsubscribe.Mqtt5Unsubscribe; import com.hivemq.client.mqtt.mqtt5.message.unsubscribe.unsuback.Mqtt5UnsubAck; -import com.hivemq.client.util.TypeSwitch; import org.jetbrains.annotations.NotNull; import javax.inject.Inject; @@ -51,40 +50,25 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import org.bouncycastle.util.encoders.Base64; import org.tinylog.Logger; @Singleton public class MqttClientExecutor extends AbstractMqttClientExecutor { @Inject - MqttClientExecutor() { - } + MqttClientExecutor() {} void mqtt5Connect(final @NotNull Mqtt5Client client, final @NotNull Mqtt5Connect connectMessage, final @NotNull Connect connect) { String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); - if (connect.isVerbose()) { - Logger.trace("{} sending CONNECT {}", - clientLogPrefix, - connectMessage); - } - else if (connect.isDebug()) { - Logger.debug("{} sending CONNECT", clientLogPrefix); - } + Logger.debug("{} sending CONNECT {}", clientLogPrefix, connectMessage); final Mqtt5ConnAck connAck = client .toBlocking() .connect(connectMessage); - if (connect.isVerbose()) { - Logger.trace("{} received CONNACK {} ", clientLogPrefix, connAck); - } - else if (connect.isDebug()) { - Logger.debug("{} received CONNACK ({})", clientLogPrefix, - connAck.getReasonCode()); - } + Logger.debug("{} received CONNACK {} ", clientLogPrefix, connAck); } @@ -92,27 +76,13 @@ void mqtt3Connect(final @NotNull Mqtt3Client client, final @NotNull Mqtt3Connect final String clientLogPrefix = LoggerUtils.getClientPrefix(client.getConfig()); - if (connect.isVerbose()) { - Logger.trace("{} sending CONNECT {}", - clientLogPrefix, - connectMessage); - } - else if (connect.isDebug()) { - Logger.debug("{} sending CONNECT", clientLogPrefix); - } + Logger.debug("{} sending CONNECT {}", clientLogPrefix, connectMessage); final Mqtt3ConnAck connAck = client .toBlocking() .connect(connectMessage); - if (connect.isVerbose()) { - Logger.trace("{} received CONNACK {} ", clientLogPrefix, connAck); - } - else if (connect.isDebug()) { - Logger.debug("{} received CONNACK ({})", clientLogPrefix, - connAck.getReturnCode()); - } - + Logger.debug("{} received CONNACK {} ", clientLogPrefix, connAck); } void mqtt5Subscribe(final @NotNull Mqtt5Client client, final @NotNull Subscribe subscribe, final @NotNull String topic, final @NotNull MqttQos qos) { @@ -130,61 +100,32 @@ void mqtt5Subscribe(final @NotNull Mqtt5Client client, final @NotNull Subscribe final Mqtt5Subscribe subscribeMessage = builder.build(); - if (subscribe.isVerbose()) { - Logger.trace("{} sending SUBSCRIBE {}", - clientLogPrefix, - subscribeMessage); - } - else if (subscribe.isDebug()) { - Logger.debug("{} sending SUBSCRIBE (Topic: {}, QoS: '{}')", - clientLogPrefix, - topic, - qos); - } - + Logger.debug("{} sending SUBSCRIBE {}", clientLogPrefix, subscribeMessage); client.toAsync() - .subscribe(subscribeMessage, new SubscribeMqtt5PublishCallback(subscribe)) + .subscribe(subscribeMessage, new SubscribeMqtt5PublishCallback(subscribe, client)) .whenComplete((subAck, throwable) -> { if (throwable != null) { - if (subscribe.isVerbose()) { - Logger.trace("{} failed SUBSCRIBE to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - } - else if (subscribe.isDebug()) { - Logger.debug("{} failed SUBSCRIBE to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable.getMessage()); - } - Logger.error("{} failed SUBSCRIBE to TOPIC '{}': {}", clientLogPrefix, topic, - MqttUtils.getRootCause(throwable).getMessage()); + throwable); + + System.err.printf("%s failed SUBSCRIBE to TOPIC '%s': %s\n", + clientLogPrefix, + topic, + Throwables.getRootCause(throwable).getMessage()); } else { - final String clientKey = MqttUtils.buildKey(client.getConfig().getClientIdentifier().get().toString(), + final String clientKey = MqttUtils.buildKey( + client.getConfig().getClientIdentifier().get().toString(), client.getConfig().getServerHost()); getClientDataMap().get(clientKey).addSubscription(MqttTopicFilter.of(topic)); - if (subscribe.isVerbose()) { - Logger.trace("{} received SUBACK {}", - clientLogPrefix, - subAck); - } - else if (subscribe.isDebug()) { - Logger.debug("{} received SUBACK ({})", - clientLogPrefix, - subAck.getReasonCodes()); - } - + Logger.debug("{} received SUBACK {}", clientLogPrefix, subAck); } - }) .join(); @@ -201,36 +142,21 @@ void mqtt3Subscribe(final @NotNull Mqtt3Client client, final @NotNull Subscribe final Mqtt3Subscribe subscribeMessage = builder.build(); - if (subscribe.isVerbose()) { - Logger.trace("{} sending SUBSCRIBE {}", clientLogPrefix, subscribeMessage); - } - else if (subscribe.isDebug()) { - Logger.debug("{} sending SUBSCRIBE (Topic: {}, QoS: '{}')", clientLogPrefix, topic, qos); - } - + Logger.debug("{} sending SUBSCRIBE {}", clientLogPrefix, subscribeMessage); client.toAsync() - .subscribe(subscribeMessage, new SubscribeMqtt3PublishCallback(subscribe)) + .subscribe(subscribeMessage, new SubscribeMqtt3PublishCallback(subscribe, client)) .whenComplete((subAck, throwable) -> { if (throwable != null) { - - if (subscribe.isVerbose()) { - Logger.trace("{} failed SUBSCRIBE to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - } - else if (subscribe.isDebug()) { - Logger.debug("{} failed SUBSCRIBE to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable.getMessage()); - } - Logger.error("{} failed SUBSCRIBE to TOPIC '{}': {}", clientLogPrefix, topic, - MqttUtils.getRootCause(throwable).getMessage()); + throwable); + + System.err.printf("%s failed SUBSCRIBE to TOPIC '%s': %s\n", + clientLogPrefix, + topic, + Throwables.getRootCause(throwable).getMessage()); } else { final String clientKey = MqttUtils.buildKey(client.getConfig().getClientIdentifier().get().toString(), @@ -238,13 +164,7 @@ else if (subscribe.isDebug()) { getClientDataMap().get(clientKey).addSubscription(MqttTopicFilter.of(topic)); - if (subscribe.isVerbose()) { - Logger.trace("{} received SUBACK {}", clientLogPrefix, subAck); - } - else if (subscribe.isDebug()) { - Logger.debug("{} received SUBACK ({})", clientLogPrefix, subAck.getReturnCodes()); - } - + Logger.debug("{} received SUBACK {}", clientLogPrefix, subAck); } }) .join(); @@ -275,69 +195,29 @@ void mqtt5Publish(final @NotNull Mqtt5Client client, final @NotNull Publish publ final Mqtt5Publish publishMessage = publishBuilder.build(); - if (publish.isVerbose()) { - Logger.trace("{} sending PUBLISH {}", clientLogPrefix, publishMessage); - } - else if (publish.isDebug()) { - Logger.debug("{} sending PUBLISH (Topic: '{}', QoS: '{}', Message: '{}')", - clientLogPrefix, - topic, - qos, - bufferToString(publish.getMessage())); - } - + Logger.debug("{} sending PUBLISH ('{}') {}", clientLogPrefix, + bufferToString(publish.getMessage()), + publishMessage); client.toAsync() .publish(publishMessage) .whenComplete((publishResult, throwable) -> { if (throwable != null) { - if (publish.isVerbose()) { - Logger.trace("{} failed PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - } - else if (publish.isDebug()) { - Logger.debug("{} failed PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable.getMessage()); - } Logger.error("{} failed PUBLISH to TOPIC '{}': {}", clientLogPrefix, topic, - MqttUtils.getRootCause(throwable).getMessage()); + throwable); + + System.err.printf("%s failed PUBLISH to TOPIC '%s': %s\n", + clientLogPrefix, + topic, + Throwables.getRootCause(throwable).getMessage()); } else { - - if (publish.isVerbose()) { - Logger.trace("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - publishResult); - } - else if (publish.isDebug()) { - - TypeSwitch.when(publishResult) - .is(Mqtt5PublishResult.Mqtt5Qos1Result.class, qos1Result -> { - Logger.debug("{} received PUBACK for PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - qos1Result.getPubAck()); - }) - .is(Mqtt5PublishResult.Mqtt5Qos2Result.class, qos2Result -> { - Logger.debug("{} received PUBREC for PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - qos2Result.getPubRec()); - }) - .is(Mqtt5PublishResult.Mqtt5Qos2CompleteResult.class, qos2CompleteResult -> { - Logger.debug("{} received PUBCOMP for PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - qos2CompleteResult.getPubComp()); - }); - } + Logger.debug("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + publishResult); } }) .join(); @@ -359,58 +239,28 @@ void mqtt3Publish(final @NotNull Mqtt3Client client, final @NotNull Publish publ final Mqtt3Publish publishMessage = publishBuilder.build(); - if (publish.isVerbose()) { - Logger.trace("{} sending PUBLISH {}", clientLogPrefix, publishMessage); - } - else if (publish.isDebug()) { - Logger.debug("{} sending PUBLISH (TOPIC: '{}', QoS: '{}', Message: '{}')", - clientLogPrefix, - topic, - qos, - bufferToString(publish.getMessage())); - } + Logger.debug("{} sending PUBLISH ('{}') {}", clientLogPrefix, bufferToString(publish.getMessage()), publishMessage); client.toAsync().publish(publishMessage) .whenComplete((publishResult, throwable) -> { if (throwable != null) { - if (publish.isVerbose()) { - Logger.trace("{} failed PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - } - else if (publish.isDebug()) { - Logger.debug("{} failed PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable.getMessage()); - } Logger.error("{} failed PUBLISH to TOPIC '{}': {}", clientLogPrefix, topic, - MqttUtils.getRootCause(throwable).getMessage()); + throwable); + + System.err.printf("%s failed PUBLISH to TOPIC '%s': %s\n", + clientLogPrefix, + topic, + Throwables.getRootCause(throwable).getMessage()); } else { - if (publish.isVerbose()) { - Logger.trace("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - publishResult); - } - else if (publish.isDebug()) { - if (publishResult.getQos().equals(MqttQos.AT_LEAST_ONCE)) { - Logger.debug("{} received PUBACK for PUBLISH to TOPIC '{}'", - clientLogPrefix, - topic); - } - else if (publishResult.getQos().equals(MqttQos.EXACTLY_ONCE)) { - Logger.debug("{} received PUBREC for PUBLISH to TOPIC '{}'", - clientLogPrefix, - topic); - } - } + Logger.debug("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", + clientLogPrefix, + topic, + publishResult); } }) .join(); @@ -426,17 +276,9 @@ void mqtt5Unsubscribe(@NotNull final Mqtt5Client client, @NotNull final Unsubscr .topicFilter(topic) .build(); - if (unsubscribe.isVerbose()) { - Logger.trace("{} sending UNSUBSCRIBE {}", + Logger.debug("{} sending UNSUBSCRIBE {}", clientLogPrefix, unsubscribeMessage); - } - else if (unsubscribe.isDebug()) { - Logger.debug("{} sending UNSUBSCRIBE (TOPIC: '{}', userProperties: {})", - clientLogPrefix, - topic, - unsubscribe.getUserProperties()); - } client.toAsync() .unsubscribe(unsubscribeMessage) @@ -444,38 +286,22 @@ else if (unsubscribe.isDebug()) { if (throwable != null) { - - if (unsubscribe.isVerbose()) { - Logger.trace("{} failed UNSUBSCRIBE from TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - } - else if (unsubscribe.isDebug()) { - Logger.debug("{} failed UNSUBSCRIBE from TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable.getMessage()); - } Logger.error("{} failed UNSUBSCRIBE from TOPIC '{}': {}", clientLogPrefix, topic, - MqttUtils.getRootCause(throwable).getMessage()); + throwable); + + System.err.printf("%s failed UNSUBSCRIBE from TOPIC '%s': %s\n", + clientLogPrefix, + topic, + Throwables.getRootCause(throwable).getMessage()); } else { getClientDataMap().get(unsubscribe.getKey()).removeSubscription(MqttTopicFilter.of(topic)); - if (unsubscribe.isVerbose()) { - Logger.trace("{} received UNSUBACK {}", - clientLogPrefix, - unsubAck); - } - else if (unsubscribe.isDebug()) { - Logger.debug("{} received UNSUBACK ({})", - clientLogPrefix, - unsubAck.getReasonCodes()); - } - + Logger.debug("{} received UNSUBACK {}", + clientLogPrefix, + unsubAck); } }) .join(); @@ -492,51 +318,26 @@ void mqtt3Unsubscribe(@NotNull final Mqtt3Client client, @NotNull final Unsubscr .topicFilter(topic) .build(); - if (unsubscribe.isVerbose()) { - Logger.trace("{} Sending UNSUBSCRIBE {}", + Logger.debug("{} Sending UNSUBSCRIBE {}", clientLogPrefix, unsubscribeMessage); - } - else if (unsubscribe.isDebug()) { - Logger.debug("{} Sending UNSUBSCRIBE (TOPIC: '{}', userProperties: {})", - clientLogPrefix, - topic, - unsubscribe.getUserProperties()); - } - client.toAsync() + client.toAsync() .unsubscribe(unsubscribeMessage) .whenComplete((Void unsubAck, Throwable throwable) -> { if (throwable != null) { - if (unsubscribe.isVerbose()) { - Logger.trace("{} failed UNSUBSCRIBE from TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - } - else if (unsubscribe.isDebug()) { - Logger.debug("{} failed UNSUBSCRIBE from TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable.getMessage()); - } Logger.error("{} failed UNSUBSCRIBE from TOPIC '{}': {}", clientLogPrefix, topic, - MqttUtils.getRootCause(throwable).getMessage()); - + throwable); + System.err.printf("%s failed UNSUBSCRIBE from TOPIC '%s': %s\n", + clientLogPrefix, + topic, + Throwables.getRootCause(throwable).getMessage()); } else { - getClientDataMap().get(unsubscribe.getKey()).removeSubscription(MqttTopicFilter.of(topic)); - - if (unsubscribe.isVerbose()) { - Logger.trace("{} received UNSUBACK", clientLogPrefix ); - } - else if (unsubscribe.isDebug()) { - Logger.debug("{} received UNSUBACK", clientLogPrefix); - } - + Logger.debug("{} received UNSUBACK", clientLogPrefix ); } }) .join(); @@ -564,19 +365,9 @@ void mqtt5Disconnect(@NotNull final Mqtt5Client client, @NotNull final Disconnec final Mqtt5Disconnect disconnectMessage = disconnectBuilder.build(); - if (disconnect.isVerbose()) { - Logger.trace("{} sending DISCONNECT {}", clientLogPrefix, disconnectMessage); - } - else if (disconnect.isDebug()) { - Logger.debug("{} sending DISCONNECT (Reason: {}, SessionExpiryInterval: {}, UserProperties: {})", - clientLogPrefix, - disconnect.getReasonString(), - disconnect.getSessionExpiryInterval(), - disconnect.getUserProperties()); - } + Logger.debug("{} sending DISCONNECT {}", clientLogPrefix, disconnectMessage); - client.toBlocking() - .disconnect(disconnectMessage); + client.toBlocking().disconnect(disconnectMessage); } @@ -593,40 +384,9 @@ void mqtt3Disconnect(@NotNull final Mqtt3Client client, @NotNull final Disconnec Logger.warn("User properties were set but are unused in Mqtt version {}", MqttVersion.MQTT_3_1_1); } - if (disconnect.isVerbose()) { - Logger.trace("Sending DISCONNECT with Mqtt3Disconnect: {}", Mqtt3Disconnect.class); - } - else if (disconnect.isDebug()) { - Logger.debug("{} Sending DISCONNECT"); - } - - client.toBlocking() - .disconnect(); - } - - - private @NotNull String applyBase64EncodingIfSet(final boolean encode, final byte[] payload) { - if (encode) { - return Base64.toBase64String(payload); - } else { - return new String(payload); - } - } - - private @NotNull String trimMessage(String p) { - if (p.length() > 10) { - return p.substring(0, 10); - } else { - return p; - } - - } - - private void logFailedPublish(final @NotNull Throwable t, - final @NotNull String topic, - final @NotNull String clientLogPrefix) { - + Logger.debug("Sending DISCONNECT with Mqtt3Disconnect: {}", Mqtt3Disconnect.class); + client.toBlocking().disconnect(); } private @NotNull String bufferToString(ByteBuffer b) { diff --git a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java index 914cf8acf..a79fb190c 100644 --- a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java +++ b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt3PublishCallback.java @@ -18,6 +18,8 @@ import com.hivemq.cli.commands.Subscribe; import com.hivemq.cli.utils.FileUtils; +import com.hivemq.cli.utils.LoggerUtils; +import com.hivemq.client.mqtt.mqtt3.Mqtt3Client; import com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3Publish; import org.bouncycastle.util.encoders.Base64; import org.jetbrains.annotations.NotNull; @@ -31,37 +33,27 @@ public class SubscribeMqtt3PublishCallback implements Consumer { - @NotNull private final String identifier; @Nullable private final File publishFile; private final boolean printToStdout; private final boolean isBase64; - private final boolean debug; - private final boolean verbose; + private final Mqtt3Client client; - SubscribeMqtt3PublishCallback(final @NotNull Subscribe subscribe) { - identifier = subscribe.getIdentifier(); + SubscribeMqtt3PublishCallback(final @NotNull Subscribe subscribe, final @NotNull Mqtt3Client client) { printToStdout = subscribe.isPrintToSTDOUT(); publishFile = subscribe.getPublishFile(); isBase64 = subscribe.isBase64(); - debug = subscribe.isDebug(); - verbose = subscribe.isVerbose(); + this.client = client; } @Override public void accept(final @NotNull Mqtt3Publish mqtt3Publish) { PrintWriter fileWriter = null; - if (publishFile != null) { - fileWriter = FileUtils.createFileAppender(publishFile); - } - - byte[] payload = mqtt3Publish.getPayloadAsBytes(); String payloadMessage = new String(payload); - if (isBase64) { - payloadMessage = Base64.toBase64String(payload); - } + if (publishFile != null) { fileWriter = FileUtils.createFileAppender(publishFile); } + if (isBase64) { payloadMessage = Base64.toBase64String(payload); } if (fileWriter != null) { fileWriter.println(mqtt3Publish.getTopic() + ": " + payloadMessage); @@ -69,22 +61,12 @@ public void accept(final @NotNull Mqtt3Publish mqtt3Publish) { fileWriter.close(); } - if (printToStdout) { - System.out.println(payloadMessage); - } - - if (verbose) { //TODO unified logging - Logger.trace("{} received PUBLISH {}, (message={})", - identifier, - mqtt3Publish, - new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } - else if (debug) { - Logger.debug("{} received PUBLISH (topic={}, message={})", - identifier, - mqtt3Publish.getTopic(), new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } + if (printToStdout) { System.out.println(payloadMessage); } + Logger.debug("{} received PUBLISH ('{}') {}", + LoggerUtils.getClientPrefix(client.getConfig()), + new String(mqtt3Publish.getPayloadAsBytes(), StandardCharsets.UTF_8), + mqtt3Publish); } } diff --git a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java index a03cb03dd..a8f9bc423 100644 --- a/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java +++ b/src/main/java/com/hivemq/cli/mqtt/SubscribeMqtt5PublishCallback.java @@ -18,6 +18,8 @@ import com.hivemq.cli.commands.Subscribe; import com.hivemq.cli.utils.FileUtils; +import com.hivemq.cli.utils.LoggerUtils; +import com.hivemq.client.mqtt.mqtt5.Mqtt5Client; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish; import org.bouncycastle.util.encoders.Base64; import org.jetbrains.annotations.NotNull; @@ -31,37 +33,27 @@ public class SubscribeMqtt5PublishCallback implements Consumer { - @NotNull private final String identifier; @Nullable private final File publishFile; private final boolean printToStdout; private final boolean isBase64; - private final boolean debug; - private final boolean verbose; + private final Mqtt5Client client; - SubscribeMqtt5PublishCallback(final @NotNull Subscribe subscribe) { - identifier = subscribe.getIdentifier(); + SubscribeMqtt5PublishCallback(final @NotNull Subscribe subscribe, final @NotNull Mqtt5Client client) { printToStdout = subscribe.isPrintToSTDOUT(); publishFile = subscribe.getPublishFile(); isBase64 = subscribe.isBase64(); - debug = subscribe.isDebug(); - verbose = subscribe.isVerbose(); + this.client = client; } @Override public void accept(final @NotNull Mqtt5Publish mqtt5Publish) { PrintWriter fileWriter = null; - if (publishFile != null) { - fileWriter = FileUtils.createFileAppender(publishFile); - } - - byte[] payload = mqtt5Publish.getPayloadAsBytes(); String payloadMessage = new String(payload); - if (isBase64) { - payloadMessage = Base64.toBase64String(payload); - } + if (publishFile != null) { fileWriter = FileUtils.createFileAppender(publishFile); } + if (isBase64) { payloadMessage = Base64.toBase64String(payload); } if (fileWriter != null) { fileWriter.println(mqtt5Publish.getTopic() + ": " + payloadMessage); @@ -69,16 +61,12 @@ public void accept(final @NotNull Mqtt5Publish mqtt5Publish) { fileWriter.close(); } - if (printToStdout) { - System.out.println(payloadMessage); - } + if (printToStdout) { System.out.println(payloadMessage); } - if (verbose) { - Logger.trace("{} received PUBLISH {} (topic={})", identifier, mqtt5Publish, new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } - else if (debug) { - Logger.debug("{} received PUBLISH (topic={}, message={})", identifier, mqtt5Publish.getTopic(), new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8)); - } + Logger.debug("{} received PUBLISH ('{}') {}", + LoggerUtils.getClientPrefix(client.getConfig()), + new String(mqtt5Publish.getPayloadAsBytes(), StandardCharsets.UTF_8), + mqtt5Publish); } From a1ff098790de85d7c8b5c3fc7ec4607681cbdf7e Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Thu, 12 Dec 2019 13:34:47 +0100 Subject: [PATCH 13/20] minify logging --- .../cli/commands/AbstractCommonFlags.java | 21 +++------- .../hivemq/cli/commands/MqttCLICommand.java | 4 +- .../cli/commands/cli/PublishCommand.java | 14 ++----- .../cli/commands/cli/SubscribeCommand.java | 13 ++---- .../shell/ContextDisconnectCommand.java | 3 +- .../commands/shell/ContextPublishCommand.java | 4 +- .../shell/ContextSubscribeCommand.java | 7 +--- .../commands/shell/ContextSwitchCommand.java | 5 ++- .../shell/ContextUnsubscribeCommand.java | 3 +- .../cli/commands/shell/ShellCommand.java | 32 ++++++-------- .../commands/shell/ShellConnectCommand.java | 3 +- .../shell/ShellDisconnectCommand.java | 3 +- .../cli/mqtt/AbstractMqttClientExecutor.java | 5 +-- .../mqtt/ContextClientDisconnectListener.java | 8 ++-- .../hivemq/cli/mqtt/MqttClientExecutor.java | 42 +++---------------- .../java/com/hivemq/cli/utils/FileUtils.java | 4 +- .../com/hivemq/cli/utils/LoggerUtils.java | 10 ----- 17 files changed, 51 insertions(+), 130 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java index 648a97d62..01565d0da 100644 --- a/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java +++ b/src/main/java/com/hivemq/cli/commands/AbstractCommonFlags.java @@ -112,8 +112,7 @@ public void setDefaultOptions() { try { password = defaultCLIProperties.getPassword(); } catch (Exception e) { - Logger.error(e); - System.err.printf("Default password could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); + Logger.error(e,"Default password could not be loaded ({})", Throwables.getRootCause(e).getMessage()); } } @@ -121,8 +120,7 @@ public void setDefaultOptions() { try { clientCertificate = defaultCLIProperties.getClientCertificate(); } catch (Exception e) { - Logger.error(e); - System.err.printf("Default client certificate could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); + Logger.error(e,"Default client certificate could not be loaded ({})", Throwables.getRootCause(e).getMessage()); } } @@ -130,8 +128,7 @@ public void setDefaultOptions() { try { clientPrivateKey = defaultCLIProperties.getClientPrivateKey(); } catch (Exception e) { - Logger.error(e); - System.err.printf("Default client private key could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); + Logger.error(e,"Default client private key could not be loaded ({})", Throwables.getRootCause(e).getMessage()); } } @@ -145,8 +142,7 @@ public void setDefaultOptions() { certificates.add(defaultServerCertificate); } } catch (Exception e) { - Logger.error(e); - System.err.printf("Default server certificate could not be loaded (%s)\n", Throwables.getRootCause(e).getMessage()); + Logger.error(e,"Default server certificate could not be loaded ({})", Throwables.getRootCause(e).getMessage()); } } @@ -159,8 +155,7 @@ public void setDefaultOptions() { return doBuildSslConfig(); } catch (Exception e) { - Logger.error(e); - System.err.println(Throwables.getRootCause(e).getMessage()); + Logger.error(e, Throwables.getRootCause(e).getMessage()); } } @@ -280,12 +275,6 @@ public String commonOptions() { getWillOptions(); } - // GETTER AND SETTER - - public void setUseSsl(final boolean useSsl) { - this.useSsl = useSsl; - } - @Nullable public String getUser() { return user; diff --git a/src/main/java/com/hivemq/cli/commands/MqttCLICommand.java b/src/main/java/com/hivemq/cli/commands/MqttCLICommand.java index 9619f7393..394b41999 100644 --- a/src/main/java/com/hivemq/cli/commands/MqttCLICommand.java +++ b/src/main/java/com/hivemq/cli/commands/MqttCLICommand.java @@ -36,9 +36,7 @@ public class MqttCLICommand { public static final @NotNull String VERSION_STRING = "1.0"; - @Inject - MqttCLICommand() { - } + MqttCLICommand() { } } diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index 2f0937a21..4085083c4 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -22,12 +22,10 @@ import com.hivemq.cli.converters.*; import com.hivemq.cli.impl.MqttAction; import com.hivemq.cli.mqtt.MqttClientExecutor; -import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; -import com.hivemq.client.mqtt.exceptions.ConnectionFailedException; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PayloadFormatIndicator; @@ -57,14 +55,11 @@ public class PublishCommand extends AbstractConnectFlags implements MqttAction, private MqttClientSslConfig sslConfig; //needed for pico cli - reflection code generation - public PublishCommand() { - this(null); - } + public PublishCommand() { this(null); } @Inject public PublishCommand(final @NotNull MqttClientExecutor mqttClientExecutor) { this.mqttClientExecutor = mqttClientExecutor; - } @CommandLine.Option(names = {"--version"}, versionHelp = true, description = "display version info") @@ -109,8 +104,8 @@ public void run() { // TinyLog configuration Map configurationMap = new HashMap<>(); configurationMap.put("writer", "console"); - configurationMap.put("writer.format", "{tag} {message|indent=4}"); - configurationMap.put("writer.level", "off"); + configurationMap.put("writer.format", "{message-only}"); + configurationMap.put("writer.level", "warn"); if (isDebug()) { configurationMap.put("writer.level", "debug"); } if (isVerbose()) { configurationMap.put("writer.level", "trace"); } @@ -128,8 +123,7 @@ public void run() { mqttClientExecutor.publish(this); } catch (final Exception ex) { - Logger.error(ex.getMessage()); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index a59afc842..6e01d630a 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -102,8 +102,8 @@ public void run() { // TinyLog configuration Map configurationMap = new HashMap<>(); configurationMap.put("writer", "console"); - configurationMap.put("writer.format", "{tag} {message}"); - configurationMap.put("writer.level", "off"); + configurationMap.put("writer.format", "{message-only}"); + configurationMap.put("writer.level", "warn"); if (isDebug()) { configurationMap.put("writer.level", "debug"); } if (isVerbose()) { configurationMap.put("writer.level", "trace"); } @@ -121,8 +121,7 @@ public void run() { subscribeClient = mqttClientExecutor.subscribe(this); } catch (final Exception ex) { - Logger.error(ex.getMessage()); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); return; } @@ -130,8 +129,7 @@ public void run() { stay(); } catch (final InterruptedException ex) { - Logger.error(ex.getMessage()); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } @@ -151,9 +149,6 @@ private void stay() throws InterruptedException { while (subscribeClient.getState().isConnectedOrReconnect()) { Thread.sleep(IDLE_TIME); } - if (isVerbose()) { - Logger.trace("Client disconnected"); - } } @Override diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java index 5e31a1e07..d29a15e0a 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextDisconnectCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.Disconnect; import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; import com.hivemq.cli.converters.UnsignedIntConverter; @@ -80,7 +81,7 @@ public void run() { } } catch (final Exception ex) { - LoggerUtils.logWithCurrentContext(this, ex); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java index 6816fadb4..f75ead076 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextPublishCommand.java @@ -99,12 +99,10 @@ public void run() { mqttClientExecutor.publish(contextClient, this); } catch (final Exception ex) { - Logger.error(ex); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } - //TODO private void logUnusedOptions() { if (contextClient.getConfig().getMqttVersion() == MqttVersion.MQTT_3_1_1) { if (messageExpiryInterval != null) { diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java index 608eb9a83..9af349358 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSubscribeCommand.java @@ -23,7 +23,6 @@ import com.hivemq.cli.converters.Mqtt5UserPropertyConverter; import com.hivemq.cli.converters.MqttQosConverter; import com.hivemq.cli.mqtt.MqttClientExecutor; -import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; @@ -105,8 +104,7 @@ public void run() { mqttClientExecutor.subscribe(contextClient, this); } catch (final Exception ex) { - Logger.error(ex); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } if (stay) { @@ -114,8 +112,7 @@ public void run() { stay(); } catch (final InterruptedException ex) { - Logger.error(ex); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java index 5877f8965..5c27dc8b7 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextSwitchCommand.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.commands.shell; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.Context; import com.hivemq.cli.mqtt.MqttClientExecutor; import com.hivemq.client.mqtt.MqttClient; @@ -69,7 +70,7 @@ public void run() { extractKeyFromContextName(contextName); } catch (final IllegalArgumentException ex) { - Logger.error(ex.getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); return; } } @@ -81,7 +82,7 @@ public void run() { if (client != null) { updateContext(client); } else { - Logger.debug("Context {}@{} not found", identifier, host); + Logger.error("Context {}@{} not found", identifier, host); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java index 021e8f732..5845e9be6 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ContextUnsubscribeCommand.java @@ -70,8 +70,7 @@ public void run() { mqttClientExecutor.unsubscribe(contextClient, this); } catch (final Exception ex) { - Logger.error(ex); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index 6619f3a54..969e7a8d7 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -124,20 +124,26 @@ public void run() { String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{tag}|min-size=10} | {{level}|min-size=7} | {message}"; if (isVerbose() || isDebug()) { - logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{level}|min-size=7} | {{class-name}.{method}:{line}|min-size=20} | {{tag}|min-size=10} | {message}"; + logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{level}|min-size=7} | {{class-name}.{method}:{line}|min-size=20} | {message}"; } - // TinyLog configuration + // File Writer (creates logfiles under .mqtt-cli/logs folder) Map configurationMap = new HashMap<>(); configurationMap.put("writer1", "file"); configurationMap.put("writer1.format", logfileFormatPattern); configurationMap.put("writer1.file", logfilePath); configurationMap.put("writer1.append", "true"); configurationMap.put("writer1.level", "off"); + configurationMap.put("writer1.tag", "-"); if (isDebug()) { configurationMap.put("writer1.level", "debug"); } if (isVerbose()) { configurationMap.put("writer1.level", "trace"); } + // Console Writer (tagged with "CONSOLE" throughout the application) + configurationMap.put("writer2", "console"); + configurationMap.put("writer2.format", "{message-only}"); + configurationMap.put("writer2.level", "warn"); + Configuration.replace(configurationMap); logfilePath = Configuration.get("writer1.file"); @@ -183,6 +189,8 @@ private void interact() { defaultCLIProperties.getShellDebugLevel()); TERMINAL_WRITER.printf("Writing Logfile to %s\n", logfilePath); + Logger.info("--- Shell-Mode started ---"); + String line; while (!exitShell) { try { @@ -193,18 +201,14 @@ private void interact() { currentCommandLine.execute(arguments); } } catch (final UserInterruptException e) { - if (VERBOSE) { - Logger.trace("User interrupted shell: {}", e); - } + Logger.trace("User interrupted shell: {}", e); return; } catch (final Exception ex) { - Logger.error(ex); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } } catch (final Exception ex) { - Logger.error(ex); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } @@ -237,16 +241,6 @@ static void readFromShell() { .toAnsi(); } - private static void logOnRightLevels(final @NotNull Exception ex) { - if (VERBOSE) { - Logger.trace(ex); - } - else if (DEBUG) { - Logger.debug(ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); - } - static void usage(Object command) { currentCommandLine.usage(command, System.out); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java index 80a5267db..6153675ba 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java @@ -83,8 +83,7 @@ public void run() { return mqttClientExecutor.connect(this); } catch (final Exception ex) { - Logger.error(ex); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } return null; } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java index 715a70069..6d9216050 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellDisconnectCommand.java @@ -103,8 +103,7 @@ public void run() { } } catch (final Exception ex) { - Logger.error(ex.getMessage()); - System.err.println(Throwables.getRootCause(ex).getMessage()); + Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java index b3cef2d84..186cad3f7 100644 --- a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java @@ -148,10 +148,7 @@ public void disconnect(final @NotNull Disconnect disconnect) { clientKeyToClientData.remove(clientKey); } - else if (disconnect.isDebug()) { - Logger.debug("client to disconnect is not connected ({}) ", clientKey); - } - + Logger.error("client to disconnect is not connected ({}) ", clientKey); } public void disconnectAllClients(final @NotNull Disconnect disconnect) { diff --git a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java index 079b3eec0..2359a16f4 100644 --- a/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java +++ b/src/main/java/com/hivemq/cli/mqtt/ContextClientDisconnectListener.java @@ -16,6 +16,7 @@ */ package com.hivemq.cli.mqtt; +import com.google.common.base.Throwables; import com.hivemq.cli.commands.shell.ShellCommand; import com.hivemq.cli.commands.shell.ShellContextCommand; import com.hivemq.cli.utils.LoggerUtils; @@ -35,11 +36,12 @@ public void onDisconnected(final @NotNull MqttClientDisconnectedContext context) if (context.getSource() != MqttDisconnectSource.USER) { final Throwable cause = context.getCause(); - Logger.debug("{} {}", LoggerUtils.getClientPrefix(context.getClientConfig()), cause); + Logger.debug(cause, "{} DISCONNECTED {}", LoggerUtils.getClientPrefix(context.getClientConfig()), + Throwables.getRootCause(cause).getMessage()); // If the currently active shell client gets disconnected from the server prompt the user to enter if (contextEqualsShellContext(context)) { - Logger.error(MqttUtils.getRootCause(cause).getMessage()); + Logger.error(cause, Throwables.getRootCause(cause).getMessage()); ShellContextCommand.removeContext(); ShellCommand.TERMINAL_WRITER.printf("Press ENTER to resume: "); ShellCommand.TERMINAL_WRITER.flush(); @@ -50,10 +52,8 @@ else if (contextEqualsShellContext(context)){ } MqttClientExecutor.getClientDataMap().remove(getKeyFromConfig(context.getClientConfig())); - } - private String getKeyFromConfig(final @NotNull MqttClientConfig clientConfig) { return MqttUtils.buildKey(clientConfig.getClientIdentifier().get().toString(), clientConfig.getServerHost()); } diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index dc1db1d4b..e4fb262a6 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -107,12 +107,7 @@ void mqtt5Subscribe(final @NotNull Mqtt5Client client, final @NotNull Subscribe .whenComplete((subAck, throwable) -> { if (throwable != null) { - Logger.error("{} failed SUBSCRIBE to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - - System.err.printf("%s failed SUBSCRIBE to TOPIC '%s': %s\n", + Logger.error(throwable,"{} failed SUBSCRIBE to TOPIC '{}': {}", clientLogPrefix, topic, Throwables.getRootCause(throwable).getMessage()); @@ -148,12 +143,7 @@ void mqtt3Subscribe(final @NotNull Mqtt3Client client, final @NotNull Subscribe .subscribe(subscribeMessage, new SubscribeMqtt3PublishCallback(subscribe, client)) .whenComplete((subAck, throwable) -> { if (throwable != null) { - Logger.error("{} failed SUBSCRIBE to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - - System.err.printf("%s failed SUBSCRIBE to TOPIC '%s': %s\n", + Logger.error(throwable, "{} failed SUBSCRIBE to TOPIC '{}': {}", clientLogPrefix, topic, Throwables.getRootCause(throwable).getMessage()); @@ -203,12 +193,7 @@ void mqtt5Publish(final @NotNull Mqtt5Client client, final @NotNull Publish publ .publish(publishMessage) .whenComplete((publishResult, throwable) -> { if (throwable != null) { - Logger.error("{} failed PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - - System.err.printf("%s failed PUBLISH to TOPIC '%s': %s\n", + Logger.error(throwable,"{} failed PUBLISH to TOPIC '{}': {}", clientLogPrefix, topic, Throwables.getRootCause(throwable).getMessage()); @@ -245,16 +230,10 @@ void mqtt3Publish(final @NotNull Mqtt3Client client, final @NotNull Publish publ .whenComplete((publishResult, throwable) -> { if (throwable != null) { - Logger.error("{} failed PUBLISH to TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - - System.err.printf("%s failed PUBLISH to TOPIC '%s': %s\n", + Logger.error(throwable, "{} failed PUBLISH to TOPIC '{}': {}", clientLogPrefix, topic, Throwables.getRootCause(throwable).getMessage()); - } else { Logger.debug("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", @@ -286,12 +265,7 @@ void mqtt5Unsubscribe(@NotNull final Mqtt5Client client, @NotNull final Unsubscr if (throwable != null) { - Logger.error("{} failed UNSUBSCRIBE from TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - - System.err.printf("%s failed UNSUBSCRIBE from TOPIC '%s': %s\n", + Logger.error(throwable,"{} failed UNSUBSCRIBE from TOPIC '{}': {}", clientLogPrefix, topic, Throwables.getRootCause(throwable).getMessage()); @@ -327,11 +301,7 @@ void mqtt3Unsubscribe(@NotNull final Mqtt3Client client, @NotNull final Unsubscr .whenComplete((Void unsubAck, Throwable throwable) -> { if (throwable != null) { - Logger.error("{} failed UNSUBSCRIBE from TOPIC '{}': {}", - clientLogPrefix, - topic, - throwable); - System.err.printf("%s failed UNSUBSCRIBE from TOPIC '%s': %s\n", + Logger.error(throwable, "{} failed UNSUBSCRIBE from TOPIC '{}': {}", clientLogPrefix, topic, Throwables.getRootCause(throwable).getMessage()); diff --git a/src/main/java/com/hivemq/cli/utils/FileUtils.java b/src/main/java/com/hivemq/cli/utils/FileUtils.java index de346ca8e..fbfaeb9d5 100644 --- a/src/main/java/com/hivemq/cli/utils/FileUtils.java +++ b/src/main/java/com/hivemq/cli/utils/FileUtils.java @@ -31,7 +31,7 @@ public static PrintWriter createFileAppender(@NotNull File file) { try { out = new FileOutputStream(file, true); } catch (final FileNotFoundException e) { - Logger.error("Could not open file: {} ", file.getName(), e.getMessage()); + Logger.error(e,"Could not open file ({}) ", file.getName(), e.getMessage()); } } else { // file has to be created @@ -39,7 +39,7 @@ public static PrintWriter createFileAppender(@NotNull File file) { try { out = new FileOutputStream(file); } catch (final FileNotFoundException e) { - Logger.error("Could not create file: {} ", file.getName(), e.getMessage()); + Logger.error(e, "Could not create file ({}) ", file.getName(), e.getMessage()); } } diff --git a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java index 92f4980f3..f5c16e1f5 100644 --- a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java +++ b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java @@ -29,16 +29,6 @@ public class LoggerUtils { - public static void logWithCurrentContext(final @NotNull CliCommand cmd, final @NotNull Exception ex) { - if (cmd.isVerbose()) { - Logger.trace("{} : ", getShellContextClientPrefix(), ex); - } - else if (cmd.isDebug()) { - Logger.debug("{} : ", getShellContextClientPrefix(), ex.getMessage()); - } - Logger.error(MqttUtils.getRootCause(ex).getMessage()); - } - public static String getShellContextClientPrefix() { if (ShellContextCommand.contextClient != null) { final MqttClientConfig config = ShellContextCommand.contextClient.getConfig(); From f8a2df7acf396e80c37f678411d6d374f7cc3c20 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Fri, 13 Dec 2019 14:47:17 +0100 Subject: [PATCH 14/20] update to 1.1.3 client version --- README.md | 2 +- build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 33f249495..0f1a66878 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ [![Build Status](https://travis-ci.com/hivemq/mqtt-cli.svg?branch=develop)](https://travis-ci.com/hivemq/mqtt-cli) [![picocli](https://img.shields.io/github/downloads/hivemq/mqtt-cli/total)](https://github.com/hivemq/mqtt-cli/releases) [![picocli](https://img.shields.io/github/license/hivemq/mqtt-cli)](https://github.com/hivemq/mqtt-cli/blob/develop/LICENSE) -[![picocli](https://img.shields.io/badge/hivemq--mqtt--client-1.1.1-green)](https://github.com/hivemq/hivemq-mqtt-client) +[![picocli](https://img.shields.io/badge/hivemq--mqtt--client-1.1.3-green)](https://github.com/hivemq/hivemq-mqtt-client) [![picocli](https://img.shields.io/badge/picocli-4.0.4-green.svg)](https://github.com/remkop/picocli) MQTT 5.0 and 3.1.1 compatible and feature-rich MQTT Command Line Interface diff --git a/build.gradle b/build.gradle index 21f7909be..7d24eef19 100644 --- a/build.gradle +++ b/build.gradle @@ -120,7 +120,7 @@ ext { jline3JansiVersion = '3.12.1' daggerVersion = '2.21' guavaVersion ='27.0.1-jre' - hivemqclientVersion = '1.1.1' + hivemqclientVersion = '1.1.3' tinylogVersion = '2.0.1' jcToolsVersion = '2.1.2' jetbrainsAnnotationsVersion = '17.0.0' From a974618f5c930e18cd61c29b90f1cd867f2aac69 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Fri, 13 Dec 2019 16:38:55 +0100 Subject: [PATCH 15/20] also log pub/sub commands to logfile change properties name 'debug.level.shell' to 'logfile.level' --- .../com/hivemq/cli/DefaultCLIProperties.java | 14 ++-- .../cli/commands/cli/PublishCommand.java | 18 ++--- .../cli/commands/cli/SubscribeCommand.java | 17 ++--- .../cli/commands/shell/ShellCommand.java | 68 +++---------------- .../com/hivemq/cli/utils/LoggerUtils.java | 52 ++++++++++---- .../hivemq/cli/DefaultCLIPropertiesTest.java | 6 +- .../PropertyFiles/override.properties | 2 +- 7 files changed, 80 insertions(+), 97 deletions(-) diff --git a/src/main/java/com/hivemq/cli/DefaultCLIProperties.java b/src/main/java/com/hivemq/cli/DefaultCLIProperties.java index 26e8a4d72..541a59875 100644 --- a/src/main/java/com/hivemq/cli/DefaultCLIProperties.java +++ b/src/main/java/com/hivemq/cli/DefaultCLIProperties.java @@ -49,7 +49,7 @@ public class DefaultCLIProperties { private static final String MQTT_VERSION = "mqtt.version"; private static final String HOST = "mqtt.host"; private static final String PORT = "mqtt.port"; - private static final String DEBUG_LEVEL_SHELL = "debug.level.shell"; + private static final String LOGFILE_DEBUG_LEVEL = "logfile.level"; private static final String CLIENT_ID_PREFIX = "client.id.prefix"; private static final String CLIENT_ID_LENGTH = "client.id.length"; private static final String SUBSCRIBE_OUTPUT_FILE = "client.subscribe.output"; @@ -67,7 +67,7 @@ public class DefaultCLIProperties { put(MQTT_VERSION, "5"); put(HOST, "localhost"); put(PORT, "1883"); - put(DEBUG_LEVEL_SHELL, "verbose"); + put(LOGFILE_DEBUG_LEVEL, "debug"); put(CLIENT_ID_PREFIX, "mqtt"); put(CLIENT_ID_LENGTH, "8"); put(SUBSCRIBE_OUTPUT_FILE, null); @@ -181,16 +181,18 @@ public int getPort() { } @NotNull - public Level getShellDebugLevel() { - final String shellDebugLevel = propertyToValue.get(DEBUG_LEVEL_SHELL); - switch (shellDebugLevel.toLowerCase()) { + public Level getLogfileDebugLevel() { + final String debugLevel = propertyToValue.get(LOGFILE_DEBUG_LEVEL); + switch (debugLevel.toLowerCase()) { case "trace": case "verbose": return Level.TRACE; case "debug": return Level.DEBUG; case "info": return Level.INFO; + case "warn": return Level.WARN; + case "error": return Level.ERROR; } - throw new IllegalArgumentException("'" + shellDebugLevel + "' is not a valid debug level"); + throw new IllegalArgumentException("'" + debugLevel + "' is not a valid debug level"); } @NotNull diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index 4085083c4..613eaf6d9 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -22,6 +22,7 @@ import com.hivemq.cli.converters.*; import com.hivemq.cli.impl.MqttAction; import com.hivemq.cli.mqtt.MqttClientExecutor; +import com.hivemq.cli.utils.LoggerUtils; import com.hivemq.cli.utils.MqttUtils; import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; @@ -102,14 +103,15 @@ public PublishCommand(final @NotNull MqttClientExecutor mqttClientExecutor) { public void run() { // TinyLog configuration - Map configurationMap = new HashMap<>(); - configurationMap.put("writer", "console"); - configurationMap.put("writer.format", "{message-only}"); - configurationMap.put("writer.level", "warn"); - if (isDebug()) { configurationMap.put("writer.level", "debug"); } - if (isVerbose()) { configurationMap.put("writer.level", "trace"); } - - Configuration.replace(configurationMap); + Map configurationMap = new HashMap() {{ + put("writer1", "console"); + put("writer1.format", "{message-only}"); + put("writer1.level", "warn"); + if (isDebug()) put("writer1.level", "debug"); + if (isVerbose()) put("writer1.level", "trace"); + }}; + + LoggerUtils.useDefaultLogging(configurationMap); setDefaultOptions(); sslConfig = buildSslConfig(); diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index 6e01d630a..cf757df00 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -100,14 +100,15 @@ public SubscribeCommand(final @NotNull MqttClientExecutor mqttClientExecutor, public void run() { // TinyLog configuration - Map configurationMap = new HashMap<>(); - configurationMap.put("writer", "console"); - configurationMap.put("writer.format", "{message-only}"); - configurationMap.put("writer.level", "warn"); - if (isDebug()) { configurationMap.put("writer.level", "debug"); } - if (isVerbose()) { configurationMap.put("writer.level", "trace"); } - - Configuration.replace(configurationMap); + Map configurationMap = new HashMap() {{ + put("writer1", "console"); + put("writer1.format", "{message-only}"); + put("writer1.level", "warn"); + if (isDebug()) put("writer1.level", "debug"); + if (isVerbose()) put("writer1.level", "trace"); + }}; + + LoggerUtils.useDefaultLogging(configurationMap); setDefaultOptions(); sslConfig = buildSslConfig(); diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index 969e7a8d7..d73879eb3 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -20,7 +20,7 @@ import com.google.common.base.Throwables; import com.hivemq.cli.DefaultCLIProperties; import com.hivemq.cli.MqttCLIMain; -import com.hivemq.cli.utils.MqttUtils; +import com.hivemq.cli.utils.LoggerUtils; import org.jetbrains.annotations.NotNull; import org.jline.reader.*; import org.jline.reader.impl.DefaultParser; @@ -29,19 +29,13 @@ import org.jline.terminal.TerminalBuilder; import org.jline.utils.AttributedStringBuilder; import org.jline.utils.AttributedStyle; -import org.tinylog.Level; import org.tinylog.Logger; import org.tinylog.configuration.Configuration; import picocli.CommandLine; import picocli.shell.jline3.PicocliJLineCompleter; -import sun.security.krb5.Config; import javax.inject.Inject; -import java.io.File; import java.io.PrintWriter; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -96,57 +90,15 @@ public class ShellCommand implements Runnable { @Override public void run() { - final String dir = defaultCLIProperties.getLogfilePath(); - - final Level debugLevel = defaultCLIProperties.getShellDebugLevel(); - switch (debugLevel) { - case TRACE: - VERBOSE = true; - DEBUG = false; - break; - case DEBUG: - VERBOSE = false; - DEBUG = true; - break; - case INFO: - VERBOSE = false; - DEBUG = false; - break; - } - - final File dirFile = new File(dir); - dirFile.mkdirs(); - - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date date = new Date(); - - logfilePath = dir + "mqtt_cli_" + dateFormat.format(date) + ".log"; - - String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{tag}|min-size=10} | {{level}|min-size=7} | {message}"; - if (isVerbose() || isDebug()) { - logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {{level}|min-size=7} | {{class-name}.{method}:{line}|min-size=20} | {message}"; - } - - // TinyLog configuration - // File Writer (creates logfiles under .mqtt-cli/logs folder) - Map configurationMap = new HashMap<>(); - configurationMap.put("writer1", "file"); - configurationMap.put("writer1.format", logfileFormatPattern); - configurationMap.put("writer1.file", logfilePath); - configurationMap.put("writer1.append", "true"); - configurationMap.put("writer1.level", "off"); - configurationMap.put("writer1.tag", "-"); - if (isDebug()) { configurationMap.put("writer1.level", "debug"); } - if (isVerbose()) { configurationMap.put("writer1.level", "trace"); } - - // Console Writer (tagged with "CONSOLE" throughout the application) - configurationMap.put("writer2", "console"); - configurationMap.put("writer2.format", "{message-only}"); - configurationMap.put("writer2.level", "warn"); + Map configurationMap = new HashMap() {{ + put("writer1", "console"); + put("writer1.format", "{message-only}"); + put("writer1.level", "warn"); + }}; - Configuration.replace(configurationMap); + LoggerUtils.useDefaultLogging(configurationMap); - logfilePath = Configuration.get("writer1.file"); + logfilePath = Configuration.get("writer.file"); interact(); } @@ -182,11 +134,11 @@ private void interact() { TERMINAL_WRITER.flush(); TERMINAL_WRITER.printf("Using default values from properties file %s:\n", defaultCLIProperties.getFile().getPath()); - TERMINAL_WRITER.printf("Host: %s, Port: %d, Mqtt-Version %s, Shell-Debug-Level: %s\n", + TERMINAL_WRITER.printf("Host: %s, Port: %d, Mqtt-Version %s, Logfile-Debug-Level: %s\n", defaultCLIProperties.getHost(), defaultCLIProperties.getPort(), defaultCLIProperties.getMqttVersion(), - defaultCLIProperties.getShellDebugLevel()); + defaultCLIProperties.getLogfileDebugLevel()); TERMINAL_WRITER.printf("Writing Logfile to %s\n", logfilePath); Logger.info("--- Shell-Mode started ---"); diff --git a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java index f5c16e1f5..7a78257a8 100644 --- a/src/main/java/com/hivemq/cli/utils/LoggerUtils.java +++ b/src/main/java/com/hivemq/cli/utils/LoggerUtils.java @@ -16,27 +16,53 @@ */ package com.hivemq.cli.utils; -import com.google.common.base.Throwables; -import com.hivemq.cli.commands.CliCommand; -import com.hivemq.cli.commands.shell.ShellContextCommand; +import com.hivemq.cli.DefaultCLIProperties; +import com.hivemq.cli.MqttCLIMain; import com.hivemq.client.mqtt.MqttClientConfig; import com.hivemq.client.mqtt.datatypes.MqttClientIdentifier; import org.jetbrains.annotations.NotNull; -import org.tinylog.Logger; +import org.jetbrains.annotations.Nullable; +import org.tinylog.Level; +import org.tinylog.configuration.Configuration; -import java.util.Objects; -import java.util.Optional; +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; public class LoggerUtils { - public static String getShellContextClientPrefix() { - if (ShellContextCommand.contextClient != null) { - final MqttClientConfig config = ShellContextCommand.contextClient.getConfig(); - return getClientPrefix(config); - } - else { - return ""; + public static void useDefaultLogging(@Nullable final Map extendedProperties) { + final DefaultCLIProperties defaultCLIProperties = MqttCLIMain.MQTTCLI.defaultCLIProperties(); + final String dir = defaultCLIProperties.getLogfilePath(); + final Level logLevel = defaultCLIProperties.getLogfileDebugLevel(); + final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + final Date date = new Date(); + final String logfilePath = dir + "mqtt_cli_" + dateFormat.format(date) + ".log"; + final String logfileFormatPattern = "{date: yyyy-MM-dd HH:mm:ss} | {pid} | {{level}|min-size=5} | {message}"; + final File dirFile = new File(dir); + + dirFile.mkdirs(); + + // TinyLog configuration + // File Writer (creates logfiles under .mqtt-cli/logs folder) + Map configurationMap = new HashMap() {{ + put("writer", "file"); + put("writer.format", logfileFormatPattern); + put("writer.file", logfilePath); + put("writer.append", "true"); + put("writer.level", logLevel.name().toLowerCase()); + }}; + + if (extendedProperties != null) { + configurationMap.putAll(extendedProperties); } + + Configuration.replace(configurationMap); + } + + public static void useDefaultLogging() { + useDefaultLogging(null); } public static String getClientPrefix(final @NotNull MqttClientConfig config) { diff --git a/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java b/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java index 2e62f82b6..a061674a9 100644 --- a/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java +++ b/src/test/java/com/hivemq/cli/DefaultCLIPropertiesTest.java @@ -68,7 +68,7 @@ void noPropertyFile() throws Exception { assertEquals(MqttVersion.MQTT_5_0, defaultCLIProperties.getMqttVersion()); assertEquals("localhost", defaultCLIProperties.getHost()); assertEquals(1883, defaultCLIProperties.getPort()); - assertEquals(Level.TRACE, defaultCLIProperties.getShellDebugLevel()); + assertEquals(Level.DEBUG, defaultCLIProperties.getLogfileDebugLevel()); assertEquals("mqtt", defaultCLIProperties.getClientPrefix()); assertEquals(pathToTmpDir + "/.mqtt-cli/logs/", defaultCLIProperties.getLogfilePath()); assertNull(defaultCLIProperties.getClientSubscribeOutputFile()); @@ -87,7 +87,7 @@ void emptyPropertyFile() throws Exception { assertEquals(MqttVersion.MQTT_5_0, defaultCLIProperties.getMqttVersion()); assertEquals("localhost", defaultCLIProperties.getHost()); assertEquals(1883, defaultCLIProperties.getPort()); - assertEquals(Level.TRACE, defaultCLIProperties.getShellDebugLevel()); + assertEquals(Level.DEBUG, defaultCLIProperties.getLogfileDebugLevel()); assertEquals("mqtt", defaultCLIProperties.getClientPrefix()); assertEquals(pathToTmpDir + "/.mqtt-cli/logs/", defaultCLIProperties.getLogfilePath()); assertNull(defaultCLIProperties.getClientSubscribeOutputFile()); @@ -106,7 +106,7 @@ void overridePropertyFile() throws Exception { assertEquals(MqttVersion.MQTT_3_1_1, defaultCLIProperties.getMqttVersion()); assertEquals("broker.hivemq.com", defaultCLIProperties.getHost()); assertEquals(1884, defaultCLIProperties.getPort()); - assertEquals(Level.DEBUG, defaultCLIProperties.getShellDebugLevel()); + assertEquals(Level.TRACE, defaultCLIProperties.getLogfileDebugLevel()); assertEquals("testprefix", defaultCLIProperties.getClientPrefix()); assertEquals("/.mqtt-cli/logs", defaultCLIProperties.getLogfilePath()); assertNull(defaultCLIProperties.getClientSubscribeOutputFile()); diff --git a/src/test/resources/PropertyFiles/override.properties b/src/test/resources/PropertyFiles/override.properties index 5d93b1e9d..b52d2a682 100644 --- a/src/test/resources/PropertyFiles/override.properties +++ b/src/test/resources/PropertyFiles/override.properties @@ -2,7 +2,7 @@ mqtt.port=1884 client.id.prefix=testprefix mqtt.host=broker.hivemq.com mqtt.version=3 -debug.level.shell=DEBUG +logfile.level=TRACE logfile.path=/.mqtt-cli/logs auth.username=mqtt auth.password=password \ No newline at end of file From f1d63acfbe034b6a27e834c7065b81fb6d087d52 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Fri, 13 Dec 2019 16:52:50 +0100 Subject: [PATCH 16/20] fix logging --- .../hivemq/cli/mqtt/AbstractMqttClientExecutor.java | 5 +++-- .../java/com/hivemq/cli/mqtt/MqttClientExecutor.java | 12 +----------- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java index 186cad3f7..ff98183bd 100644 --- a/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/AbstractMqttClientExecutor.java @@ -146,9 +146,10 @@ public void disconnect(final @NotNull Disconnect disconnect) { break; } clientKeyToClientData.remove(clientKey); - } - Logger.error("client to disconnect is not connected ({}) ", clientKey); + else { + Logger.error("client to disconnect is not connected ({}) ", clientKey); + } } public void disconnectAllClients(final @NotNull Disconnect disconnect) { diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index e4fb262a6..5edd382a0 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -344,17 +344,7 @@ void mqtt5Disconnect(@NotNull final Mqtt5Client client, @NotNull final Disconnec @Override void mqtt3Disconnect(@NotNull final Mqtt3Client client, @NotNull final Disconnect disconnect) { - if (disconnect.getSessionExpiryInterval() != null) { - Logger.warn("Session expiry interval set but is unused in Mqtt version {}", MqttVersion.MQTT_3_1_1); - } - if (disconnect.getReasonString() != null) { - Logger.warn("Reason string was set but is unused in Mqtt version {}", MqttVersion.MQTT_3_1_1); - } - if (disconnect.getUserProperties() != null) { - Logger.warn("User properties were set but are unused in Mqtt version {}", MqttVersion.MQTT_3_1_1); - } - - Logger.debug("Sending DISCONNECT with Mqtt3Disconnect: {}", Mqtt3Disconnect.class); + Logger.debug("{} Sending DISCONNECT", LoggerUtils.getClientPrefix(client.getConfig())); client.toBlocking().disconnect(); } From e119b1d04f9b891249c3068d7897520de000ab46 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 18 Dec 2019 09:36:18 +0100 Subject: [PATCH 17/20] improve logging for connection refusals --- .../java/com/hivemq/cli/commands/cli/PublishCommand.java | 4 ++++ .../java/com/hivemq/cli/commands/cli/SubscribeCommand.java | 4 ++++ .../java/com/hivemq/cli/commands/shell/ShellCommand.java | 3 ++- .../com/hivemq/cli/commands/shell/ShellConnectCommand.java | 4 ++++ src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java | 6 ++---- 5 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java index 613eaf6d9..9ea2d88bb 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/PublishCommand.java @@ -27,6 +27,7 @@ import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; +import com.hivemq.client.mqtt.exceptions.ConnectionFailedException; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PayloadFormatIndicator; @@ -124,6 +125,9 @@ public void run() { qos = MqttUtils.arrangeQosToMatchTopics(topics, qos); mqttClientExecutor.publish(this); } + catch (final ConnectionFailedException cex) { + Logger.error(cex, cex.getCause().getMessage()); + } catch (final Exception ex) { Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } diff --git a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java index cf757df00..42bf47ca0 100644 --- a/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java +++ b/src/main/java/com/hivemq/cli/commands/cli/SubscribeCommand.java @@ -30,6 +30,7 @@ import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; import com.hivemq.client.mqtt.datatypes.MqttQos; +import com.hivemq.client.mqtt.exceptions.ConnectionFailedException; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; @@ -121,6 +122,9 @@ public void run() { qos = MqttUtils.arrangeQosToMatchTopics(topics, qos); subscribeClient = mqttClientExecutor.subscribe(this); } + catch (final ConnectionFailedException cex) { + Logger.error(cex, cex.getCause().getMessage()); + } catch (final Exception ex) { Logger.error(ex, Throwables.getRootCause(ex).getMessage()); return; diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java index d73879eb3..e1397b1ff 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellCommand.java @@ -153,12 +153,13 @@ private void interact() { currentCommandLine.execute(arguments); } } catch (final UserInterruptException e) { - Logger.trace("User interrupted shell: {}", e); + Logger.trace("--- User interrupted shell ---"); return; } catch (final Exception ex) { Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } } + Logger.info("--- Shell-Mode exited ---"); } catch (final Exception ex) { Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java index 6153675ba..12afbc80c 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellConnectCommand.java @@ -27,6 +27,7 @@ import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.MqttClientSslConfig; import com.hivemq.client.mqtt.MqttVersion; +import com.hivemq.client.mqtt.exceptions.ConnectionFailedException; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperties; import com.hivemq.client.mqtt.mqtt5.datatypes.Mqtt5UserProperty; import org.jetbrains.annotations.NotNull; @@ -82,6 +83,9 @@ public void run() { try { return mqttClientExecutor.connect(this); } + catch (final ConnectionFailedException cex) { + Logger.error(cex, cex.getCause().getMessage()); + } catch (final Exception ex) { Logger.error(ex, Throwables.getRootCause(ex).getMessage()); } diff --git a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java index 5edd382a0..7d777d467 100644 --- a/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java +++ b/src/main/java/com/hivemq/cli/mqtt/MqttClientExecutor.java @@ -199,9 +199,8 @@ void mqtt5Publish(final @NotNull Mqtt5Client client, final @NotNull Publish publ Throwables.getRootCause(throwable).getMessage()); } else { - Logger.debug("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", + Logger.debug("{} received PUBLISH acknowledgement {}", clientLogPrefix, - topic, publishResult); } }) @@ -236,9 +235,8 @@ void mqtt3Publish(final @NotNull Mqtt3Client client, final @NotNull Publish publ Throwables.getRootCause(throwable).getMessage()); } else { - Logger.debug("{} received PUBLISH acknowledgement for PUBLISH to TOPIC '{}': {}", + Logger.debug("{} received PUBLISH acknowledgement {}", clientLogPrefix, - topic, publishResult); } }) From 9b57d26cfefa9bd738b79648d43b793bd04b96db Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 18 Dec 2019 11:07:40 +0100 Subject: [PATCH 18/20] use console writer for printing inside shell instead of system.out --- .../cli/commands/shell/ListClientsCommand.java | 13 ++++++++----- .../cli/commands/shell/ShellContextCommand.java | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java index b1db6abdf..24cc06279 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ListClientsCommand.java @@ -25,6 +25,7 @@ import picocli.CommandLine; import javax.inject.Inject; +import java.io.PrintWriter; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; @@ -72,8 +73,10 @@ public void run() { final List sortedClientData = getSortedClientData(); + final PrintWriter writer = ShellCommand.TERMINAL_WRITER; + if (longOutput) { - System.out.println("total " + sortedClientData.size()); + writer.println("total " + sortedClientData.size()); if (sortedClientData.size() == 0) { return; @@ -125,7 +128,7 @@ public void run() { final String connectionState = client.getState().toString(); - System.out.printf(format, + writer.printf(format, connectionState, dateTime.getHour(), dateTime.getMinute(), dateTime.getSecond(), client.getConfig().getClientIdentifier().get().toString(), @@ -135,7 +138,7 @@ public void run() { client.getConfig().getSslConfig().map(ssl -> ssl.getProtocols().get().toString()).orElse("NO_SSL")); if (listSubscriptions) { - System.out.printf(" -subscribed topics: %s\n", clientData.getSubscribedTopics()); + writer.printf(" -subscribed topics: %s\n", clientData.getSubscribedTopics()); } } @@ -143,9 +146,9 @@ public void run() { } else { for (final ClientData clientData : sortedClientData) { - System.out.println(clientData.getClient().getConfig().getClientIdentifier().get() + "@" + clientData.getClient().getConfig().getServerHost()); + writer.println(clientData.getClient().getConfig().getClientIdentifier().get() + "@" + clientData.getClient().getConfig().getServerHost()); if (listSubscriptions) { - System.out.printf(" -subscribed topics: %s\n", clientData.getSubscribedTopics()); + writer.printf(" -subscribed topics: %s\n", clientData.getSubscribedTopics()); } } } diff --git a/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java b/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java index 7350825e9..d11424fe5 100644 --- a/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java +++ b/src/main/java/com/hivemq/cli/commands/shell/ShellContextCommand.java @@ -65,7 +65,7 @@ public static void removeContext() { @Override public void run() { - System.out.println(ShellCommand.getUsageMessage()); + ShellCommand.TERMINAL_WRITER.println(ShellCommand.getUsageMessage()); } public String getKey() { From 8511853c75404dcf45b06768a3cf598f2c59c090 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Wed, 18 Dec 2019 11:07:56 +0100 Subject: [PATCH 19/20] define forbidden apis --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 7d24eef19..d6173789d 100644 --- a/build.gradle +++ b/build.gradle @@ -217,8 +217,8 @@ forbiddenApisMain { } forbiddenApis { - bundledSignatures = ['jdk-system-out'] - ignoreFailures = true + bundledSignatures = ['jdk-deprecated', 'jdk-non-portable', 'jdk-reflection' ] + ignoreFailures = false } //disable From a3886123f68ef6bfefe465523ddacd547b682a22 Mon Sep 17 00:00:00 2001 From: Till Seeberger Date: Thu, 19 Dec 2019 13:00:49 +0100 Subject: [PATCH 20/20] fix formatting --- src/main/java/com/hivemq/cli/commands/MqttCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/hivemq/cli/commands/MqttCommand.java b/src/main/java/com/hivemq/cli/commands/MqttCommand.java index ef998dea3..39c27b422 100644 --- a/src/main/java/com/hivemq/cli/commands/MqttCommand.java +++ b/src/main/java/com/hivemq/cli/commands/MqttCommand.java @@ -80,7 +80,7 @@ public void setDefaultOptions() { else { final String rndID = MqttUtils.buildRandomClientID(defaultCLIProperties.getClientLength()); identifier = identifierPrefix + rndID; - Logger.trace("Created 'identifier' ({})", identifier); + Logger.trace("Created identifier ('{}')", identifier); } }