Search in sources :

Example 6 with DefaultMqttPahoClientFactory

use of org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory in project spring-integration by spring-projects.

the class MqttAdapterTests method testDifferentQos.

@Test
public void testDifferentQos() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);
    factory = spy(factory);
    MqttAsyncClient aClient = mock(MqttAsyncClient.class);
    final MqttClient client = mock(MqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
    given(client.isConnected()).willReturn(true);
    new DirectFieldAccessor(client).setPropertyValue("aClient", aClient);
    willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class));
    willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class));
    willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any());
    IMqttToken token = mock(IMqttToken.class);
    given(token.getGrantedQos()).willReturn(new int[] { 2, 0 });
    willReturn(token).given(aClient).subscribe(any(String[].class), any(int[].class), any(), any());
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
    AtomicReference<Method> method = new AtomicReference<>();
    ReflectionUtils.doWithMethods(MqttPahoMessageDrivenChannelAdapter.class, m -> {
        m.setAccessible(true);
        method.set(m);
    }, m -> m.getName().equals("connectAndSubscribe"));
    assertNotNull(method.get());
    Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class));
    new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
    given(logger.isWarnEnabled()).willReturn(true);
    method.get().invoke(adapter);
    verify(logger, atLeastOnce()).warn("Granted QOS different to Requested QOS; topics: [baz, fix] requested: [1, 1] granted: [2, 0]");
    verify(client).setTimeToWait(30_000L);
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Log(org.apache.commons.logging.Log) SocketFactory(javax.net.SocketFactory) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) AtomicReference(java.util.concurrent.atomic.AtomicReference) Method(java.lang.reflect.Method) Properties(java.util.Properties) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) CallsRealMethods(org.mockito.internal.stubbing.answers.CallsRealMethods) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

Example 7 with DefaultMqttPahoClientFactory

use of org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory in project spring-integration by spring-projects.

the class MqttAdapterTests method buildAdapter.

private MqttPahoMessageDrivenChannelAdapter buildAdapter(final IMqttClient client, Boolean cleanSession, ConsumerStopAction action) throws MqttException {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory() {

        @Override
        public IMqttClient getClientInstance(String uri, String clientId) throws MqttException {
            return client;
        }
    };
    factory.setServerURIs("tcp://localhost:1883");
    if (cleanSession != null) {
        factory.setCleanSession(cleanSession);
    }
    if (action != null) {
        factory.setConsumerStopAction(action);
    }
    given(client.isConnected()).willReturn(true);
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("client", factory, "foo");
    adapter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    adapter.setOutputChannel(new NullChannel());
    adapter.setTaskScheduler(mock(TaskScheduler.class));
    adapter.afterPropertiesSet();
    return adapter;
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TaskScheduler(org.springframework.scheduling.TaskScheduler) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) NullChannel(org.springframework.integration.channel.NullChannel)

Example 8 with DefaultMqttPahoClientFactory

use of org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory in project spring-integration by spring-projects.

the class MqttAdapterTests method testOutboundOptionsApplied.

@Test
public void testOutboundOptionsApplied() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);
    factory = spy(factory);
    final MqttAsyncClient client = mock(MqttAsyncClient.class);
    willAnswer(invocation -> client).given(factory).getAsyncClientInstance(anyString(), anyString());
    MqttPahoMessageHandler handler = new MqttPahoMessageHandler("foo", "bar", factory);
    handler.setDefaultTopic("mqtt-foo");
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    final MqttToken token = mock(MqttToken.class);
    final AtomicBoolean connectCalled = new AtomicBoolean();
    willAnswer(invocation -> {
        MqttConnectOptions options = invocation.getArgument(0);
        assertEquals(23, options.getConnectionTimeout());
        assertEquals(45, options.getKeepAliveInterval());
        assertEquals("pass", new String(options.getPassword()));
        assertSame(socketFactory, options.getSocketFactory());
        assertSame(props, options.getSSLProperties());
        assertEquals("user", options.getUserName());
        assertEquals("foo", options.getWillDestination());
        assertEquals("bar", new String(options.getWillMessage().getPayload()));
        assertEquals(2, options.getWillMessage().getQos());
        connectCalled.set(true);
        return token;
    }).given(client).connect(any(MqttConnectOptions.class));
    willReturn(token).given(client).subscribe(any(String[].class), any(int[].class));
    final MqttDeliveryToken deliveryToken = mock(MqttDeliveryToken.class);
    final AtomicBoolean publishCalled = new AtomicBoolean();
    willAnswer(invocation -> {
        assertEquals("mqtt-foo", invocation.getArguments()[0]);
        MqttMessage message = invocation.getArgument(1);
        assertEquals("Hello, world!", new String(message.getPayload()));
        publishCalled.set(true);
        return deliveryToken;
    }).given(client).publish(anyString(), any(MqttMessage.class));
    handler.handleMessage(new GenericMessage<String>("Hello, world!"));
    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) SocketFactory(javax.net.SocketFactory) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) MqttToken(org.eclipse.paho.client.mqttv3.MqttToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) MqttAsyncClient(org.eclipse.paho.client.mqttv3.MqttAsyncClient) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttPahoMessageHandler(org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler) BeanFactory(org.springframework.beans.factory.BeanFactory) MqttDeliveryToken(org.eclipse.paho.client.mqttv3.MqttDeliveryToken) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

