-
Notifications
You must be signed in to change notification settings - Fork 2.6k
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
nmy6452
wants to merge
4
commits into
spring-projects:main
Choose a base branch
from
nmy6452:issue/323
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6543349
Add MQTT5 sample application with integration flows and tests
nmy6452 e29ae9c
FEAT: delete useless logback.xml
nmy6452 2af9a07
TEST: update assertions in ApplicationTest to use JUnit assertions
nmy6452 06bf9e9
FEAT: configure MQTT broker host and port using application properties
nmy6452 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
|
142 changes: 142 additions & 0 deletions
142
basic/mqtt5/src/main/java/org/springframework/integration/samples/mqtt5/Application.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
} |
51 changes: 51 additions & 0 deletions
51
...c/main/java/org/springframework/integration/samples/mqtt5/MqttStringToBytesConverter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
|
||
} |
60 changes: 60 additions & 0 deletions
60
basic/mqtt5/src/test/java/org/springframework/integration/samples/mqtt5/ApplicationTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
} | ||
} |
86 changes: 86 additions & 0 deletions
86
basic/mqtt5/src/test/java/org/springframework/integration/samples/mqtt5/BrokerRunning.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
|
||
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); | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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