org.eclipse.paho.client.mqttv3.MqttConnectOptions Java Examples

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttConnectOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 7 votes vote down vote up
@Before
public void before() throws Exception {
    log.info("=============================={}.{}==============================",
            this.getClass().getSimpleName(),
            this.testName.getMethodName());

    String clientId = UUID.randomUUID().toString();

    this.cleanupOptions = new MqttConnectOptions();
    this.cleanupOptions.setConnectionTimeout(this.actionTimeout);
    this.cleanupOptions.setKeepAliveInterval(this.actionTimeout);
    this.cleanupOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    this.cleanupOptions.setCleanSession(true);

    this.persistOptions = new MqttConnectOptions();
    this.persistOptions.setConnectionTimeout(this.actionTimeout);
    this.persistOptions.setKeepAliveInterval(this.actionTimeout);
    this.persistOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    this.persistOptions.setCleanSession(false);

    this.mqttClient = new MqttClient(this.url, clientId, null);
    this.mqttClient.connect(this.cleanupOptions);
}
 
Example #2
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testWill() {
    try {
        String clientId = UUID.randomUUID().toString();
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setConnectionTimeout(this.actionTimeout);
        connectOptions.setKeepAliveInterval(this.actionTimeout);
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        connectOptions.setWill(this.topicName, this.content.getBytes(), 1, false);
        connectOptions.setCleanSession(true);
        mqttClient.connect(this.cleanupOptions);
        mqttClient.disconnect();

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example #3
Source File: ApplicationConfig.java    From iot-java with Eclipse Public License 1.0 6 votes vote down vote up
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException {
	MqttConnectOptions connectOptions = new MqttConnectOptions();

	connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT);

	connectOptions.setUserName(getMqttUsername());
	connectOptions.setPassword(getMqttPassword().toCharArray());

	connectOptions.setCleanSession(this.options.mqtt.cleanStart);
	connectOptions.setKeepAliveInterval(this.options.mqtt.keepAlive);
	connectOptions.setMaxInflight(DEFAULT_MAX_INFLIGHT_MESSAGES);
	connectOptions.setAutomaticReconnect(true);

	SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
	sslContext.init(null, null, null);

	connectOptions.setSocketFactory(sslContext.getSocketFactory());

	return connectOptions;
}
 
Example #4
Source File: AwsIotMqttConnection.java    From aws-iot-device-sdk-java with Apache License 2.0 6 votes vote down vote up
private MqttConnectOptions buildMqttConnectOptions(AbstractAwsIotClient client, SocketFactory socketFactory) {
    MqttConnectOptions options = new MqttConnectOptions();

    options.setSocketFactory(socketFactory);
    options.setCleanSession(client.isCleanSession());
    options.setConnectionTimeout(client.getConnectionTimeout() / 1000);
    options.setKeepAliveInterval(client.getKeepAliveInterval() / 1000);
    if(client.isClientEnableMetrics()) {
        options.setUserName(USERNAME_METRIC_STRING);
    }

    Set<String> serverUris = getServerUris();
    if (serverUris != null && !serverUris.isEmpty()) {
        String[] uriArray = new String[serverUris.size()];
        serverUris.toArray(uriArray);
        options.setServerURIs(uriArray);
    }

    if (client.getWillMessage() != null) {
        AWSIotMessage message = client.getWillMessage();

        options.setWill(message.getTopic(), message.getPayload(), message.getQos().getValue(), false);
    }

    return options;
}
 
Example #5
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnect31() {
    try {
        // client id must less then 23 bytes in 3.1
        String clientId = UUID.randomUUID().toString().split("-")[0];
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setConnectionTimeout(this.actionTimeout);
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        mqttClient.connect(connOpts);

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example #6
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenPahoConnectToBrokerViaProxyThenItWorks() throws Throwable {
    
    // Wait a second
    Thread.sleep(1000);
    
    // Create the client
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    
    // Connect, publish, disconnect
    AsyncPahoUtils.connect(asyncClient);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    AsyncPahoUtils.disconnect(asyncClient);
    
    // Check we received a message
    Assert.assertEquals(1, broker.getMessages().size());
    
}
 
Example #7
Source File: MqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
public void activate(Dictionary<String, Object> config) throws Exception {
    this.config = config;
    client = new MqttClient(
            getValue(config, SERVER_PROPERTY, SERVER_DEFAULT),
            getValue(config, CLIENT_ID_PROPERTY, CLIENT_ID_DEFAULT),
            new MemoryPersistence());
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(true);
    String username = getValue(config, "username", null);
    String password = getValue(config, "password", null);
    if (username != null) {
        options.setUserName(username);
    }
    if (password != null) {
        options.setPassword(password.toCharArray());
    }
    client.connect(options);
}
 
Example #8
Source File: MqttClientService.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() throws MqttException {
   final String serverURI = "tcp://localhost:1883";
   final MqttConnectOptions options = new MqttConnectOptions();
   options.setAutomaticReconnect(true);
   options.setCleanSession(false);
   options.setMaxInflight(1000);
   options.setServerURIs(new String[] {serverURI});
   options.setMqttVersion(MQTT_VERSION_3_1_1);

   final ThreadFactory threadFactory = new DefaultThreadFactory("mqtt-client-exec");
   executorService = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
   mqttClient = new MqttClient(serverURI, clientId, persistence, executorService);
   mqttClient.setTimeToWait(-1);
   mqttClient.connect(options);
   mqttClient.setCallback(this);
   log.debugf("[MQTT][Connected][client: %s]", clientId);
}
 
Example #9
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedBadUsernamePassword(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setUserName("wrong_username");
    options.setPassword("wrong_password".toCharArray());
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_FAILED_AUTHENTICATION);
  }
}
 
Example #10
Source File: IotCoreClient.java    From cloud-iot-core-androidthings with Apache License 2.0 6 votes vote down vote up
private MqttConnectOptions configureConnectionOptions() throws JoseException {
    MqttConnectOptions options = new MqttConnectOptions();

    // Note that the Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

    // Cloud IoT Core ignores the user name field, but Paho requires a user name in order
    // to send the password field. We set the user name because we need the password to send a
    // JWT to authorize the device.
    options.setUserName("unused");

    // generate the jwt password
    options.setPassword(mJwtGenerator.createJwt().toCharArray());

    return options;
}
 
Example #11
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedUnacceptableProtocolVersion(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    // trying the old 3.1
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_PROTOCOL_VERSION);
  }
}
 
