Additional HiveMQ Enterprise Extension SDK Services

The HiveMQ Enterprise Extension SDK adds several powerful services to the extension framework that specifically focus on the additional features the HiveMQ Enterprise and Professional Editions provide.

Access to the HiveMQ Enterprise Extension SDK requires certification.

Once certified, you can use the services of the HiveMQ Enterprise Extension SDK to build and implement valid extensions for your Professional or Enterprise version of HiveMQ.

To learn more about HiveMQ Enterprise Extension SDK certification training or request scheduling and pricing information, contact HiveMQ sales.

Consumer Service

The Consumer Service allows you to register and unregister message consumers. Message consumers can be used to react quickly to incoming publishes on a specific set of topics and further process the consumed messages however your business case requires.

The Consumer Service is great fit when you want to write all or specific incoming publish messages to a third party system. For example, the HiveMQ Enterprise Extension for Kafka uses the Consumer Service to transform MQTT publish messages into Kafka records and then write the records into Kafka.

Each consumer must be registered with a unique consumer ID and defined consumer options.

The Consumer Service allows extensions to do the following:

The extension that runs the consumer must be registered on every node in the HiveMQ cluster.

Consumer Options

Consumer options describe the intended use of the consumer.
The definition of Consumer Options is mandatory for each consumer that you want to implement.

Table 1. Available Consumer Options
Option Description

Topic Filters

Sets all the configured topic filters for the selected consumer option.

Queue Limit

Sets the queue limit of the consumer per topic filter. The default value is 500000.

Example consumer options
final ConsumerOptions consumerOptions = EnterpriseBuilders.consumerOptions()
        .topicFilters("+/IN/#", "+/OUT/#")
        .queueLimit(1_000_000).build();

Create a Consumer

A message consumer is called whenever the broker receives an incoming publish messages that matches the topic filters for which the consumer is registered. When you use the Message Consumer Interface, only the method for consuming messages must be implemented. To avoid blocking the consumer, we recommend the use of an async wrapper.

This example show how to create a simple message consumer.

Example to create a message consumer
    public class MySimpleConsumer implements MessageConsumer {
        @Override
        public void consume(@NotNull ConsumerInput consumerInput, @NotNull ConsumerOutput consumerOutput) {
            final PublishPacket publishPacket = consumerInput.getPublish();
            final Async<ConsumerOutput> async = consumerOutput.async(Duration.ofSeconds(2));
            Services.extensionExecutorService().submit(() -> doSomethingWith(publishPacket, async));
        }
        private void doSomethingWith(final @NotNull PublishPacket publishPacket, final @NotNull Async<ConsumerOutput> async) {
            try {
                //your business logic
            } catch (Exception any) {
                async.getOutput().cancelConsumption();
            } finally {
                async.resume();
            }
        }
    }

ConsumerOutput marks this operation as async.

  • Always call Async.resume(), regardless of whether an operation is successful or unsuccessful.

  • If the timeout expires before Async.resume() is called, then the outcome is handled as failed.

  • Do not call this method more than once. If an async method is called multiple times an exception is thrown.

CancelConsumption() indicates a PUBLISH message was not consumed. Use this method to cancel unprocessed messages when you shut down your consumer.
The QoS of the canceled message determines the exact processing of the message:

  • Cancelled messages with QoS 0 (at most once) are discarded.

  • Cancelled messages with QoS 1 (at least once) or QoS 2 (exactly once) are offered again later to the same consumer (determined by consumer ID) on the current node.

Make sure that your business logic prevents endless retry loops for messages that fail and get cancelled.

Access the Consumer Service

EnterpriseServices.consumerService()

Register a Consumer with Options to HiveMQ

Before you work with a consumer, the consumer must be registered. Consumer registration is ideally done at the start of the extension. To register a consumer with options to HiveMQ, you need the unique ID of the consumer and the associated consumer options definition.

This example shows a consumer registration with consumer options.

EnterpriseServices.consumerService()
  .registerConsumer(consumerId, consumerOptions, new MessageConsumerProvider() {
      @Override
      public @NotNull MessageConsumer get() {
          return myConsumer;
      }
  });

The Message Consumer interface contains an init method that can be optionally overwritten.

When you register your consumer implementation, HiveMQ calls the init method with the defined consumer options as the parameters.

This example shows the init method with the consumer options that where provided when the consumer was registered, and the custom code that is needed for the specific consumer.

public void init(final @NotNull ConsumerOptions consumerOptions) {
   log.info("Initialize myConsumer");
}
Full Example Code
final ConsumerOptions consumerOptions = EnterpriseBuilders.consumerOptions().topicFilters("+/STAT").build();
final String consumerId = "myConsumerId";
final MessageConsumer myConsumer = new MySimpleConsumer();

