Search in sources :

Example 1 with DefaultMqttPahoClientFactory

use of org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory in project sinsim by WilsonHu.

the class MqttService method mqttClientFactory.

@Bean
public MqttPahoClientFactory mqttClientFactory() {
    String addressFormat = "tcp://%s:1883";
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setServerURIs(String.format(addressFormat, brokerHost));
    // factory.setPassword("password");
    return factory;
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) Bean(org.springframework.context.annotation.Bean)

Example 2 with DefaultMqttPahoClientFactory

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

the class MqttAdapterTests method testPahoConnectOptions.

@Test
public void testPahoConnectOptions() {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);
    MqttConnectOptions options = factory.getConnectionOptions();
    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());
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) SocketFactory(javax.net.SocketFactory) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) Test(org.junit.Test)

Example 3 with DefaultMqttPahoClientFactory

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

the class MqttAdapterTests method testInboundOptionsApplied.

@Test
public void testInboundOptionsApplied() 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 IMqttClient client = mock(IMqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
    final AtomicBoolean connectCalled = new AtomicBoolean();
    final AtomicBoolean failConnection = new AtomicBoolean();
    final CountDownLatch waitToFail = new CountDownLatch(1);
    final CountDownLatch failInProcess = new CountDownLatch(1);
    final CountDownLatch goodConnection = new CountDownLatch(2);
    final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR);
    willAnswer(invocation -> {
        if (failConnection.get()) {
            failInProcess.countDown();
            waitToFail.await(10, TimeUnit.SECONDS);
            throw reconnectException;
        }
        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);
        goodConnection.countDown();
        return null;
    }).given(client).connect(any(MqttConnectOptions.class));
    final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>();
    willAnswer(invocation -> {
        callback.set(invocation.getArgument(0));
        return null;
    }).given(client).setCallback(any(MqttCallback.class));
    given(client.isConnected()).willReturn(true);
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
    QueueChannel outputChannel = new QueueChannel();
    adapter.setOutputChannel(outputChannel);
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    adapter.setTaskScheduler(taskScheduler);
    adapter.setBeanFactory(mock(BeanFactory.class));
    ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class);
    final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>();
    willAnswer(invocation -> {
        events.add(invocation.getArgument(0));
        return null;
    }).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class));
    adapter.setApplicationEventPublisher(applicationEventPublisher);
    adapter.setRecoveryInterval(500);
    adapter.afterPropertiesSet();
    adapter.start();
    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());
    MqttMessage message = new MqttMessage("qux".getBytes());
    callback.get().messageArrived("baz", message);
    Message<?> outMessage = outputChannel.receive(0);
    assertNotNull(outMessage);
    assertEquals("qux", outMessage.getPayload());
    MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    // lose connection and make first reconnect fail
    failConnection.set(true);
    RuntimeException e = new RuntimeException("foo");
    adapter.connectionLost(e);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), e);
    assertTrue(failInProcess.await(10, TimeUnit.SECONDS));
    waitToFail.countDown();
    failConnection.set(false);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), reconnectException);
    // reconnect can now succeed; however, we might have other failures on a slow server (500ms retry).
    assertTrue(goodConnection.await(10, TimeUnit.SECONDS));
    int n = 0;
    while (!(event instanceof MqttSubscribedEvent) && n++ < 20) {
        event = events.poll(10, TimeUnit.SECONDS);
    }
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    taskScheduler.destroy();
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) QueueChannel(org.springframework.integration.channel.QueueChannel) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) MqttException(org.eclipse.paho.client.mqttv3.MqttException) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) BeanFactory(org.springframework.beans.factory.BeanFactory) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) MqttIntegrationEvent(org.springframework.integration.mqtt.event.MqttIntegrationEvent) DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) SocketFactory(javax.net.SocketFactory) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttSubscribedEvent(org.springframework.integration.mqtt.event.MqttSubscribedEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttConnectionFailedEvent(org.springframework.integration.mqtt.event.MqttConnectionFailedEvent) Test(org.junit.Test)

Example 4 with DefaultMqttPahoClientFactory

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

the class MqttAdapterTests method testSubscribeFailure.

@Test
public void testSubscribeFailure() 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[] { 0x80 });
    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());
    try {
        method.get().invoke(adapter);
        fail("Expected InvocationTargetException");
    } catch (InvocationTargetException e) {
        assertThat(e.getCause(), instanceOf(MqttException.class));
        assertThat(((MqttException) e.getCause()).getReasonCode(), equalTo((int) MqttException.REASON_CODE_SUBSCRIBE_FAILED));
    }
}
Also used : 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) Method(java.lang.reflect.Method) Properties(java.util.Properties) InvocationTargetException(java.lang.reflect.InvocationTargetException) 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) MqttException(org.eclipse.paho.client.mqttv3.MqttException) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) Test(org.junit.Test)

Example 5 with DefaultMqttPahoClientFactory

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

the class Application method mqttClientFactory.

@Bean
public MqttPahoClientFactory mqttClientFactory() {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setServerURIs("tcp://localhost:1883");
    factory.setUserName("guest");
    factory.setPassword("guest");
    return factory;
}
Also used : DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) Bean(org.springframework.context.annotation.Bean)

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