Search in sources :

Example 26 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage 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 27 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project spring-integration by spring-projects.

the class DefaultPahoMessageConverter method fromMessage.

@Override
public MqttMessage fromMessage(Message<?> message, Class<?> targetClass) {
    byte[] payloadBytes = messageToMqttBytes(message);
    MqttMessage mqttMessage = new MqttMessage(payloadBytes);
    Integer qos = this.qosProcessor.processMessage(message);
    mqttMessage.setQos(qos == null ? this.defaultQos : qos);
    Boolean retained = this.retainedProcessor.processMessage(message);
    mqttMessage.setRetained(retained == null ? this.defaultRetained : retained);
    return mqttMessage;
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage)

Example 28 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project product-iots by wso2.

the class AndroidSenseEnrollment method testEventPublishing.

@Test(description = "Test an Android sense device data publishing.", dependsOnMethods = { "testEnrollment" })
public void testEventPublishing() throws Exception {
    String DEVICE_TYPE = "android_sense";
    String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + DEVICE_ID + "/data";
    int qos = 2;
    String broker = "tcp://localhost:1886";
    String clientId = DEVICE_ID + ":" + DEVICE_TYPE;
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(true);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    MqttMessage message = new MqttMessage(PayloadGenerator.getJsonArray(Constants.AndroidSenseEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION).toString().getBytes());
    message.setQos(qos);
    for (int i = 0; i < 100; i++) {
        sampleClient.publish(topic, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    HttpResponse response = analyticsClient.get(Constants.AndroidSenseEnrollment.IS_TABLE_EXIST_CHECK_URL + "?table=" + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME);
    Assert.assertEquals("ORG_WSO2_IOT_ANDROID_BATTERY_STATS table does not exist. Problem with the android sense " + "analytics", HttpStatus.SC_OK, response.getResponseCode());
    // Allow some time to perform the analytics tasks.
    log.info("Mqtt Client is Disconnected");
    String url = Constants.AndroidSenseEnrollment.RETRIEVER_ENDPOINT + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME + "/";
    Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 3600000);
    url += timestamp.getTime() + "/" + new Timestamp(System.currentTimeMillis()).getTime() + "/0/100";
    response = analyticsClient.get(url);
    JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray();
// TODO: temporarily commenting out untill new changes are merged
// Assert.assertEquals(
// "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
// HttpStatus.SC_OK, response.getResponseCode());
// Assert.assertTrue(
// "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
// jsonArray.size() > 0);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) JsonArray(com.google.gson.JsonArray) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) Timestamp(java.sql.Timestamp) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test)

Example 29 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project xian by happyyangyuan.

the class IMqttPublisher method p2pPublish.

/*, IMsgPublisher*/
// 点对点发布消息,返回一个callback
default boolean p2pPublish(String xianPid, String payload) {
    LOG.debug("MQ发送消息>>> " + xianPid + " >>> " + payload);
    final long start = System.nanoTime();
    MqttMessage message = new MqttMessage(payload.getBytes());
    message.setQos(getQos());
    message.setRetained(false);
    String wrappedTargetId = wrap(xianPid);
    boolean msgPublished = false;
    LOG.debug("原来重发次数是5,现改为fast-fail模式,不再重试,直接返回失败给上层应用,优先保证服务器不会过载");
    short count = 0, MAX_RETRY = 0;
    do {
        try {
            msgPublished = true;
            count++;
            getSampleClient().publish(wrappedTargetId, message).setActionCallback(new IMqttActionListener() {

                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    if (System.nanoTime() - start > 1000000 * 1000)
                        LOG.cost("mqttPub", start, System.nanoTime());
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    LOG.error(exception);
                    LOG.cost("mqttPub", start, System.nanoTime());
                }
            });
        } catch (MqttException e) {
            LOG.error(e);
            if (MqttException.REASON_CODE_CLIENT_NOT_CONNECTED == e.getReasonCode()) {
                LOG.debug("注意:这里只针对客户端未连接这一种异常设置消息重发,其他不重发!");
                msgPublished = false;
            /*reconnect();*/
            }
        }
    } while (!msgPublished && count < MAX_RETRY);
    return true;
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) IMqttActionListener(org.eclipse.paho.client.mqttv3.IMqttActionListener) MqttException(org.eclipse.paho.client.mqttv3.MqttException) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken)

Example 30 with MqttMessage

use of org.eclipse.paho.client.mqttv3.MqttMessage in project java-docs-samples by GoogleCloudPlatform.

the class MqttExample method attachCallback.

/**
 * Attaches the callback used when configuration changes occur.
 */
public static void attachCallback(MqttClient client, String deviceId) throws MqttException {
    mCallback = new MqttCallback() {

        @Override
        public void connectionLost(Throwable cause) {
        // Do nothing...
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            String payload = new String(message.getPayload());
            System.out.println("Payload : " + payload);
        // TODO: Insert your parsing / handling of the configuration message here.
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        // Do nothing;
        }
    };
    String configTopic = String.format("/devices/%s/config", deviceId);
    client.subscribe(configTopic, 1);
    client.setCallback(mCallback);
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) IMqttDeliveryToken(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Aggregations

MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)65 MqttException (org.eclipse.paho.client.mqttv3.MqttException)28 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)19 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)16 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)16 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)15 Test (org.junit.Test)14 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)8 CountDownLatch (java.util.concurrent.CountDownLatch)4 JsonParser (com.google.gson.JsonParser)3 IOException (java.io.IOException)3 MqttAsyncClient (org.eclipse.paho.client.mqttv3.MqttAsyncClient)3 JSONObject (org.json.JSONObject)3 Test (org.testng.annotations.Test)3 JsonArray (com.google.gson.JsonArray)2 JsonObject (com.google.gson.JsonObject)2 MISTEdge (edu.snu.mist.common.graph.MISTEdge)2 ArrayList (java.util.ArrayList)2 Properties (java.util.Properties)2 CamelContext (org.apache.camel.CamelContext)2