final CompletableFuture<Void> registerFuture =
       EnterpriseServices.consumerService()
               .registerConsumer(consumerId, consumerOptions, new MessageConsumerProvider() {
                   @Override
                   public @NotNull MessageConsumer get() {
                       return myConsumer;
                   }
               });

registerFuture.whenComplete((aVoid, throwable) -> {
   if (throwable == null) {
       log.info("Consumer {} started.", consumerId);
   } else {
       log.warn("Not able to start  Consumer \"{}\", reason:", throwable.getMessage());
   }
});
The HiveMQ consumer API is built for high performance that allows asynchronous and simultaneous thread handling. To ensure consistency, the business logic you implement must be thread-safe.

Remove a Consumer from HiveMQ

It is best practice to unregister and remove consumers that you no longer plan to use.
Consumer removal is usually done when the extension stops.

This example shows how to remove a consumer with options from HiveMQ.

EnterpriseServices.consumerService().removeConsumer(consumerId);

The Message Consumer interface contains a destroy method that can be optionally overwritten.

When you remove your consumer, HiveMQ calls the destroy method with the defined consumer options. A consumer can be destroyed during runtime and additional code can be added via the destroy method.

This example shows the destroy method with the consumer options that where provided when the consumer was registered, and the custom code the specific consumer needs.

public void destroy(final @NotNull ConsumerOptions consumerOptions) {
    log.info("Destroy myConsumer");
}

Get All Consumers

If your extension uses multiple consumers, the ability to retrieve a map of all consumers that are registered to the extension can be very helpful. The key-value pairs that the method returns show the consumer ID and the modifiable consumer options for each consumer.

This example shows how to get a map of all consumers registered to the extension:

final @NotNull Map<String, @NotNull ModifiableConsumerOptions> myConsumers = EnterpriseServices.consumerService().getConsumers();

Get Options for a Specific Consumer

This example shows how to get the options for a specific consumer.

EnterpriseServices.consumerService().getConsumerOptions(“myConsumerId”);
Consumer options can be modified. This ability can be very helpful when a topic structure must be changed during runtime.
Example Code
final @NotNull Optional<ModifiableConsumerOptions> options = EnterpriseServices.consumerService().getConsumerOptions(consumerId);
if( options.isPresent()) {
   options.get().removeTopicFilter("+/STATUS");
   options.get().addTopicFilter("+/ERROR");
}

Session Attribute Store

This service allows an extension to manage the session attributes of clients that have the same lifecycle as the existing MQTT client session of your HiveMQ broker.

The Session Attribute Store manages the sessions of clients that have an existing session. The service cannot be used to add a client session.

The Sessions Attribute Store allows extensions to do the following:

You can also view the session attributes of a client on the client detail pages in your HiveMQ Control Center.
For more information, see Control Center Session Attributes.

Access the Session Attribute Store Interface

EnterpriseServices.sessionAttributeStore()
The earliest point that you can use the session attribute store for the client is the InitializerInput callback. This method is called when a client connects to a new or existing session. The method is also called for online clients when the extension starts.

Get All Session Attributes for a Client

This example shows how to retrieve all session attributes for a client with a specific client ID.

final @NotNull CompletableFuture<Map<String, ByteBuffer>> attributes = EnterpriseServices.sessionAttributeStore().getAll(clientId);
attributes.whenComplete( (aMap, throwable) -> {
   if (throwable == null) {
       log.info("Attributes found", aMap.keySet());
       checkAttributes(aMap);
   } else {
       log.warn("Exception with reason:", throwable.getMessage());
   }
});

Clear All Session Attributes for a Client

This example shows how to remove all session attributes from a specific client.

final String clientId = initializerInput.getClientInformation().getClientId();
EnterpriseServices.sessionAttributeStore().clear(clientId);

Add a Session Attribute to a Client

This example shows how to add a session attribute to a specific client.

EnterpriseServices.sessionAttributeStore().put(clientId, "myAttributeKey",
    ByteBuffer.wrap("myAttributeValue".getBytes(StandardCharsets.UTF_8)));
The session attribute that you set for the client must contain a key and a value. The maximum key length is 65535 characters. The maximum value size is 5 MB. Null values are not permitted.

Get a Specific Session Attribute for a Client

This example shows how to retrieve a specific session attribute of a specific client.

