Skip to content

Add MQTT5 sample application with integration flows and tests #365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ This is a good place to get started. The samples here are technically motivated
* **jpa** - Shows the usage of the JPA Components
* **mail** - Example showing **IMAP** and **POP3** support
* **mqtt** - Demonstrates the functionality of inbound and outbound **MQTT Adapters**
* **mqtt5** - Demonstrates the functionality of inbound and outbound **MQTT5 Adapters**
* **mongodb** - Shows how to persist a Message payload to a **MongoDb** document store and how to read documents from **MongoDb**
* **oddeven** - Example combining the functionality of **Inbound Channel Adapter**, **Filter**, **Router** and **Poller**
* **quote** - Example demoing core EIP support using **Channel Adapter (Inbound and Stdout)**, **Poller** with Interval Triggers, **Service Activator**
Expand Down
29 changes: 29 additions & 0 deletions basic/mqtt5/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
Spring Integration - MQTT5 Sample
================================

# Overview

This sample demonstrates basic functionality of the **Spring Integration MQTT5 Adapters**.

It assumes a broker is running on localhost on port 1883.

Once the application is started, you enter some text on the command prompt and a message containing that entered text is
dispatched to the MQTT topic. In return that message is retrieved by Spring Integration and then logged.

# How to Run the Sample