Example 9 with DefaultMqttPahoClientFactory

use of org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory in project spring-integration by spring-projects.

the class BrokerRunning method apply.

@Override
public Statement apply(Statement base, Description description) {
    assumeTrue(brokerOnline.get(port));
    String url = "tcp://localhost:" + port;
    IMqttClient client = null;
    try {
        client = new DefaultMqttPahoClientFactory().getClientInstance(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);
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MqttException(org.eclipse.paho.client.mqttv3.MqttException) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient)

Example 10 with DefaultMqttPahoClientFactory

use of org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory in project spring-integration by spring-projects.

the class BackToBackAdapterTests method testAsyncPersisted.

@Test
public void testAsyncPersisted() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    MqttClientPersistence persistence = new MqttDefaultFilePersistence(folder.getRoot().getAbsolutePath());
    factory.setPersistence(persistence);
    MqttPahoMessageHandler adapter = new MqttPahoMessageHandler("tcp://localhost:1883", "si-test-out", factory);
    adapter.setDefaultTopic("mqtt-foo");
    adapter.setBeanFactory(mock(BeanFactory.class));
    adapter.setAsync(true);
    adapter.setAsyncEvents(true);
    adapter.setDefaultQos(1);
    EventPublisher publisher1 = new EventPublisher();
    adapter.setApplicationEventPublisher(publisher1);
    adapter.afterPropertiesSet();
    adapter.start();
    MqttPahoMessageDrivenChannelAdapter inbound = new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883", "si-test-in", "mqtt-foo", "mqtt-bar");
    QueueChannel outputChannel = new QueueChannel();
    inbound.setOutputChannel(outputChannel);
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    inbound.setTaskScheduler(taskScheduler);
    inbound.setBeanFactory(mock(BeanFactory.class));
    inbound.afterPropertiesSet();
    inbound.start();
    Message<String> message1 = new GenericMessage<String>("foo");
    adapter.handleMessage(message1);
    verifyEvents(adapter, publisher1, message1);
    Message<String> message2 = MessageBuilder.withPayload("bar").setHeader(MqttHeaders.TOPIC, "mqtt-bar").build();
    EventPublisher publisher2 = new EventPublisher();
    adapter.setApplicationEventPublisher(publisher2);
    adapter.handleMessage(message2);
    verifyEvents(adapter, publisher2, message2);
    verifyMessageIds(publisher1, publisher2);
    int clientInstance = publisher1.delivered.getClientInstance();
    adapter.stop();
    // new client instance
    adapter.start();
    publisher1 = new EventPublisher();
    adapter.setApplicationEventPublisher(publisher1);
    adapter.handleMessage(message1);
    verifyEvents(adapter, publisher1, message1);
    publisher2 = new EventPublisher();
    adapter.setApplicationEventPublisher(publisher2);
    adapter.handleMessage(message2);
    verifyEvents(adapter, publisher2, message2);
    verifyMessageIds(publisher1, publisher2);
    assertNotEquals(clientInstance, publisher1.delivered.getClientInstance());
    Message<?> out = null;
    for (int i = 0; i < 4; i++) {
        out = outputChannel.receive(20000);
        assertNotNull(out);
        if ("foo".equals(out.getPayload())) {
            assertEquals("mqtt-foo", out.getHeaders().get(MqttHeaders.RECEIVED_TOPIC));
        } else if ("bar".equals(out.getPayload())) {
            assertEquals("mqtt-bar", out.getHeaders().get(MqttHeaders.RECEIVED_TOPIC));
        } else {
            fail("unexpected payload " + out.getPayload());
        }
    }
    adapter.stop();
    inbound.stop();
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) QueueChannel(org.springframework.integration.channel.QueueChannel) MqttClientPersistence(org.eclipse.paho.client.mqttv3.MqttClientPersistence) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) GenericMessage(org.springframework.messaging.support.GenericMessage) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) MqttPahoMessageHandler(org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler) BeanFactory(org.springframework.beans.factory.BeanFactory) MqttDefaultFilePersistence(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence) Test(org.junit.Test)

Aggregations

DefaultMqttPahoClientFactory (org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory)10 Test (org.junit.Test)6 Properties (java.util.Properties)5 SocketFactory (javax.net.SocketFactory)5 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)5 Will (org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will)5 MqttPahoMessageDrivenChannelAdapter (org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter)5 IMqttClient (org.eclipse.paho.client.mqttv3.IMqttClient)4 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)4 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 IMqttToken (org.eclipse.paho.client.mqttv3.IMqttToken)3 MqttAsyncClient (org.eclipse.paho.client.mqttv3.MqttAsyncClient)3 MqttException (org.eclipse.paho.client.mqttv3.MqttException)3 BeanFactory (org.springframework.beans.factory.BeanFactory)3 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)3 ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)3 Method (java.lang.reflect.Method)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)2