Example #12
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void refusedClientIdZeroBytes(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(false);
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
    context.assertNotNull(rejection);
  }
}
 
Example #13
Source File: MqttAutoConfiguration.java    From mqtt-spring-boot with MIT License 6 votes vote down vote up
@Bean
public DefaultMqttPahoClientFactory clientFactory() {

    MqttConnectOptions connectOptions = new MqttConnectOptions();
    String username = mqttProperties.getUsername();
    String password = mqttProperties.getPassword();
    if(username != null) {
        connectOptions.setUserName(username);
    }
    if (password != null) {
        connectOptions.setPassword(password.toCharArray());
    }
    String[] serverURIs = mqttProperties.getServerURIs();
    if (serverURIs == null || serverURIs.length == 0) {
        throw new NullPointerException("serverURIs can not be null");
    }
    connectOptions.setCleanSession(mqttProperties.getCleanSession());
    connectOptions.setKeepAliveInterval(mqttProperties.getKeepAliveInterval());
    connectOptions.setServerURIs(serverURIs);

    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setConnectionOptions(connectOptions);

    return factory;
}
 
Example #14
Source File: MqttServerClientIdentifierTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "invalid-id-with-24-chars", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(false);

  } catch (MqttException ignore) {
    context.assertTrue(true);
  }
}
 
Example #15
Source File: MqttServerClientIdentifierTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "id-madeof-23-characters", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(true);

  } catch (MqttException ignore) {
    context.assertTrue(false);
  }
}
 