final @NotNull CompletableFuture<Optional<ByteBuffer>> myAttributeValue = EnterpriseServices.sessionAttributeStore().get(clientId, "myAttributeKey");
myAttributeValue.whenComplete( (aBuffer, throwable) -> {
   if (throwable == null) {
       if (aBuffer.isPresent()) {
          log.info("Attribute found", getValueAsStringFrom(aBuffer.get()));
       } else {
          log.info("Attribute not found");
       }
   } else {
       log.warn("Exception with reason:", throwable.getMessage());
   }
});
To get the desired session attribute from the Session Attribute Store, you must have the attribute key and client ID.

Remove a Specific Session Attribute from a Client

This example shows how to remove a specific session attribute of a specific client.

EnterpriseServices.sessionAttributeStore().remove(clientId,"myAttributeKey");
To remove the desired session attribute from the Session Attribute Store, you must have the attribute key and client ID.

Extension Messaging Service

The Extension Messaging Service makes it possible to send non-MQTT messages through the cluster and is intended for internal cluster traffic/communication between the extensions that run on the HiveMQ instances in your cluster.

The service is helpful when your use case requires the exchange of client information or data that is distributed over the cluster to be fully available on all nodes.

The ExtensionMessagingService allows extensions to do the following:

Define Extension Messaging Broadcast Options

The BroadcastMode of the Extension Messaging Service allows you to configure to which nodes information is sent.
The following options are available:

  • ALL: Sends information to all nodes in the cluster and includes the originating node.

  • OTHER: Sends information to the other nodes in the cluster and omits the originating node.

This example shows how to set the options to send information to all nodes in a cluster, omitting the originating node.

EnterpriseBuilders.extensionMessageOptions().mode(BroadcastMode.OTHERS).build()

Register Message Response to Receive Messages for a Specific Identifier

This example shows how to register to receive responses for a specific identifier to receive messages sent for the identifier with the Extension Messaging Service.

EnterpriseServices.extensionMessagingService()
    .register(MY_MESSAGE_ID, new MySimpleMessagingService.MySimpleRespondCallback());
When multiple extensions register a response callback for the same ID, the extension with the highest priority overrides any previous registration. Every extensionMessageCallback is removed after extension stop.

Send Messages for a Specific Identifier

This example shows how to send a message with ExtensionMessageOptions for a specific identifier with the Extension Messaging Service.
Every registered ExtensionMessageCallback with the specific identifier receives this message and can respond with a reply message.

The method returns a list of completable futures that contain the reply messages from all callbacks registered with the same identifier.

final List<CompletableFuture<ExtensionMessageResponse>> responseList =
    EnterpriseServices.extensionMessagingService.send(MY_MESSAGE_ID,
                                                        new byte[0],
                                                        extensionMessageOptions);
The completable futures of this method can fail throw an exception for the following reasons:
- A message is sent to a cluster node that runs a HiveMQ version older than 4.1.0.
- A message is sent to a cluster node that does not have a callback registered for the selected identifier.
- A message is sent to a cluster node that is currently not reachable.

Respond to Received Messages

This example shows how to complete message communication with a response.

static class MyRespondCallback implements ExtensionMessageCallback {
    ...

    @Override
    public void receive(@NotNull ExtensionMessage extensionMessage) {
        ...
        extensionMessage.respond(serializedResponseData);
        ...
    }
}
Full Example Code
public class MySimpleMessagingService {
   private static final Logger log = LoggerFactory.getLogger(MySimpleMessagingService.class);
   private static final @NotNull String MY_MESSAGE_ID = "MySimpleMessagingService";
   private final @NotNull ExtensionMessagingService extensionMessagingService;
   private final @NotNull ScheduledExecutorService scheduledExecutorService;

   public MySimpleMessagingService(final @NotNull ExtensionMessagingService extensionMessagingService,
                                   final @NotNull ScheduledExecutorService scheduledExecutorService) {
       this.extensionMessagingService = extensionMessagingService;
       this.scheduledExecutorService = scheduledExecutorService;
   }

   public void start() {
       extensionMessagingService.register(MY_MESSAGE_ID, new MySimpleMessagingService.MySimpleRespondCallback());
       scheduledExecutorService.scheduleAtFixedRate(this::send, 1, 1, TimeUnit.MINUTES);
   }

   public void stop() {
       extensionMessagingService.unregister(MY_MESSAGE_ID);
   }

