### Complete MQTT 5 Client Setup Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/01-client-builders.md Demonstrates a full configuration for an MQTT 5 blocking client, including identifier, server details, SSL, authentication, and automatic reconnect. Use this for a comprehensive setup. ```java Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("my-app-client") .serverHost("broker.hivemq.com") .serverPort(8883) .sslWithDefaultConfig() .simpleAuth() .username("user") .password("pass") .applySimpleAuth() .automaticReconnectWithDefaultConfig() .buildBlocking(); client.connect(); client.publishWith() .topic("sensor/temperature") .qos(MqttQos.AT_LEAST_ONCE) .payload("23.5".getBytes()) .send(); client.disconnect(); ``` -------------------------------- ### MQTT 3.1.1 Async Client Example Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/03-async-api.md Connects to a broker using the MQTT 3.1.1 asynchronous client. This example demonstrates a basic connection and waits for its completion. ```java Mqtt3AsyncClient client = Mqtt3Client.builder() .identifier("mqtt3-async") .serverHost("broker.example.com") .buildAsync(); client.connect() .thenAccept(connAck -> { System.out.println("Connected with return code: " + connAck.getReturnCode()); }) .join(); // Wait for completion ``` -------------------------------- ### Example Usage of Connected Listener Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md An example demonstrating how to register a connected listener to print the server address upon successful connection. ```java builder.addConnectedListener(context -> { System.out.println("Connected to " + context.getServerAddress()); }) ``` -------------------------------- ### Async Callback Example Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/09-quick-start-examples.md Demonstrates connecting to a broker, subscribing to a topic, and handling incoming messages using asynchronous callbacks. ```java public class AsyncCallbackExample { public static void main(String[] args) throws Exception { Mqtt5AsyncClient client = Mqtt5Client.builder() .identifier("callback-client") .serverHost("broker.example.com") .buildAsync(); client.connect() .thenAccept(connAck -> System.out.println("Connected")) .get(); // Subscribe with callback Mqtt5Subscribe subscribe = Mqtt5Subscribe.builder() .topicFilter("sensor/#") .qos(MqttQos.AT_LEAST_ONCE) .build(); client.subscribe(subscribe, publish -> { String topic = publish.getTopic().toString(); String payload = new String(publish.getPayloadAsBytes()); System.out.println(topic + ": " + payload); }); // Keep running Thread.sleep(30000); client.disconnect().get(); } } ``` -------------------------------- ### Complete MQTT 5 Async Client Example Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/03-async-api.md Connects to a broker, subscribes to a topic, and sets up a message listener. The application continues to run without blocking after initiating the connection. ```java Mqtt5AsyncClient client = Mqtt5Client.builder() .identifier("async-app") .serverHost("broker.example.com") .buildAsync(); client.connect() .thenCompose(connAck -> { System.out.println("Connected"); return client.subscribeWith() .topicFilter("home/sensors/#") .qos(MqttQos.AT_LEAST_ONCE) .send(); }) .thenAccept(subAck -> { System.out.println("Subscribed"); client.publishes(MqttGlobalPublishFilter.ALL, publish -> { System.out.println("Message: " + publish.getTopic()); }); }) .exceptionally(ex -> { System.out.println("Error: " + ex.getMessage()); return null; }); // Application continues without blocking ``` -------------------------------- ### Complete Mqtt5BlockingClient Lifecycle Example Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/08-lifecycle-listeners.md Demonstrates setting up connected and disconnected listeners, including handling MQTT 5 specific disconnect information and automatic reconnect configurations. Use this for comprehensive client lifecycle management. ```java Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("lifecycle-client") .serverHost("broker.example.com") .serverPort(8883) .sslWithDefaultConfig() // Connected listener .addConnectedListener(context -> { System.out.println("=== CONNECTED ==="); System.out.println("Server: " + context.getServerHost() + ":" + context.getServerPort()); Mqtt5ClientConnectedContext ctx5 = (Mqtt5ClientConnectedContext) context; Mqtt5ConnAck connAck = ctx5.getConnAck(); System.out.println("Session Present: " + connAck.isSessionPresent()); if (connAck.getAssignedClientIdentifier().isPresent()) { System.out.println("Server assigned ID: " + connAck.getAssignedClientIdentifier().get()); } }) // Disconnected listener .addDisconnectedListener(context -> { System.out.println("=== DISCONNECTED ==="); System.out.println("Disconnect Source: " + context.getDisconnectSource()); // Handle disconnection based on source if (context.getDisconnectSource() == MqttDisconnectSource.SERVER) { Mqtt5ClientDisconnectedContext ctx5 = (Mqtt5ClientDisconnectedContext) context; Optional disconnect = ctx5.getDisconnect(); if (disconnect.isPresent()) { Mqtt5Disconnect msg = disconnect.get(); System.out.println("Server reason: " + msg.getReasonCode()); // Handle server reference for broker migration if (msg.getServerReference().isPresent()) { System.out.println("Broker migrated to: " + msg.getServerReference().get()); // Update connection config to new broker } } } // Check if automatic reconnect will happen Optional reconnector = context.getReconnector(); if (reconnector.isPresent()) { System.out.println("Auto-reconnect enabled, will retry..."); reconnector.get().resubscribeIfSessionExpired(); } else { System.out.println("No auto-reconnect configured"); } // Log cause if disconnection was unexpected Optional cause = context.getCause(); if (cause.isPresent()) { System.out.println("Error: " + cause.get().getMessage()); cause.get().printStackTrace(); } }) // Auto-reconnect configuration .automaticReconnectWithDefaultConfig() .buildBlocking(); // Use client client.connect(); try { client.publishWith() .topic("test/topic") .qos(MqttQos.AT_LEAST_ONCE) .payload("test".getBytes()) .send(); Thread.sleep(5000); // Simulate work } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { client.disconnect(); } ``` -------------------------------- ### Basic Blocking Client Example Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/09-quick-start-examples.md Demonstrates connecting, publishing, and subscribing using a blocking MQTT client. Ensure you have the necessary dependencies for HiveMQ MQTT Client. ```java import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.datatypes.MqttQos; import com.hivemq.client.mqtt.mqtt5.Mqtt5BlockingClient; import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck; import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PublishResult; public class BasicBlockingExample { public static void main(String[] args) throws Exception { // Create client Mqtt5BlockingClient client = MqttClient.builder() .identifier("my-app-client") .serverHost("broker.hivemq.com") .useMqttVersion5() .buildBlocking(); try { // Connect Mqtt5ConnAck connAck = client.connect(); System.out.println("Connected: " + connAck.getReasonCode()); // Publish Mqtt5PublishResult result = client.publishWith() .topic("my/test/topic") .qos(MqttQos.AT_LEAST_ONCE) .payload("Hello MQTT".getBytes()) .send(); System.out.println("Published successfully"); // Subscribe and receive try (Mqtt5BlockingClient.Mqtt5Publishes publishes = client.publishes(MqttGlobalPublishFilter.ALL)) { client.subscribeWith() .topicFilter("my/test/topic") .qos(MqttQos.AT_LEAST_ONCE) .send(); var message = publishes.receive(5, TimeUnit.SECONDS); if (message.isPresent()) { System.out.println("Received: " + new String(message.get().getPayloadAsBytes())); } } } finally { client.disconnect(); } } } ``` -------------------------------- ### Shared Subscription Example (Java) Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/09-quick-start-examples.md Demonstrates how multiple clients can subscribe to a shared topic to load-balance messages. Ensure the broker supports shared subscriptions and the topic filter is correctly formatted. ```java public class SharedSubscriptionExample { public static void main(String[] args) throws Exception { // Multiple clients with shared subscription // Messages are load-balanced among subscribers for (int i = 1; i <= 3; i++) { int clientId = i; new Thread(() -> runClient(clientId)).start(); } } static void runClient(int clientId) { try { Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("consumer-" + clientId) .serverHost("broker.example.com") .buildBlocking(); client.connect(); try (Mqtt5BlockingClient.Mqtt5Publishes publishes = client.publishes(MqttGlobalPublishFilter.ALL)) { // Use shared subscription // Messages are distributed among all subscribers client.subscribeWith() .topicFilter("$share/workgroup/tasks/#") .qos(MqttQos.AT_LEAST_ONCE) .send(); System.out.println("Consumer " + clientId + " ready"); for (int j = 0; j < 10; j++) { var message = publishes.receive(5, TimeUnit.SECONDS); if (message.isPresent()) { String payload = new String(message.get().getPayloadAsBytes()); System.out.println("Consumer " + clientId + " got: " + payload); } } } client.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Complete MQTT5 Blocking Client Configuration Example Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Demonstrates building and connecting an MQTT5 blocking client with basic connection details, WebSocket transport, authentication, automatic reconnect, and connection properties like keep-alive and last-will messages. ```java Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("my-client-id") .serverHost("broker.example.com") .serverPort(8883) .sslWithDefaultConfig() .simpleAuth() .username("admin") .password("password123") .applySimpleAuth() .automaticReconnectWithDefaultConfig() .addConnectedListener(context -> { System.out.println("Connected!"); }) .addDisconnectedListener(context -> { System.out.println("Disconnected: " + context.getCause()); }) .connectWith() .keepAlive(60) .sessionExpiryInterval(3600) .willPublish() .topic("last-will") .qos(MqttQos.AT_LEAST_ONCE) .payload("offline".getBytes()) .applyWillPublish() .send() .buildBlocking(); client.connect(); ``` -------------------------------- ### Connect with Username/Password Authentication Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/09-quick-start-examples.md Shows how to authenticate with an MQTT broker using a username and password. This example also demonstrates setting custom connection properties like keep-alive and session expiry. ```java public class AuthExample { public static void main(String[] args) throws Exception { Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("auth-client") .serverHost("broker.example.com") .serverPort(8883) .sslWithDefaultConfig() // Simple authentication (username/password) .simpleAuth() .username("myuser") .password("mypassword") .applySimpleAuth() // Connect with custom properties .connectWith() .keepAlive(60) .sessionExpiryInterval(3600) .send() .buildBlocking(); Mqtt5ConnAck connAck = client.connect(); System.out.println("Connected: " + connAck.getReasonCode()); client.disconnect(); } } ``` -------------------------------- ### Error Handling during Connection Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/README.md Provides an example of how to catch and handle connection errors, specifically `Mqtt5ConnAckException`. ```APIDOC ## Error Handling ### Description This example demonstrates how to handle connection errors using a try-catch block for `Mqtt5ConnAckException`. ### Method ```java try { client.connect(); } catch (Mqtt5ConnAckException e) { System.out.println("Failed: " + e.getMqttMessage().getReasonCode()); } ``` ### Throws/Completes Exceptionally: - `Mqtt5ConnAckException` — When the connection acknowledgment indicates a failure. ``` -------------------------------- ### Subscribe with Callback Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Example of subscribing to a topic using the async API with a callback for received messages. Ensure the client is connected before subscribing. ```java Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier(UUID.randomUUID().toString()) .serverHost("broker.hivemq.com") .buildBlocking(); client.connect(); client.toAsync().subscribeWith() .topicFilter("test/topic") .qos(MqttQos.AT_LEAST_ONCE) .callback(System.out::println) .send(); ``` -------------------------------- ### Publish with Callbacks Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Example of publishing a message asynchronously. The publish operation is chained with connect and disconnect using CompletableFuture. ```java Mqtt5AsyncClient client = Mqtt5Client.builder() .identifier(UUID.randomUUID().toString()) .serverHost("broker.hivemq.com") .buildAsync(); client.connect() .thenCompose(connAck -> client.publishWith().topic("test/topic").payload("1".getBytes()).send()) .thenCompose(publishResult -> client.disconnect()); ``` -------------------------------- ### Subscribe with Fluent API Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Example of subscribing to a topic with a specific QoS level using the fluent `subscribeWith()` method. ```java client.subscribeWith().topicFilter("test/topic").qos(MqttQos.EXACTLY_ONCE).send(); ``` -------------------------------- ### Reactive Backpressure Example Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/09-quick-start-examples.md Illustrates how to handle high message volumes using reactive streams and backpressure. It buffers messages and processes them on a separate IO scheduler. ```java public class BackpressureExample { public static void main(String[] args) { Mqtt5RxClient client = Mqtt5Client.builder() .identifier("backpressure-client") .serverHost("broker.example.com") .buildRx(); client.connect() .ignoreElement() .andThen(client.publishes(MqttGlobalPublishFilter.ALL)) .onBackpressureBuffer(1000) // Buffer up to 1000 messages .observeOn(Schedulers.io()) // Process on IO scheduler .flatMap(publish -> processMessageAsync(publish) .doOnSuccess(result -> System.out.println("Processed")) .onErrorReturn("error") ) .subscribe( result -> System.out.println("Result: " + result), error -> System.err.println("Error: " + error), () -> System.out.println("Complete") ); // Subscribe to data client.subscribeWith() .topicFilter("data/stream") .qos(MqttQos.AT_LEAST_ONCE) .send() .subscribe(); // Keep running new CountDownLatch(1).await(); } static Single processMessageAsync(Mqtt5Publish publish) { return Single.fromCallable(() -> { String payload = new String(publish.getPayloadAsBytes()); Thread.sleep(100); // Simulate processing return "Processed: " + payload; }); } } ``` -------------------------------- ### Get Mqtt3Client Configuration Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/01-client-builders.md Retrieve the configuration object for an existing MQTT 3.1.1 client instance. ```java @Override Mqtt3ClientConfig getConfig() ``` -------------------------------- ### Create MQTT 5 Subscribe Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/04-types-and-datatypes.md Example of building an MQTT 5 Subscribe message with multiple topic filters, QoS levels, and specific options like No Local and Retain As Published. ```java Mqtt5Subscribe subscribe = Mqtt5Subscribe.builder() .topicFilter("home/+/temperature") .qos(MqttQos.AT_LEAST_ONCE) .noLocal(true) // Don't receive own publishes .retainAsPublished(true) .addSubscription() .topicFilter("home/light/#") .qos(MqttQos.AT_MOST_ONCE) .applySubscription() .build(); ``` -------------------------------- ### Get MQTT QoS Code Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/04-types-and-datatypes.md Retrieves the numeric MQTT QoS code for a given QoS level. Use this to get the integer representation (0-2) of a QoS enum. ```java int code = MqttQos.AT_LEAST_ONCE.getCode(); // Returns 1 ``` -------------------------------- ### Creating a Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/README.md Demonstrates how to build and initialize a blocking MQTT5 client instance with a specified identifier and server host. ```APIDOC ## Creating a Client ### Description This method shows how to create a blocking MQTT5 client instance. ### Method ```java Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("my-client") .serverHost("broker.example.com") .buildBlocking(); ``` ### Returns: `Mqtt5BlockingClient` — The initialized blocking MQTT5 client. ``` -------------------------------- ### Create MQTT v3 Client Directly Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Demonstrates creating an MQTT v3 client directly using its dedicated builder. ```java Mqtt3Client client = Mqtt3Client.builder()...build(); ``` -------------------------------- ### Get User Properties Builder Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/04-types-and-datatypes.md Returns a builder for user-defined properties. ```java Mqtt5UserPropertiesBuilder userProperties() ``` -------------------------------- ### Create MQTT v5 Client Directly Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Shows how to create an MQTT v5 client directly using its specific builder when the version is known upfront. ```java Mqtt5Client client = Mqtt5Client.builder()...build(); ``` -------------------------------- ### Get Server Address on Disconnect Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/08-lifecycle-listeners.md Retrieves the InetSocketAddress of the server from which the client was disconnected. ```java InetSocketAddress getServerAddress() ``` -------------------------------- ### Get Client Configuration on Disconnect Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/08-lifecycle-listeners.md Retrieves the client configuration that was active at the time of disconnection. ```java MqttClientConfig getClientConfig() ``` -------------------------------- ### Get Server Hostname on Disconnect Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/08-lifecycle-listeners.md Retrieves the hostname of the MQTT broker from which the client was disconnected. ```java String getServerHost() ``` -------------------------------- ### Create MQTT v5 Client using Builder Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Demonstrates how to create an MQTT v5 client instance using the fluent builder pattern, specifying the client identifier and server host. ```java Mqtt5Client client = MqttClient.builder() .identifier(UUID.randomUUID().toString()) .serverHost("broker.hivemq.com") .useMqttVersion5() .build(); ``` -------------------------------- ### Get Maximum Reconnect Delay Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the configured maximum delay between subsequent reconnection attempts. ```java long getMaxDelayMs() ``` -------------------------------- ### Get Initial Reconnect Delay Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the configured initial delay before the first reconnection attempt. ```java long getInitialDelayMs() ``` -------------------------------- ### Create a Blocking MQTT5 Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/README.md Shows how to build and initialize a blocking MQTT5 client instance. Configure the client identifier and server host before building. ```java Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("my-client") .serverHost("broker.example.com") .buildBlocking(); ``` -------------------------------- ### Get WebSocket Query String Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the optional query string appended to the WebSocket URL. ```java Optional getQueryString() ``` -------------------------------- ### Create MQTT v3 Client using Builder Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Illustrates the creation of an MQTT v3 client instance using the fluent builder pattern. ```java Mqtt3Client client = MqttClient.builder()...useMqttVersion3().build(); ``` -------------------------------- ### Get WebSocket Path Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the configured path for the WebSocket connection. Defaults to "/". ```java String getPath() ``` -------------------------------- ### Connect with TLS/SSL Configuration Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/09-quick-start-examples.md Demonstrates how to configure TLS/SSL for secure MQTT connections. This includes loading a truststore and applying custom hostname verification. ```java import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import java.io.FileInputStream; import java.security.KeyStore; public class TlsExample { public static void main(String[] args) throws Exception { // Load truststore KeyStore truststore = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream("/path/to/truststore.jks")) { truststore.load(fis, "password".toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(truststore); // Create client with TLS Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("tls-client") .serverHost("broker.example.com") .serverPort(8883) // TLS port .sslConfig() .trustManagerFactory(tmf) .hostnameVerifier((hostname, session) -> { // Custom hostname verification System.out.println("Verifying: " + hostname); return hostname.equals("broker.example.com"); }) .applyConfig() .buildBlocking(); client.connect(); // ... use client ... client.disconnect(); } } ``` -------------------------------- ### Get Server Port on Disconnect Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/08-lifecycle-listeners.md Retrieves the port number of the MQTT broker from which the client was disconnected. ```java int getServerPort() ``` -------------------------------- ### Subscribe to MQTT Topics with Reactive API Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Demonstrates how to connect to an MQTT broker and subscribe to topics using the reactive API. It shows how to handle connection acknowledgments, subscription acknowledgments, and incoming publish messages. ```java Mqtt5RxClient client = Mqtt5Client.builder() .identifier(UUID.randomUUID().toString()) .serverHost("broker.hivemq.com") .buildRx(); // As we use the reactive API, the following line does not connect yet, but returns a reactive type. // e.g. Single is something like a lazy and reusable future. Think of it as a source for the ConnAck message. Single connAckSingle = client.connect(); // Same here: the following line does not subscribe yet, but returns a reactive type. // FlowableWithSingle is a combination of the single SubAck message and a Flowable of Publish messages. // A Flowable is an asynchronous stream that enables backpressure from the application over the client to the broker. FlowableWithSingle subAckAndMatchingPublishes = client.subscribeStreamWith() .topicFilter("a/b/c").qos(MqttQos.AT_LEAST_ONCE) .addSubscription().topicFilter("a/b/c/d").qos(MqttQos.EXACTLY_ONCE).applySubscription() .applySubscribe(); // The reactive types offer many operators that will not be covered here. // Here we register callbacks to print messages when we received the CONNACK, SUBACK and matching PUBLISH messages. Completable connectScenario = connAckSingle .doOnSuccess(connAck -> System.out.println("Connected, " + connAck.getReasonCode())) .doOnError(throwable -> System.out.println("Connection failed, " + throwable.getMessage())) .ignoreElement(); Completable subscribeScenario = subAckAndMatchingPublishes .doOnSingle(subAck -> System.out.println("Subscribed, " + subAck.getReasonCodes())) .doOnNext(publish -> System.out.println( "Received publish" + ", topic: " + publish.getTopic() + ", QoS: " + publish.getQos() + ", payload: " + new String(publish.getPayloadAsBytes()))) .ignoreElements(); // Reactive types can be easily and flexibly combined connectScenario.andThen(subscribeScenario).blockingAwait(); ``` -------------------------------- ### Handle Mqtt5PubAckException Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/05-exceptions.md Demonstrates catching Mqtt5PubAckException when publishing with QoS 1. It shows how to check the PubAck reason code, specifically for NOT_AUTHORIZED. ```java try { Mqtt5PublishResult result = blockingClient.publish(message); } catch (Mqtt5PubAckException e) { Mqtt5PubAck ack = e.getMqttMessage(); if (ack.getReasonCode() == Mqtt5PubAckReasonCode.NOT_AUTHORIZED) { System.out.println("Not authorized to publish to this topic"); } } ``` -------------------------------- ### Mqtt5Client Instance Methods Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/01-client-builders.md Provides methods to access the client's configuration and convert it to different API styles (reactive, asynchronous, blocking). ```APIDOC ## Mqtt5Client Instance Methods ### getConfig() #### Description Returns a configuration snapshot of this client. #### Method `Mqtt5ClientConfig getConfig()` #### Returns `Mqtt5ClientConfig` — Configuration snapshot of this client --- ### toRx() #### Description Converts the client to its reactive API (RxJava 3 compatible). This can be used concurrently with other APIs. #### Method `Mqtt5RxClient toRx()` #### Returns `Mqtt5RxClient` — Reactive API wrapper for this client #### Example ```java Mqtt5RxClient rxClient = client.toRx(); Single connAck = rxClient.connect(); ``` --- ### toAsync() #### Description Converts the client to its asynchronous API using `CompletableFuture`. This can be used concurrently with other APIs. #### Method `Mqtt5AsyncClient toAsync()` #### Returns `Mqtt5AsyncClient` — Async API wrapper for this client #### Example ```java Mqtt5AsyncClient asyncClient = client.toAsync(); CompletableFuture connAck = asyncClient.connect(); ``` --- ### toBlocking() #### Description Converts the client to its blocking API. This can be used concurrently with other APIs. #### Method `Mqtt5BlockingClient toBlocking()` #### Returns `Mqtt5BlockingClient` — Blocking API wrapper for this client #### Example ```java Mqtt5BlockingClient blockingClient = client.toBlocking(); Mqtt5ConnAck connAck = blockingClient.connect(); ``` ``` -------------------------------- ### Handle MqttClientStateException with Blocking Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/05-exceptions.md Shows how to catch MqttClientStateException when using a blocking client, for example, attempting to connect when already connected. ```java try { Mqtt5ConnAck ack = blockingClient.connect(); } catch (MqttClientStateException e) { System.out.println("Already connected"); } ``` -------------------------------- ### Connect Client with Pre-built Connect Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Illustrates connecting the client using a pre-constructed MQTT v5 Connect message with custom properties. ```java Mqtt5Connect connectMessage = Mqtt5Connect.builder().keepAlive(10).build(); client.connect(connectMessage); ``` -------------------------------- ### Get Application Scheduler Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the optional executor for application callbacks. This allows for custom thread management for handling client callbacks. ```java Optional getApplicationScheduler() ``` -------------------------------- ### Connect Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Shows the basic method to connect an MQTT client to the broker. ```java client.connect(); ``` -------------------------------- ### Get Netty Executor Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the optional custom executor for Netty event loops. This allows for custom thread management for network operations. ```java Optional getNettyExecutor() ``` -------------------------------- ### Connect, Subscribe, and Process Messages with Reactive Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/09-quick-start-examples.md Shows how to build a reactive scenario for connecting, subscribing to topics, processing incoming messages, and disconnecting. Ideal for event-driven applications. ```java import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.mqtt5.Mqtt5RxClient; import io.reactivex.rxjava3.core.Completable; public class ReactiveClientExample { public static void main(String[] args) { Mqtt5RxClient client = MqttClient.builder() .identifier("rx-app") .serverHost("broker.hivemq.com") .useMqttVersion5() .buildRx(); // Build reactive scenario Completable scenario = client.connect() .doOnSuccess(connAck -> System.out.println("Connected")) .ignoreElement() .andThen( client.subscribeStreamWith() .topicFilter("sensor/+/temperature") .qos(MqttQos.AT_LEAST_ONCE) .applySubscribe() .doOnSingle(subAck -> System.out.println("Subscribed")) .take(5) // Process first 5 messages .doOnNext(publish -> { String payload = new String(publish.getPayloadAsBytes()); System.out.println("Received: " + payload); }) .ignoreElements() ) .andThen(client.disconnect()) .doOnComplete(() -> System.out.println("Done")); // Execute scenario.blockingAwait(); } } ``` -------------------------------- ### Handle Connection Errors Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/README.md Provides an example of how to catch and handle connection acknowledgment exceptions. It logs the reason code of the MQTT message upon failure. ```java try { client.connect(); } catch (Mqtt5ConnAckException e) { System.out.println("Failed: " + e.getMqttMessage().getReasonCode()); } ``` -------------------------------- ### MQTT 3.1.1 Reactive Client Connection and Subscription Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Shows how to build and connect an MQTT 3.1.1 reactive client and subscribe to a topic. ```java Mqtt3RxClient client = Mqtt3Client.builder() .identifier("mqtt3-rx") .serverHost("broker.example.com") .buildRx(); client.connect() .doOnSuccess(connAck -> System.out.println("Connected")) .flatMap(ack -> client.subscribeWith() .topicFilter("test/#") .qos(MqttQos.AT_LEAST_ONCE) .send()) .subscribe(); ``` -------------------------------- ### Get Server Address from Config Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the server address the client is connected to from the client's configuration object. Useful for verifying connection details. ```java MqttClientConfig config = client.getConfig(); InetSocketAddress addr = config.getTransportConfig().getServerAddress(); System.out.println("Server: " + addr.getHostString() + ":" + addr.getPort()); ``` -------------------------------- ### MqttQos Enum Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/04-types-and-datatypes.md Represents the MQTT Quality of Service levels: AT_MOST_ONCE, AT_LEAST_ONCE, and EXACTLY_ONCE. Includes methods to get the numeric code and convert from a code. ```APIDOC ## MqttQos ### Description Enumeration for MQTT Quality of Service levels. ### Enum Values - **AT_MOST_ONCE**: Best-effort delivery. - **AT_LEAST_ONCE**: Guaranteed delivery with possible duplicates. - **EXACTLY_ONCE**: Guaranteed exactly-once delivery. ### Methods #### getCode() ```java int getCode() ``` Returns the numeric MQTT QoS code. **Returns:** `int` — Byte code (0-2) **Example:** ```java int code = MqttQos.AT_LEAST_ONCE.getCode(); // Returns 1 ``` #### fromCode(int code) ```java static MqttQos fromCode(int code) ``` Converts a numeric code to QoS enum. **Parameters:** - **code** (int) - Required - Numeric QoS code (0-2) **Returns:** `MqttQos` or null — QoS if code is valid, null otherwise **Example:** ```java MqttQos qos = MqttQos.fromCode(1); // Returns AT_LEAST_ONCE ``` ``` -------------------------------- ### Create MQTT Client with Auto Version Detection Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/01-client-builders.md Use this builder to create an MQTT client. The library automatically detects the MQTT version based on the methods used in the builder. ```java static MqttClientBuilder builder() ``` ```java Mqtt5Client client = MqttClient.builder() .identifier(UUID.randomUUID().toString()) .serverHost("broker.hivemq.com") .serverPort(8883) .useMqttVersion5() .buildBlocking(); ``` -------------------------------- ### Build Simple Username/Password Authentication Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Use this builder to configure simple username and password authentication for MQTT 5 clients. Ensure the username and password are set correctly. ```java Mqtt5SimpleAuthBuilder simpleAuth() ``` ```java builder.simpleAuth() .username("myuser") .password("mypass") .applySimpleAuth() ``` -------------------------------- ### Subscribe with Pre-built Subscribe Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Illustrates subscribing to a topic using a pre-constructed MQTT v5 Subscribe message object. ```java Mqtt5Subscribe subscribeMessage = Mqtt5Subscribe.builder() .topicFilter("test/topic") .qos(MqttQos.EXACTLY_ONCE) .build(); client.subscribe(subscribeMessage); ``` -------------------------------- ### Mqtt5RxClient.connect() Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Reactive source for connecting with default Connect message. Emits ConnAck once or an error. ```APIDOC ## Mqtt5RxClient.connect() ### Description Reactive source for connecting with default Connect message. Returns a lazy source emitting ConnAck once or an error. ### Method ```java Single connect() ``` ### Returns `Single` — Lazy source emitting ConnAck once. ### Throws/Emits Error - `Mqtt5ConnAckException` — if ConnAck contains error code ### Example ```java Mqtt5RxClient client = Mqtt5Client.builder() .identifier("rx-client") .serverHost("broker.example.com") .buildRx(); Single connAck = client.connect(); // Nothing happens until subscribed connAck .doOnSuccess(ack -> System.out.println("Connected: " + ack.getReasonCode())) .doOnError(ex -> System.out.println("Connect failed: " + ex.getMessage())) .subscribe(); ``` ``` -------------------------------- ### Get MQTT 5 Enhanced Authentication Mechanism Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the configured enhanced authentication mechanism for MQTT 5.0 clients. This is used for custom authentication flows. ```java Optional getEnhancedAuthMechanism() ``` -------------------------------- ### Create MQTT 5.0 Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/01-client-builders.md Use this builder specifically for creating MQTT 5.0 clients. It ensures all configurations adhere to the MQTT 5.0 protocol. ```java static Mqtt5ClientBuilder builder() ``` ```java Mqtt5Client client = Mqtt5Client.builder() .identifier("my-client-id") .serverHost("broker.example.com") .buildBlocking(); ``` -------------------------------- ### Get MQTT 5 Message Interceptors Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the configured message interceptors for MQTT 5.0 clients. Interceptors allow modification of messages before they are sent or after they are received. ```java Mqtt5ClientInterceptors getInterceptors() ``` -------------------------------- ### Mqtt5RxClient.connectWith() Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Fluent builder for reactive Connect. Allows configuring connection details before sending. ```APIDOC ## Mqtt5RxClient.connectWith() ### Description Fluent builder for reactive Connect. Allows configuring connection details before sending. ### Method ```java Mqtt5ConnectBuilder.Send> connectWith() ``` ### Returns Builder with `send()` returning `Single` ### Example ```java client.connectWith() .keepAlive(60) .sessionExpiryInterval(7200) .send() .subscribe(); ``` ``` -------------------------------- ### Get ConnAck from Mqtt5ClientConnectedContext Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/08-lifecycle-listeners.md Retrieve the ConnAck message from the MQTT 5 connected context to access server properties like session present and keep alive. ```java addConnectedListener(context -> { Mqtt5ConnAck connAck = ((Mqtt5ClientConnectedContext) context).getConnAck(); System.out.println("Session Present: " + connAck.isSessionPresent()); if (connAck.getServerKeepAlive().isPresent()) { System.out.println("Server Keep Alive: " + connAck.getServerKeepAlive().getAsInt()); } }) ``` -------------------------------- ### Get Advanced MQTT 5 Configuration Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/06-configuration.md Retrieves the advanced configuration object for MQTT 5.0 clients. This object provides access to further MQTT 5 specific features. ```java Mqtt5ClientAdvancedConfig getAdvancedConfig() ``` -------------------------------- ### Publish Message with Pre-built Publish Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Demonstrates publishing a message using a pre-built MQTT v5 Publish message object. ```java Mqtt5Publish publishMessage = Mqtt5Publish.builder() .topic("test/topic") .qos(MqttQos.AT_LEAST_ONCE) .payload("payload".getBytes()) .build(); client.publish(publishMessage); ``` -------------------------------- ### Handle Mqtt5ConnAckException in Blocking Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/05-exceptions.md Demonstrates how to catch and handle Mqtt5ConnAckException when using a blocking client. It shows how to access the ConnAck message to get the reason code and string. ```java try { Mqtt5ConnAck connAck = blockingClient.connect(); } catch (Mqtt5ConnAckException e) { Mqtt5ConnAck ack = e.getMqttMessage(); System.out.println("Connect failed: " + ack.getReasonCode()); System.out.println("Reason: " + ack.getReasonString().orElse("unknown")); } ``` -------------------------------- ### Create MQTT 5 Publish Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/04-types-and-datatypes.md Demonstrates how to construct an MQTT 5.0 Publish message using the fluent builder pattern. This includes setting the topic, QoS, payload, and message expiry interval. ```java Mqtt5Publish publish = Mqtt5Publish.builder() .topic("sensor/temperature") .qos(MqttQos.AT_LEAST_ONCE) .payload("23.5".getBytes()) .messageExpiryInterval(3600) .build(); ``` -------------------------------- ### Create MQTT 5 Disconnect Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/04-types-and-datatypes.md Example of building an MQTT 5 Disconnect message with a reason code, session expiry, reason string, and server reference for redirection. ```java Mqtt5Disconnect disconnect = Mqtt5Disconnect.builder() .reasonCode(Mqtt5DisconnectReasonCode.NORMAL_DISCONNECTION) .sessionExpiryInterval(0) // Don't persist session .reasonString("Bye") .serverReference("broker2.example.com") // Redirect to another broker .build(); ``` -------------------------------- ### connect() Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/03-async-api.md Asynchronously connects to the broker with default Connect message. Returns a CompletableFuture that completes with ConnAck. ```APIDOC ## connect() ### Description Asynchronously connects to the broker with default Connect message. ### Method N/A (Java method) ### Endpoint N/A (Java method) ### Parameters None ### Request Example ```java Mqtt5AsyncClient client = Mqtt5Client.builder() .identifier("async-client") .serverHost("broker.example.com") .buildAsync(); client.connect() .thenAccept(connAck -> System.out.println("Connected: " + connAck.getReasonCode())) .exceptionally(ex -> { System.out.println("Connection failed: " + ex.getMessage()); return null; }); ``` ### Response #### Success Response `CompletableFuture` — Future that completes with ConnAck #### Response Example (See Request Example for completion handling) ``` -------------------------------- ### subscribeWith() Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Provides a fluent builder for creating subscriptions and returns a Single upon completion. ```APIDOC ## subscribeWith() ### Description Fluent builder for subscription returning Single. ### Method Signature ```java Mqtt5SubscribeBuilder.Send.Start> subscribeWith() ``` ### Returns Builder with `send()` returning `Single` ### Example ```java Single subAck = client.subscribeWith() .topicFilter("sensor/+/temperature") .qos(MqttQos.AT_LEAST_ONCE) .send(); subAck.subscribe(ack -> System.out.println("Subscribed")); ``` ``` -------------------------------- ### Subscribe with Pre-built Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Subscribe to topics using a pre-built Mqtt5Subscribe message object. This is useful when the subscription details are constructed elsewhere. ```java Mqtt5Subscribe subscribe = Mqtt5Subscribe.builder() .topicFilter("test/topic") .qos(MqttQos.AT_LEAST_ONCE) .build(); client.subscribe(subscribe) .subscribe(subAck -> System.out.println("Subscribed")); ``` -------------------------------- ### Ignore Flowable Elements, Get Only Single SubAck Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Use ignoreElements() on a FlowableWithSingle to discard all incoming Publish messages and only receive the Single SubAck. This is useful when you only need to confirm the subscription. ```java Single justSubAck = subAndMessages.ignoreElements(); ``` -------------------------------- ### Connect to Broker with Default Configuration Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/02-blocking-api.md Connects to the MQTT broker using default settings. Ensure the client is built with server host and identifier. This method blocks until a connection is established or an error occurs. ```java Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier("client-1") .serverHost("broker.example.com") .buildBlocking(); Mqtt5ConnAck connAck = client.connect(); System.out.println("Connected: " + connAck.getReasonCode()); ``` -------------------------------- ### Mqtt5RxClient.publishWith() Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Fluent builder for reactive publish. Creates a single-message Flowable for publishing. ```APIDOC ## Mqtt5RxClient.publishWith() ### Description Fluent builder for reactive publish. Creates a single-message Flowable for publishing. ### Method ```java Mqtt5PublishBuilder.Send> publishWith() ``` ### Returns Builder returning `Flowable` ### Example ```java client.publishWith() .topic("home/temperature") .qos(MqttQos.AT_MOST_ONCE) .payload("22.5".getBytes()) .send() .subscribe(); ``` ``` -------------------------------- ### Subscribe and Consume Messages with Blocking API Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Example of subscribing to a topic and consuming incoming messages using the blocking API, including handling potential message loss and client disconnection. ```java final Mqtt5BlockingClient client = Mqtt5Client.builder() .identifier(UUID.randomUUID().toString()) .serverHost("broker.hivemq.com") .buildBlocking(); client.connect(); try (final Mqtt5Publishes publishes = client.publishes(MqttGlobalPublishFilter.ALL)) { client.subscribeWith().topicFilter("test/topic").qos(MqttQos.AT_LEAST_ONCE).send(); publishes.receive(1, TimeUnit.SECONDS).ifPresent(System.out::println); publishes.receive(100, TimeUnit.MILLISECONDS).ifPresent(System.out::println); } finally { client.disconnect(); } ``` -------------------------------- ### Handle Backpressure with Buffering Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/07-reactive-api.md Demonstrates how to handle backpressure by buffering incoming publishes and processing them on a separate IO thread. ```java Flowable incoming = client.publishes(MqttGlobalPublishFilter.ALL); incoming .onBackpressureBuffer(1000) // Buffer up to 1000 messages .observeOn(Schedulers.io()) // Process on IO thread .flatMap(publish -> processMessageAsync(publish)) .subscribe( result -> System.out.println("Processed: " + result), error -> System.out.println("Error: " + error), () -> System.out.println("Complete") ); client.subscribeWith() .topicFilter("data/#") .qos(MqttQos.AT_LEAST_ONCE) .send() .subscribe(); ``` -------------------------------- ### Subscribe to a Topic with QoS Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/README.md Illustrates how to subscribe to a topic filter with a specified Quality of Service level. This is used to receive messages from the broker. ```java client.subscribeWith() .topicFilter("my/topic") .qos(MqttQos.AT_LEAST_ONCE) .send(); ``` -------------------------------- ### Subscribe and Receive with Blocking Client Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/00-index.md Subscribe to a topic using the blocking API and receive messages within a specified timeout. This example uses a try-with-resources block for proper resource management. ```java try (Mqtt5BlockingClient.Mqtt5Publishes publishes = client.publishes(MqttGlobalPublishFilter.ALL)) { client.subscribeWith().topicFilter("my/topic").qos(MqttQos.AT_LEAST_ONCE).send(); var message = publishes.receive(10, TimeUnit.SECONDS); } ``` -------------------------------- ### Handle Reactive API Exceptions with Retry Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/05-exceptions.md Illustrates exception handling for the reactive API using doOnError and retry. This example specifically catches Mqtt5ConnAckException and retries the connection up to 3 times. ```java client.toRx().connect() .doOnError(throwable -> { if (throwable instanceof Mqtt5ConnAckException) { System.out.println("Connect failed"); } }) .retry(3) // Retry up to 3 times .subscribe(); ``` -------------------------------- ### Subscribe with Pre-built Message Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/README.md Subscribe to a topic using a pre-built Mqtt5Subscribe message object. This allows for more complex subscription configurations. ```java Mqtt5Subscribe subscribeMessage = Mqtt5Subscribe.builder() .topicFilter("test/topic") .qos(MqttQos.EXACTLY_ONCE) .build(); client.subscribe(subscribeMessage, System.out::println); client.subscribe(subscribeMessage, System.out::println, executor); ``` -------------------------------- ### Mqtt5Connect Builder Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/04-types-and-datatypes.md Illustrates how to construct an MQTT 5.0 Connect message using the builder pattern. This includes setting keep-alive, session expiry, WILL publish, and authentication details. ```APIDOC ## MQTT 5 Connect Messages ### Mqtt5Connect MQTT 5.0 Connect message for establishing connections. **Location:** `com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect` #### Creating Connect Messages ##### builder() ```java static Mqtt5ConnectBuilder builder() ``` Creates a builder for Connect messages. **Returns:** `Mqtt5ConnectBuilder` #### Key Properties (via builder) ```java Mqtt5Connect connect = Mqtt5Connect.builder() .keepAlive(30) // Seconds between pings .sessionExpiryInterval(3600) // Session timeout .willPublish() .topic("will/topic") .qos(MqttQos.AT_LEAST_ONCE) .payload("offline".getBytes()) .applyWillPublish() .simpleAuth() .username("user") .password("pass") .applySimpleAuth() .build(); ``` ``` -------------------------------- ### Handle ConnectionFailedException in Java Source: https://github.com/hivemq/hivemq-mqtt-client/blob/master/_autodocs/05-exceptions.md Demonstrates how to catch and handle ConnectionFailedException when establishing a connection using a blocking client. ```java try { client.connect().get(); } catch (ExecutionException e) { if (e.getCause() instanceof ConnectionFailedException) { ConnectionFailedException cfe = (ConnectionFailedException) e.getCause(); System.out.println("Connection failed: " + cfe.getMessage()); } } ```