Example #16
Source File: ProtobufMqttProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
public ProtobufMqttProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

	String mqtt_url = PropertyUtil.getProperty(MQTT_URL_PROP, null);
	if (mqtt_url == null) {
		throw new RuntimeIOException("Property '" + MQTT_URL_PROP + "' must be set");
	}

	try {
		mqttClient = new MqttClient(mqtt_url, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setAutomaticReconnect(true);
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		Logger.debug("Connected to {}", mqtt_url);

		// Subscribe
		Logger.debug("Subscribing to response and notification topics...");
		mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
		mqttClient.subscribe(MqttProviderConstants.GPIO_NOTIFICATION_TOPIC);
		Logger.debug("Subscribed");
	} catch (MqttException e) {
		throw new RuntimeIOException(e);
	}
}
 
Example #17
Source File: MQService.java    From HelloMQTT with Apache License 2.0 6 votes vote down vote up
/**
 * 服务初始化回调函数
 */
@Override
public void onCreate() {
    super.onCreate();

    /**创建一个Handler*/
    mConnHandler = new Handler();
    try {
        /**新建一个本地临时存储数据的目录,该目录存储将要发送到服务器的数据,直到数据被发送到服务器*/
        mDataStore = new MqttDefaultFilePersistence(getCacheDir().getAbsolutePath());
    } catch(Exception e) {
        e.printStackTrace();
        /**新建一个内存临时存储数据的目录*/
        mDataStore = null;
        mMemStore = new MemoryPersistence();
    }
    /**连接的参数选项*/
    mOpts = new MqttConnectOptions();
    /**删除以前的Session*/
    mOpts.setCleanSession(MQTT_CLEAN_SESSION);
    // Do not set keep alive interval on mOpts we keep track of it with alarm's
    /**定时器用来实现心跳*/
    mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    /**管理网络连接*/
    mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
}
 
Example #18
Source File: AbstractMqttClient.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * 连接mqtt server,并返回一个客户端对象,如果连接失败,那么返回null
 */
public MqttAsyncClient connectBroker() {
    LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 准备建立连接,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
    try {
        sampleClient = new MqttAsyncClient("tcp://overriddenByMqttConnectOptions.setServerURIs:1883", getMqttClientId(), persistence);
        connOpts = new MqttConnectOptions();
        connOpts.setAutomaticReconnect(true);
        connOpts.setServerURIs(serverURIs);
        connOpts.setUserName(userName);
        connOpts.setPassword(getPwd());
        connOpts.setCleanSession(cleanSession);
        connOpts.setMaxInflight(1000 /**默认的值是10,对于我们来说这个值太小!*/);
        connOpts.setKeepAliveInterval(keepAliveInterval);
        sampleClient.setCallback(getCallback(this));
        sampleClient.connect(connOpts).waitForCompletion(60 * 1000);
        LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 建立连接完成,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName));
        return sampleClient;
    } catch (MqttException me) {
        throw new RuntimeException(String.format("mqtt=======客户端%s与rabbitMQ server: %s 连接失败!!! userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName), me);
    }
}
 
Example #19
Source File: MQTTClient.java    From amazon-mq-workshop with Apache License 2.0 6 votes vote down vote up
private static void sendMessages(MqttClient client, MqttConnectOptions options, String destination, String name, int interval, WrapInt count) throws Exception {
    client.connect(options);
    System.out.println(String.format("Successfully connected to %s", client.getServerURI()));

    while (true) {
        count.v++;

        String message = String.format("[topic://%s] [%s] Message number %s", destination.replace('/', '.'), name, count.v);
        client.publish(destination, message.getBytes(StandardCharsets.UTF_8), 1, false);

        if (interval > 0) {
            System.out.println(String.format("%s - Sender: sent '%s'", df.format(new Date()), message));
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                System.out.println(String.format("Error: %s", e.getMessage()));
                System.exit(1);
            }
        }
    }
}
 