If you imported the example into your IDE, you can just run class **org.springframework.integration.samples.mqtt5.Application**.
For example in [SpringSource Tool Suite](https://www.springsource.com/developer/sts) (STS) do:

* Right-click on SampleSimple class --> Run As --> Spring Boot App

(or run from the boot console).

Alternatively, you can start the sample from the command line:

* ./gradlew :mqtt5:run

Enter some data (e.g. `foo`) on the console; you will see `foo sent to MQTT5, received from MQTT5`

Ctrl-C to terminate.

Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* Copyright 2025 the original author or authors.
*
* 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
*
* https://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 org.springframework.integration.samples.mqtt5;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.Pollers;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.handler.LoggingHandler;
import org.springframework.integration.mqtt.inbound.Mqttv5PahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.Mqttv5PahoMessageHandler;
import org.springframework.integration.stream.CharacterStreamReadingMessageSource;
import org.springframework.messaging.MessageHandler;

import java.nio.charset.StandardCharsets;

/**
* Starts the Spring Context and will initialize the Spring Integration message flow.
*
* @author Minyoung Noh
*
*/
@SpringBootApplication
public class Application {

@Value("${mqtt.broker.host:localhost}")
private String mqttHost;

@Value("${mqtt.broker.port:1883}")
private int mqttPort;

private static final Log LOGGER = LogFactory.getLog(Application.class);

/**
* Load the Spring Integration Application Context
*
* @param args - command line arguments
*/
public static void main(final String... args) {

LOGGER.info("\n========================================================="
+ "\n "
+ "\n Welcome to Spring Integration! "
+ "\n "
+ "\n For more information please visit: "
+ "\n https://spring.io/projects/spring-integration "
+ "\n "
+ "\n=========================================================");

LOGGER.info("\n========================================================="
+ "\n "
+ "\n This is the MQTT5 Sample - "
+ "\n "
+ "\n Please enter some text and press return. The entered "
+ "\n Message will be sent to the configured MQTT topic, "
+ "\n then again immediately retrieved from the Message "
+ "\n Broker and ultimately printed to the command line. "
+ "\n "
+ "\n=========================================================");

SpringApplication.run(Application.class, args);
}

@Bean
public MqttConnectionOptions mqttConnectionOptions() {
MqttConnectionOptions options = new MqttConnectionOptions();
options.setServerURIs(new String[]{ String.format("tcp://%s:%d", mqttHost, mqttPort) });
options.setUserName("guest");
options.setPassword("guest".getBytes(StandardCharsets.UTF_8));
return options;
}

// publisher

@Bean
public IntegrationFlow mqttOutFlow() {
return IntegrationFlow.from(CharacterStreamReadingMessageSource.stdin(),
e -> e.poller(Pollers.fixedDelay(1000)))
.transform(p -> p + " sent to MQTT5")
.handle(mqttOutbound())
.get();
}

@Bean
public MessageHandler mqttOutbound() {
Mqttv5PahoMessageHandler messageHandler = new Mqttv5PahoMessageHandler(mqttConnectionOptions(), "siSamplePublisher");
messageHandler.setAsync(true);
messageHandler.setAsyncEvents(true);
messageHandler.setDefaultTopic("siSampleTopic");
return messageHandler;
}

// consumer

@Bean
public IntegrationFlow mqttInFlow() {
return IntegrationFlow.from(mqttInbound())
.transform(p -> p + ", received from MQTT5")
.handle(logger())
.get();
}

private LoggingHandler logger() {
LoggingHandler loggingHandler = new LoggingHandler("INFO");
loggingHandler.setLoggerName("siSample");
return loggingHandler;
}

@Bean
public MessageProducerSupport mqttInbound() {
Mqttv5PahoMessageDrivenChannelAdapter adapter =
new Mqttv5PahoMessageDrivenChannelAdapter(mqttConnectionOptions(),"siSampleConsumer", "siSampleTopic");
adapter.setCompletionTimeout(5000);
adapter.setPayloadType(String.class);
adapter.setMessageConverter(new MqttStringToBytesConverter());
adapter.setQos(1);
return adapter;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2025 the original author or authors.
*
* 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
*
* https://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 org.springframework.integration.samples.mqtt5;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.AbstractMessageConverter;

import java.nio.charset.StandardCharsets;

/**
* A simple {@link AbstractMessageConverter} that converts
*
* @author Minyoung Noh
* @since 5.2
*
*/
public class MqttStringToBytesConverter extends AbstractMessageConverter {
@Override
protected boolean supports(Class<?> clazz) {
return true;
}

@Override
protected Object convertFromInternal(Message<?> message, Class<?> targetClass,
Object conversionHint) {

return message.getPayload().toString().getBytes(StandardCharsets.UTF_8);
}

@Override
protected Object convertToInternal(Object payload, MessageHeaders headers,
Object conversionHint) {

return new String((byte[]) payload);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package org.springframework.integration.samples.mqtt5;

import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.springframework.integration.test.mock.MockIntegration.messageArgumentCaptor;
import static org.springframework.integration.test.mock.MockIntegration.mockMessageHandler;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.test.context.MockIntegrationContext;
import org.springframework.integration.test.context.SpringIntegrationTest;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@SpringIntegrationTest
public class ApplicationTest {

@BeforeAll
static void setupBroker() {
BrokerRunning brokerRunning = BrokerRunning.isRunning(1883);
}

@Autowired
private MockIntegrationContext mockIntegrationContext;

@Autowired
private IntegrationFlow mqttOutFlow;

@Test
void testMqttFlow() throws InterruptedException {
ArgumentCaptor<Message<?>> captor = messageArgumentCaptor();
CountDownLatch receiveLatch = new CountDownLatch(1);
MessageHandler mockMessageHandler = mockMessageHandler(captor).handleNext(m -> receiveLatch.countDown());

mockIntegrationContext.substituteMessageHandlerFor(
"mqttInFlow.org.springframework.integration.config.ConsumerEndpointFactoryBean#1",
mockMessageHandler);

mqttOutFlow.getInputChannel().send(new GenericMessage<>("foo"));

assertTrue(receiveLatch.await(10, TimeUnit.SECONDS));
verify(mockMessageHandler).handleMessage(any());
assertEquals("foo sent to MQTT5, received from MQTT5",captor.getValue().getPayload());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright 2025 the original author or authors.
*
* 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
*
* https://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 org.springframework.integration.samples.mqtt5;

import static org.junit.Assume.assumeNoException;
import static org.junit.Assume.assumeTrue;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.mqttv5.client.IMqttClient;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;


/**
* @author Minyoung Noh
*
* @since 5.2
*
*/
public class BrokerRunning extends TestWatcher {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove BrokerRunning as the method for testing the MQTT5 app. Please use the Mosquitto test container as shown here: https://github.com/spring-projects/spring-integration/blob/main/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttDslTests.java


private static final Log logger = LogFactory.getLog(BrokerRunning.class);

// Static so that we only test once on failure: speeds up test suite
private static final Map<Integer, Boolean> brokerOnline = new HashMap<>();

private final int port;

private BrokerRunning(int port) {
this.port = port;
brokerOnline.put(port, true);
}

@Override
public Statement apply(Statement base, Description description) {
assumeTrue(brokerOnline.get(port));
String url = "tcp://localhost:" + port;
IMqttClient client = null;
try {
client = new MqttClient(url, "junit-" + System.currentTimeMillis());
client.connect();
}
catch (MqttException e) {
logger.warn("Tests not running because no broker on " + url + ":", e);
assumeNoException(e);
}
finally {
if (client != null) {
try {
client.disconnect();
client.close();
}
catch (MqttException e) {
}
}
}
return super.apply(base, description);
}


public static BrokerRunning isRunning(int port) {
return new BrokerRunning(port);
}

}
Loading