Search in sources :

Example 36 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project ignite by apache.

the class MqttStreamer method start.

/**
 * Starts streamer.
 *
 * @throws IgniteException If failed.
 */
public void start() throws IgniteException {
    if (!stopped)
        throw new IgniteException("Attempted to start an already started MQTT Streamer");
    // For simplicity, if these are null initialize to empty lists.
    topics = topics == null ? new ArrayList<String>() : topics;
    qualitiesOfService = qualitiesOfService == null ? new ArrayList<Integer>() : qualitiesOfService;
    try {
        Map<String, Object> logValues = new HashMap<>();
        // Parameter validations.
        A.notNull(getStreamer(), "streamer");
        A.notNull(getIgnite(), "ignite");
        A.ensure(!(getSingleTupleExtractor() == null && getMultipleTupleExtractor() == null), "tuple extractor missing");
        A.ensure(getSingleTupleExtractor() == null || getMultipleTupleExtractor() == null, "cannot provide both single and multiple tuple extractor");
        A.notNullOrEmpty(brokerUrl, "broker URL");
        // If the client ID is empty, generate one.
        if (clientId == null || clientId.length() == 0)
            clientId = MqttClient.generateClientId();
        // size 1 and == topic, as this would be a case of re-initialization), fail.
        if (topic != null && topic.length() > 0 && !topics.isEmpty() && topics.size() != 1 && !topics.get(0).equals(topic))
            throw new IllegalArgumentException("Cannot specify both a single topic and a list at the same time.");
        // Same as above but for QoS.
        if (qualityOfService != null && !qualitiesOfService.isEmpty() && qualitiesOfService.size() != 1 && !qualitiesOfService.get(0).equals(qualityOfService))
            throw new IllegalArgumentException("Cannot specify both a single QoS and a list at the same time.");
        // Paho API requires disconnect timeout if providing a quiesce timeout and disconnecting forcibly.
        if (disconnectForcibly && disconnectQuiesceTimeout != null)
            A.notNull(disconnectForciblyTimeout, "disconnect timeout cannot be null when disconnecting forcibly " + "with quiesce");
        // If we have multiple topics.
        if (!topics.isEmpty()) {
            for (String t : topics) A.notNullOrEmpty(t, "topic in list of topics");
            A.ensure(qualitiesOfService.isEmpty() || qualitiesOfService.size() == topics.size(), "qualities of service must be either empty or have the same size as topics list");
            logValues.put("topics", topics);
        } else {
            // Just the single topic.
            topics.add(topic);
            if (qualityOfService != null)
                qualitiesOfService.add(qualityOfService);
            logValues.put("topic", topic);
        }
        // Finish building log values.
        logValues.put("brokerUrl", brokerUrl);
        logValues.put("clientId", clientId);
        // Cache log values.
        cachedLogValues = "[" + Joiner.on(", ").withKeyValueSeparator("=").join(logValues) + "]";
        // Create logger.
        log = getIgnite().log();
        // Create the MQTT client.
        if (persistence == null)
            client = new MqttClient(brokerUrl, clientId);
        else
            client = new MqttClient(brokerUrl, clientId, persistence);
        // Set this as a callback.
        client.setCallback(this);
        // Set stopped to false, as the connection will start async.
        stopped = false;
        // Build retrier.
        Retryer<Void> retrier = RetryerBuilder.<Void>newBuilder().retryIfResult(new Predicate<Void>() {

            @Override
            public boolean apply(Void v) {
                return !client.isConnected() && !stopped;
            }
        }).retryIfException().retryIfRuntimeException().withWaitStrategy(retryWaitStrategy).withStopStrategy(retryStopStrategy).build();
        // Create the connection retrier.
        connectionRetrier = new MqttConnectionRetrier(retrier);
        if (log.isInfoEnabled())
            log.info("Starting MQTT Streamer " + cachedLogValues);
        // Connect.
        connectionRetrier.connect();
    } catch (Exception e) {
        throw new IgniteException("Failed to initialize MQTT Streamer.", e);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IgniteException(org.apache.ignite.IgniteException) Predicate(com.google.common.base.Predicate) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) IgniteException(org.apache.ignite.IgniteException)

Example 37 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project transporter by wang4ever.

the class MqttConsumer method configure.

public MqttConsumer configure() {
    try {
        if (this.client != null) {
            logger.info("The initialized MQTT client consumer. {}", this.client);
            return this;
        }
        // host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以文件保存
        this.client = new MqttClient(this.config.getHostUrl(), this.config.getClientId(MQClientId.MQ_C), new MemoryPersistence());
        // MQTT的连接设置
        this.options = new MqttConnectOptions();
        // 设置是否清空session, false:服务器会保留客户端的连接记录,true:每次连接到服务器都以新的身份连接
        this.options.setCleanSession(this.config.getConsumerConfig().getCleanSession());
        this.options.setUserName(this.config.getUsername());
        this.options.setPassword(this.config.getPassword().toCharArray());
        // 设置超时时间 单位为秒
        this.options.setConnectionTimeout(this.config.getConsumerConfig().getConnectionTimeout());
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
        this.options.setKeepAliveInterval(this.config.getConsumerConfig().getKeepAliveInterval());
        this.client.setCallback(this.callback);
    // 当一个客户端断开连接的时候,它希望客户端可以发送它指定的消息。该消息和普通消息的结构相同。通过设置该位并填入和信息相关的内容即可。
    // this.options.setWill(topic, "close".getBytes(), 0, true);
    } catch (Exception e) {
        logger.error("MQTT client consumer initialization failed.", e);
    }
    return this;
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttConsumerException(io.transport.mqttclient.exception.MqttConsumerException) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 38 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project transporter by wang4ever.

the class MqttProducer method configure.

public MqttProducer configure() {
    try {
        if (this.client != null) {
            logger.info("The initialized MQTT client producer. {}", this.client);
            return this;
        }
        // host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以文件保存
        this.client = new MqttClient(this.config.getHostUrl(), this.config.getClientId(MQClientId.MQ_P), new MemoryPersistence());
        // MQTT的连接设置
        this.options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
        this.options.setCleanSession(this.config.getProducerConfig().getCleanSession());
        this.options.setUserName(this.config.getUsername());
        this.options.setPassword(this.config.getPassword().toCharArray());
        // 设置超时时间 单位为秒
        this.options.setConnectionTimeout(this.config.getProducerConfig().getConnectionTimeout());
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
        this.options.setKeepAliveInterval(this.config.getProducerConfig().getKeepAliveInterval());
        this.client.setCallback(this.callback);
        this.client.setTimeToWait(this.config.getProducerConfig().getTimeToWait());
    // MqttTopic topic = this.client.getTopic("");
    // // setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
    // this.options.setWill(topic, "close".getBytes(), 0, true);
    } catch (Exception e) {
        logger.error("MQTT client producer initialization failed.", e);
    }
    return this;
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttProducerException(io.transport.mqttclient.exception.MqttProducerException)

Example 39 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project pentaho-kettle by pentaho.

the class MQTTClientBuilderTest method testValidBuilderParams.

@Test
public void testValidBuilderParams() throws MqttException {
    MqttClient client = builder.withQos("2").withUsername("user").withPassword("pass").withIsSecure(true).withTopics(Collections.singletonList("SomeTopic")).withSslConfig(ImmutableMap.of("ssl.trustStore", "/some/path")).withCallback(callback).withKeepAliveInterval("1000").withMaxInflight("2000").withConnectionTimeout("3000").withCleanSession("true").withStorageLevel("/Users/NoName/Temp").withServerUris("127.0.0.1:3000").withMqttVersion("3").withAutomaticReconnect("false").buildAndConnect();
    verify(client).setCallback(callback);
    verify(factory).getClient(anyString(), anyString(), any(MemoryPersistence.class));
    verify(client).connect(connectOptsCapture.capture());
    MqttConnectOptions opts = connectOptsCapture.getValue();
    assertThat(opts.getUserName(), equalTo("user"));
    assertThat(opts.getPassword(), equalTo("pass".toCharArray()));
    Properties props = opts.getSSLProperties();
    assertThat(props.size(), equalTo(1));
    assertThat(props.getProperty("com.ibm.ssl.trustStore"), equalTo("/some/path"));
    assertEquals(opts.getKeepAliveInterval(), 1000);
    assertEquals(opts.getMaxInflight(), 2000);
    assertEquals(opts.getConnectionTimeout(), 3000);
    assertEquals(opts.isCleanSession(), true);
    assertArrayEquals(opts.getServerURIs(), new String[] { "ssl://127.0.0.1:3000" });
    assertEquals(opts.getMqttVersion(), 3);
    assertEquals(opts.isAutomaticReconnect(), false);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) Properties(java.util.Properties) Test(org.junit.Test)

Example 40 with MqttClient

use of org.eclipse.paho.client.mqttv3.MqttClient in project pentaho-kettle by pentaho.

the class MQTTProducerTest method testSendRowToProducer.

@Test
public void testSendRowToProducer() throws Exception {
    doAnswer(invocation -> {
        String topic = (String) invocation.getArguments()[0];
        MqttMessage message = (MqttMessage) invocation.getArguments()[1];
        assertEquals("TestWinning", topic);
        assertEquals(0, message.getQos());
        assertEquals("#winning", new String(message.getPayload()));
        return null;
    }).when(mqttClient).publish(any(), any());
    trans.startThreads();
    trans.waitUntilFinished();
    verify(mqttClient).disconnect();
    assertEquals(4, trans.getSteps().get(1).step.getLinesOutput());
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)46 MqttException (org.eclipse.paho.client.mqttv3.MqttException)37 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)23 MemoryPersistence (org.eclipse.paho.client.mqttv3.persist.MemoryPersistence)23 MqttMessage (org.eclipse.paho.client.mqttv3.MqttMessage)18 Test (org.junit.Test)12 Properties (java.util.Properties)6 IMqttClient (org.eclipse.paho.client.mqttv3.IMqttClient)6 MqttDefaultFilePersistence (org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence)5 IOException (java.io.IOException)4 IMqttDeliveryToken (org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)4 MqttCallback (org.eclipse.paho.client.mqttv3.MqttCallback)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 JsonArray (com.google.gson.JsonArray)3 JsonElement (com.google.gson.JsonElement)3 JsonObject (com.google.gson.JsonObject)3 SSLSecurityManager (it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)3 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3