Example #20
Source File: MQTTClient.java    From amazon-mq-workshop with Apache License 2.0 6 votes vote down vote up
private static void receiveMessages(final MqttClient client, final MqttConnectOptions options,final  String destination) throws Exception {
    new Thread(new Runnable() {
        public void run() {
            try {
                client.setCallback(new MqttCallback() {
                    public void connectionLost(Throwable cause) {
                    }

                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        System.out.println(String.format("%s - Receiver: received '%s'", df.format(new Date()), new String(message.getPayload())));
                    }

                    public void deliveryComplete(IMqttDeliveryToken token) {
                    }
                });
                client.connect(options);
                System.out.println(String.format("Successfully connected to %s", client.getServerURI()));

                client.subscribe(destination);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }).start();
}
 
Example #21
Source File: MqttListener.java    From diozero with MIT License 5 votes vote down vote up
public MqttListener() {
	try {
		mqttClient = new MqttClient(mqttServer, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		System.out.println("Connected to '" + mqttServer + "'");
	} catch (MqttException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #22
Source File: MoquetteConnectivityTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenBrokerIsRestartedThenWithAutoReconnectClientIsReconnected() throws Throwable {
    
    // Create client with re-connect and dirty sessions
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(true);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    ObservableMqttClient observableClient = observableClient(asyncClient, options);
    
    // Connect
    observableClient.connect().blockingAwait();
    Assert.assertTrue(observableClient.isConnected());

    // Stop the broker proxy
    this.brokerProxy.disable();
    Thread.sleep(3000);
    Assert.assertFalse(observableClient.isConnected());
 
    // Restart the broker proxy
    this.brokerProxy.enable();
    Thread.sleep(5000);
    Assert.assertTrue(observableClient.isConnected());	
}
 
Example #23
Source File: MoquetteConnectivityTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenBrokerIsStoppedThenClientIsDisconnected() throws Throwable {
    
	// Create client with re-connect and dirty sessions
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
	MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    ObservableMqttClient observableClient = observableClient(asyncClient, options);
    
    // Connect
    observableClient.connect().blockingAwait();
    Assert.assertTrue(observableClient.isConnected());

    // Stop the broker proxy
    this.brokerProxy.disable();
    Thread.sleep(3000);
    Assert.assertFalse(observableClient.isConnected());
 
    // Restart the broker proxy
    this.brokerProxy.enable();
    Thread.sleep(3000);
    Assert.assertFalse(observableClient.isConnected());
    
}
 
Example #24
Source File: MoquetteConnectivityTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenWeConnectObservableClientToTestBrokerThenItCanPublishMessages() throws Throwable {
    
    // Connect, publish, disconnect
    MqttAsyncClient asyncClient = new MqttAsyncClient(this.broker.toUrl(), "test-client-id", new MemoryPersistence());
    ObservableMqttClient observableClient = observableClient(asyncClient, new MqttConnectOptions());
    observableClient.connect().blockingAwait();
    observableClient.publish("topical", PublishMessage.create("Test message".getBytes(), 2, false)).blockingGet();
    observableClient.disconnect().blockingAwait();
    
    // Check we received a message
    Assert.assertEquals(1, broker.getMessages().size());
}
 
Example #25
Source File: MqttClientInstance.java    From maestro-java with Apache License 2.0 5 votes vote down vote up
public static MqttConnectOptions getConnectionOptions() {
    final MqttConnectOptions connOpts = new MqttConnectOptions();

    connOpts.setCleanSession(true);
    connOpts.setAutomaticReconnect(true);

    /*
     Paho uses 10 as the default max inflight exchanges. This may be a bit too small
     when sending log files, handling stats messages, ping requests ... all at the same.
     */
    connOpts.setMaxInflight(20);

    return connOpts;
}
 
Example #26
Source File: ConnectFactoryTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenCreateIsCalledAndAnErrorOccursThenObserverOnErrorIsCalled()
        throws Throwable {
    this.expectedException.expectCause(isA(MqttException.class));
    final MqttConnectOptions options = Mockito
            .mock(MqttConnectOptions.class);
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    Mockito.when(client.connect(Matchers.same(options), Matchers.isNull(),
            Matchers.any(ConnectFactory.ConnectActionListener.class)))
            .thenThrow(new MqttException(
                    MqttException.REASON_CODE_CLIENT_CONNECTED));
    final ConnectFactory factory = new ConnectFactory(client, options);
    final Completable obs = factory.create();
    obs.blockingAwait();
}
 
Example #27
Source File: MaestroMqttClient.java    From maestro-java with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to the maestro broker
 * @throws MaestroConnectionException if unable to connect to the broker
 */
public void connect() throws MaestroConnectionException {
    try {
        if (!mqttClient.isConnected()) {
            final MqttConnectOptions connOpts = MqttClientInstance.getConnectionOptions();

            mqttClient.connect(connOpts);
        }
    }
    catch (MqttException e) {
        throw new MaestroConnectionException("Unable to establish a connection to Maestro: " + e.getMessage(), e);
    }
}
 
Example #28
Source File: ToxiproxyConnectivityITCase.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void whenBrokerIsStoppedThenClientIsDisconnected() throws Throwable {
    
	// Create client with re-connect and dirty sessions
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
	MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    ObservableMqttClient observableClient = observableClient(asyncClient, options);
    
    // Connect
    observableClient.connect().blockingAwait();
    Assert.assertTrue(observableClient.isConnected());

    // Stop the broker proxy
    this.brokerProxy.disable();
    Thread.sleep(3000);
    Assert.assertFalse(observableClient.isConnected());
 
    // Restart the broker proxy
    this.brokerProxy.enable();
    Thread.sleep(3000);
    Assert.assertFalse(observableClient.isConnected());
    
}
 
Example #29
Source File: MqttLogger.java    From json-data-generator with Apache License 2.0 5 votes vote down vote up
public MqttLogger(Map<String, Object> props) throws MqttException {
    String brokerHost = (String) props.get(BROKER_SERVER_PROP_NAME);
    Integer brokerPort = (Integer) props.get(BROKER_PORT_PROP_NAME);
    String brokerAddress = brokerHost + ":" + brokerPort.toString();
    
    String clientId = (String) props.get(CLIENT_ID_PROP_NAME);
    String username = (String)props.get(USERNAME_PROP_NAME);
    String password = (String)props.get(PASSWORD_PROP_NAME);

    topic = (String) props.get(TOPIC_PROP_NAME);
    Integer _qos = (Integer) props.get(QOS_PROP_NAME);
    qos = null == _qos ? DEFAULT_QOS : _qos;
    
    mqttClient = new MqttClient(brokerAddress,
            null == clientId ? DEFAULT_CLIENT_ID : clientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setCleanSession(true);
    if (null != username) {
        connOpts.setUserName(username);
        if (null != password) {
            connOpts.setPassword(password.toCharArray());
        }
    }

    log.debug("Connecting to broker: "+brokerAddress);
    mqttClient.connect(connOpts);
    log.debug("Connected");
}
 
Example #30
Source File: SocketProxyTest.java    From rxmqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void whenAutoReconnectThenPahoReconnectsAfterProxyDisable() throws Throwable {
    
    // Create the client
    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(true);
    options.setCleanSession(false);
    options.setKeepAliveInterval(1);
    options.setConnectionTimeout(1);
    
    String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT;
    MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence());
    
    // Connect, publish
    AsyncPahoUtils.connect(asyncClient, options);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    AsyncPahoUtils.subscribe(asyncClient, "topical2", (t, m) -> {});
    Assert.assertEquals(1, broker.getMessages().size());
    
    // Disable proxy
    brokerProxy.disable();
    Thread.sleep(5000);
    
    // Check disconnected
    Assert.assertFalse(asyncClient.isConnected());
    
    // Re-enable
    brokerProxy.enable();
    Thread.sleep(10000);
    AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes());
    
    
    // Check connected
    Assert.assertTrue(asyncClient.isConnected());
    
}