   private void send() {
       byte[] data =  createDataToSend();
       //Send Message in the cluster and retrieve responses from other nodes
       final List<CompletableFuture<ExtensionMessageResponse>> responseList =
               extensionMessagingService.send(
                       MY_MESSAGE_ID,
                       data,
                       EnterpriseBuilders.extensionMessageOptions().mode(BroadcastMode.OTHERS).build());

       CompletableFuture.allOf(responseList.toArray(new CompletableFuture[]{}))
               .exceptionally(throwable -> null)
               .thenAccept(aVoid -> {
                   for (CompletableFuture<ExtensionMessageResponse> responseCompletableFuture : responseList) {
                       try {
                           final ExtensionMessageResponse response = responseCompletableFuture.get();
                           processDataFromResponse(response.getClusterNodeId(), response.getMessage());
                       } catch (ExecutionException | InterruptedException any) {
                           log.error(" Requesting response of data failed: ", any);
                       }
                   }
               });
   }

   private byte[] createDataToSend() {
       log.info("Create data to Send ");
       return RandomUtils.nextBytes(200);
   }

   private void processDataFromResponse(String clusterNodeId, byte[] message) {
       log.info("got response from {} ", clusterNodeId);
   }

   /**
    * The callback that receives an ExtensionMessage must respond in any case.
    */
   static class MySimpleRespondCallback implements ExtensionMessageCallback {
       boolean success = false;

       @Override
       public void receive(@NotNull ExtensionMessage message) {
           try {
               success = createRespond(message.receive());
           } finally {
               message.respond(new byte[]{(byte) (success ? 1 : 0)});
           }
       }

       private boolean createRespond(byte[] data) {
           return true;
       }
   }
}
When you implement the Extension Messaging Service, you must register a response callback that generates a response for each ExtensionMessage received. It is absolutely necessary for your response callback to respond in all cases to every ExtensionMessage.

Unregister to Stop Receiving Messages for a Specific Identifier

This example shows how to unregister a response to stop receiving messages for a specific identifier through the Extension Messaging Service.

extensionMessagingService.unregister(MY_MESSAGE_ID);

Control Center Service

Use this service to add custom views or notifications to the HiveMQ Control Center.

The Control Center Service allows extensions to do the following:

Access the Control Center Service

EnterpriseServices.controlCenterService()

Add Authentication to the HiveMQ Control Center

The Control Center Service allows extensions to add an authenticator for the HiveMQ Control Center users.

The HiveMQ Control Center can be configured with multiple users who each have a username and password (SHA256 and username prepended salt). For more information, see HiveMQ Control Center User Configuration.

The HiveMQ Enterprise Edition supports Role Based Access Control (RBAC) for Control Center users. RBAC gives you the ability to restrict user permissions and precisely control which users can view, access, and modify data. With RBAC, you can create fine-grained access management for your HiveMQ system.

This example shows how to add an authenticator to the HiveMQ Control Center.

//Implementation of the authenticator
public class MyControlCenterAuthenticator implements ControlCenterAuthenticator {
    private static final String MY_DASHBOARD_VIEW = "MY_DASHBOARD_VIEW";

    @Override
    public void onLogin(@NotNull ControlCenterAuthInput controlCenterAuthInput, @NotNull ControlCenterAuthOutput controlCenterAuthOutput) { ... }
}

//usage
EnterpriseServices.controlCenterService().setAuthenticator(new MyControlCenterAuthenticator());

View and Add Control Center Permissions

This example shows how to view and add HiveMQ Control Center permissions.

final @NotNull ControlCenterPermission permission =
EnterpriseBuilders.controlCenterPermission()
.id(MY_DASHBOARD_VIEW)
.displayName("View My Dashboard")
.description("View My Dashboard Permission")
.group("CUSTOM").build();

EnterpriseServices.controlCenterService().addPermission(permission);

//Use permission by setting in ControlCenterAuthenticator Output for the logged-in user
//See full list of permissions from
// https://www.hivemq.com/docs/ese/latest/enterprise-security-extension/ese.html#control-center-access-control

controlCenterAuthOutput.getUserPermissions().add(MY_DASHBOARD_VIEW);

Add Custom Control Center Views

The Control Center Service allows extensions to add single extension views or views with subviews to the HiveMQ Control Center.

This example adds a new view to the HiveMQ Control Center.

EnterpriseServices.controlCenterService().addView(new MyExtensionView(myViewDataProvider);
View details must be implemented with use of Vaadin libraries and CSS. Vaadin is an open-source platform for web application development.
Create a Custom Extension View for the HiveMQ Control Center

Implementation of your custom extension view must include the following:

  • Your extension icon. The default is a plug icon.

  • The title of your extension view

  • The URL that appears for this view in the browser

  • A permission ID to return the needed Permission for this view

  • The view itself provided as a Vaadin View

Based on your custom extension view, these implementation elements are optional:

  • A selected URL that is suitable if your subview does not have a URL

  • A menu title

  • The associated CSS

The view must be created each time, because it will be shown currently on the specific website request. If not it could happen, that the view is not actual and user X is getting the data of the view that User Y has requested.

public class MyDashboardView implements ExtensionView {

    public MyDashboardView() { … }
    @Override
    public @NotNull String getTitle() { return "My Dashboard"; }
    @Override
    public @NotNull String getUrl() { return "MyDashboard"; }
    @Override
    public @Nullable String getCss() { return "VAADIN/myExtension.css";}
    @Override
    public @NotNull View getView() { return new DemoView(); }

    @Nullable
    public String getPermissionId() {  return "MY_DASHBOARD_VIEW"; }

    private class DemoView implements View { … }
}

Add or Remove HiveMQ Control Center Notifications

This example shows how to add or remove notifications from the HiveMQ Control Center.

@NotNull Notification myNotification;
myNotification = new Notification() {
@Override
public @NotNull String getMessage() { return "Hello from myExtension"; }
@Override
public @NotNull NotificationLevel getLevel() { return NotificationLevel.INFO; }
};

EnterpriseServices.controlCenterService().addNotification(myNotification);
EnterpriseServices.controlCenterService().removeNotification(myNotification);

REST Service

The HiveMQ REST Service allows extensions to create accessible HTTP APIs directly within HiveMQ. Any HTTP content can be served directly from HiveMQ.

The REST Service allows extensions to do the following:

The JAX-RS resources can be used to interact with HiveMQ by using other services. Interaction with HiveMQ is not necessary, you can also use the internal HTTP server of HiveMQ to avoid setting up an external HTTP server for your existing JAX-RS resources.

Access the HiveMQ REST API Service

EnterpriseServices.restService()

Register a Custom REST API Application

This example shows how to register a custom REST API application with the HiveMQ REST API service.

When you register a custom REST API application with the HiveMQ REST API Service, The base path for all resources is automatically determined by the extension ID: /api/v1/extensions/{extension-id}/.
At most one REST application can be set.

//simple example for rest service usage
Resource r = new Resource("backend");
try {
   EnterpriseServices.restService().setRestApplication(() -> List.of(r));
} catch (FeatureDisabledException disabledException) {
   //ignore
   log.error("REST-API is not enabled in config.xml");
}
The REST API must be enabled in the configuration file of your HiveMQ instance (config.xml).

Remove a Custom REST API Application

This example shows how to stop and remove a custom REST API application from the HiveMQ REST API service:

EnterpriseServices.restService().removeRestApplication();

Client Event Service

The Client Event Service allows extensions to do the following:

  • Iterate the events of a specific client in a defined time frame

Before you use the Client Event Service, make sure that the Client Event History feature is enabled in the config.xml file of your HiveMQ instance.
    <client-event-history>
        <enabled>true</enabled>
        <lifetime>604800</lifetime> <!-- 7 days -->
    </client-event-history>

Access the Client Event Service

EnterpriseServices.clientEventService()
Based on the time frame you define, the operation of this method can be expensive in large scale deployments. For example, do not call this method with long time frames (multiple days) in a loop for multiple clients.

Iterate Events for Client

This example shows how to iterate the events of a specified client in a defined time frame.

EnterpriseServices.clientEventService().iterateEventsForClient(clientId, from, to, (context, event) -> {
   switch (event.getType()) {
       case OVERLOAD_PROTECTION_ON: {
           resource.getClientStates().add( OVERLOAD_PROTECTION_ON.toString());
           break;
       }
       case OVERLOAD_PROTECTION_OFF: {
           resource.getClientStates().add( OVERLOAD_PROTECTION_OFF.toString());
           break;
       }
       case DISCONNECT_BY_CLIENT_GRACEFUL:
       case DISCONNECT_BY_CLIENT_UNGRACEFUL:
       case DISCONNECT_BY_SERVER:
       {
           resource.getClientStates().add(event.toString());
           context.abortIteration();
           break;
       }
   }
});

The Client Event Service can identify the following types of events:

  • CONNECT_SUCCEEDED

  • CONNECT_FAILED

  • DISCONNECT_BY_CLIENT_GRACEFUL

  • DISCONNECT_BY_CLIENT_UNGRACEFUL

  • DISCONNECT_BY_SERVER

  • SESSION_REMOVED

  • OVERLOAD_PROTECTION_ON

  • OVERLOAD_PROTECTION_OFF

Next Steps

To learn more about the possibilities HiveMQ extensions offer and view code examples for several frequently implemented HiveMQ extension use cases, see Popular HiveMQ Extension Use Cases