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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttException. 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 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 #2
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    try {
        MessageListener listener = new MessageListener();
        IMqttToken token = this.mqttClient.subscribeWithResponse(this.topicName, listener);
        token.waitForCompletion();

        Assert.assertEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());

        MqttMessage message = new MqttMessage(this.content.getBytes(StandardCharsets.UTF_8));
        this.mqttClient.publish(this.topicName, message);

        Thread.sleep(this.actionTimeout);
        Assert.assertTrue(listener.received > 0);
    } catch (MqttException | InterruptedException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example #3
Source File: ConsumeMQTT.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void initializeClient(ProcessContext context) {
    // NOTE: This method is called when isConnected returns false which can happen when the client is null, or when it is
    // non-null but not connected, so we need to handle each case and only create a new client when it is null
    try {
        if (mqttClient == null) {
            logger.debug("Creating client");
            mqttClient = createMqttClient(broker, clientID, persistence);
            mqttClient.setCallback(this);
        }

        if (!mqttClient.isConnected()) {
            logger.debug("Connecting client");
            mqttClient.connect(connOpts);
            mqttClient.subscribe(topicPrefix + topicFilter, qos);
        }
    } catch (MqttException e) {
        logger.error("Connection to {} lost (or was never connected) and connection failed. Yielding processor", new Object[]{broker}, e);
        context.yield();
    }
}
 
Example #4
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 #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: 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 #7
Source File: PublishFactoryTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCreateIsCalledAndAnErrorOccursThenObserverOnErrorIsCalled()
        throws Throwable {
    this.expectedException.expectCause(isA(MqttException.class));
    final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
    Mockito.when(client.publish(Matchers.any(String.class),
            Matchers.any(byte[].class), Matchers.any(int.class),
            Matchers.any(boolean.class), Matchers.isNull(),
            Matchers.any(PublishFactory.PublishActionListener.class)))
            .thenThrow(new MqttException(
                    MqttException.REASON_CODE_CLIENT_CONNECTED));
    final PublishFactory factory = new PublishFactory(client);
    final Single<PublishToken> obs = factory.create("topic1",
            Mockito.mock(MqttMessage.class));
    obs.blockingGet();
}
 
Example #8
Source File: OshiApp.java    From iot-java with Eclipse Public License 1.0 6 votes vote down vote up
public void run() {
	try {
		client.connect();
		client.registerEventCallback(new MyEventCallback());
		client.registerCodec(new JsonCodec());

		// Create subscriptions for json-sigar events only because we only have a json
		// codec registered
		client.subscribeToDeviceEvents("+", "+", "+", "json-sigar");

		while (!quit) {
			Thread.sleep(1000);
		}
		System.out.println("Closing connection to the IBM Watson IoT Platform");

		// Once told to stop, cleanly disconnect from WIoTP
		client.disconnect();
	} catch (InterruptedException | KeyManagementException | NoSuchAlgorithmException | MqttException e) {
		e.printStackTrace();
	}
}
 
Example #9
Source File: MqttIndegoAdapter.java    From iot-device-bosch-indego-controller with Apache License 2.0 6 votes vote down vote up
/**
 * This marks the Indego device as offline.
 * 
 * @param mqttClient the connection to use
 * @throws MqttPersistenceException
 * @throws MqttException
 */
private void pushMqttStateOffline (MqttClient mqttClient) throws MqttPersistenceException, MqttException
{
    LOG.info("Pushing offline state to MQTT");

    publish(mqttClient, MQTT_TOPIC_ONLINE, false, true);
    publish(mqttClient, MQTT_TOPIC_STATE_CODE, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_STATE_MESSAGE, "", RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_ERROR_CODE, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_STATE_LEVEL, -2, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MOWED_PERCENTAGE, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MAP_SVG_CACHE_TS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MAP_UPDATE_AVAILABLE, false, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MOWED_TS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_TOTAL_OPERATE_MINS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_TOTAL_CHARGE_MINS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_SESSION_OPERATE_MINS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_SESSION_CHARGE_MINS, 0, RETAINMENT);
}
 
Example #10
Source File: MqttExporter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private void subscribe ( final Session session, final MqttItemToTopic itemToTopic ) throws InvalidSessionException, InvalidItemException, MqttSecurityException, MqttException
{
    this.executor.submit ( new Callable<Void> () {
        @Override
        public Void call () throws Exception
        {
            logger.trace ( "subscribe () called with {}", itemToTopic );
            if ( itemToTopic.isWritable () )
            {
                logger.trace ( "subscribe () called on topic '{}'", makeWriteTopicName ( itemToTopic ) );
                MqttExporter.this.client.subscribe ( makeWriteTopicName ( itemToTopic ) );
                MqttExporter.this.itemsToWriteTopics.put ( itemToTopic.getItemId (), makeWriteTopicName ( itemToTopic ) );
            }
            if ( itemToTopic.isReadable () )
            {
                MqttExporter.this.hive.subscribeItem ( session, itemToTopic.getItemId () );
                MqttExporter.this.itemsToReadTopics.put ( itemToTopic.getItemId (), makeReadTopicName ( itemToTopic ) );
            }
            return null;
        }
    } );
}
 
Example #11
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    try {
        MessageListener listener = new MessageListener();
        IMqttToken token = this.mqttClient.subscribeWithResponse(this.topicName, listener);
        token.waitForCompletion();

        Assert.assertEquals(token.getGrantedQos()[0], MqttQoS.AT_LEAST_ONCE.value());

        MqttMessage message = new MqttMessage(this.content.getBytes(StandardCharsets.UTF_8));
        this.mqttClient.publish(this.topicName, message);

        Thread.sleep(this.actionTimeout);
        Assert.assertTrue(listener.received > 0);
    } catch (MqttException | InterruptedException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example #12
Source File: MQService.java    From HelloMQTT with Apache License 2.0 6 votes vote down vote up
/**
 * 发送一个心跳包,保持长连接
 * @return MqttDeliveryToken specified token you can choose to wait for completion
 */
private synchronized MqttDeliveryToken sendKeepAlive()
        throws MqttConnectivityException, MqttPersistenceException, MqttException {
    if(!isConnected())
        throw new MqttConnectivityException();

    if(mKeepAliveTopic == null) {
        mKeepAliveTopic = mClient.getTopic(TOPIC);

    }
    Log.i(DEBUG_TAG,"Sending Keepalive to " + MQTT_BROKER);

    MqttMessage message = new MqttMessage(MQTT_KEEP_ALIVE_MESSAGE.getBytes());
    message.setQos(MQTT_KEEP_ALIVE_QOS);
    /**发送一个心跳包给服务器,然后回调到:messageArrived 方法中*/
   return mKeepAliveTopic.publish(message);
}
 
Example #13
Source File: MyIoTActionListener.java    From iot-starter-for-android with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Called on successful connection to the MQTT broker.
 */
private void handleConnectSuccess() {
    Log.d(TAG, ".handleConnectSuccess() entered");

    app.setConnected(true);

    if (app.getConnectionType() != Constants.ConnectionType.QUICKSTART) {
        // create ActionListener to handle message published results
        try {
            MyIoTActionListener listener = new MyIoTActionListener(context, Constants.ActionStateStatus.PUBLISH);
            IoTClient iotClient = IoTClient.getInstance(context);
            iotClient.subscribeToCommand("+", "json", 0, "subscribe", listener);
        } catch (MqttException e) {
            Log.d(TAG, ".handleConnectSuccess() received exception on subscribeToCommand()");
        }
    }

    String runningActivity = app.getCurrentRunningActivity();
    //if (runningActivity != null && runningActivity.equals(LoginPagerFragment.class.getName())) {
    Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOGIN);
    actionIntent.putExtra(Constants.INTENT_DATA, Constants.INTENT_DATA_CONNECT);
    context.sendBroadcast(actionIntent);
    //}
}
 
Example #14
Source File: MQTTInputConnector.java    From mqtt-client-connector with Eclipse Public License 1.0 5 votes vote down vote up
@Override
  public void start() throws MbException  {
      writeServiceTraceEntry(clsName, "start", "Entry");
      
      try {
	String clientId = getProperties().getProperty("clientId");
	String clientName = clientId;
	if (clientId == null) {
		clientName = getConnectorFactory().getContainerServices()
				.containerName() + getName();
	}
	if (clientName.length() > 23) {
		clientName = clientName.substring(clientName.length() - 23);
	}
	try {
		dataStore = ((MQTTConnectorFactory)getConnectorFactory()).getClientPersistence();
		client = new MqttClient(connectionUrl, clientName, dataStore);
		client.setCallback(this);
		connectClient();
              writeActivityLog("12066", 	new String[] {connectionUrl, clientId},
				activityLogTag);
	} catch (MqttException e) {
		if (failedToConnect == false) {
			failedToConnect = true;

			writeActivityLog("12067", new String[] { connectionUrl + " when starting " + client.getClientId() },
					activityLogTag);
			writeActivityLog("12071", new String[] { connectionUrl },
					activityLogTag);
		}
		getConnectorFactory().getContainerServices()
		.throwMbRecoverableException("12067",
				new String[] { connectionUrl + " when starting " + client.getClientId() });
	}
	writeActivityLog("12063", new String[] { connectionUrl },
			activityLogTag);
} finally {
	writeServiceTraceExit(clsName, "start", "Exit");
}
  }
 
Example #15
Source File: MqttLogger.java    From json-data-generator with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param event the value of event
 * @param qos the value of qos
 * @param topic the value of topic
 */
private void logEvent(String event, String topic, int qos) {
    MqttMessage message = new MqttMessage(event.getBytes());
    message.setQos(qos);
    try {
        mqttClient.publish(topic, message);
        log.debug("Message published");
    } catch (MqttException ex) {
        log.error("Failed to publish message", ex);
    }
}
 
Example #16
Source File: MqttClientTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
protected List<ConfigIssue> init() {
  List<ConfigIssue> issues = super.init();
  errorRecordHandler = new DefaultErrorRecordHandler(getContext());
  if(issues.size() == 0) {
    publisherConf.dataGeneratorFormatConfig.init(
        getContext(),
        publisherConf.dataFormat,
        Groups.MQTT.name(),
        HttpClientCommon.DATA_FORMAT_CONFIG_PREFIX,
        issues
    );
    generatorFactory = publisherConf.dataGeneratorFormatConfig.getDataGeneratorFactory();

    try {
      this.mqttClientCommon.init(getContext(), issues);
      mqttClient = mqttClientCommon.createMqttClient(this);
    } catch (MqttException|StageException e) {
      throw new RuntimeException(new StageException(Errors.MQTT_04, e, e));
    }

    this.allowedTopics = new HashSet<>();
    allowAllTopics = false;
    if (publisherConf.runtimeTopicResolution) {
      if (publisherConf.topicExpression == null || publisherConf.topicExpression.trim().isEmpty()) {
        issues.add(
            getContext().createConfigIssue(
                Groups.MQTT.name(),
                "publisherConf.topicExpression",
                Errors.MQTT_05
            )
        );
      }
      validateTopicExpression(getContext(), issues);
      validateTopicWhiteList(getContext(), issues);
    }
  }

  return issues;
}
 
Example #17
Source File: MqttTestClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void publish(String topic, MqttMessage message) throws MqttException, MqttPersistenceException {
    switch (type) {
        case Publisher:
            publishedMessage = new MQTTQueueMessage(topic, message);
            break;
        case Subscriber:
            try {
                mqttCallback.messageArrived(topic, message);
            } catch (Exception e) {
                throw new MqttException(e);
            }
            break;
    }
}
 
Example #18
Source File: IotCoreClientTest.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackoffOnRetryableError() throws MqttException {
    when(mMockBackoff.nextBackoff()).thenReturn(0L);
    mRunBackgroundThreadSpy.set(true);

    doThrow(new MqttException(MqttException.REASON_CODE_CLIENT_NOT_CONNECTED))
            .when(mMockMqttClient)
            .connect(any(MqttConnectOptions.class));

    mTestIotCoreClient.reconnectLoop();

    verify(mMockBackoff).nextBackoff();
}
 
Example #19
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Unsubscribe from application status of the IBM Watson IoT Platform. <br>
 * 
 * @param appId object of String which denotes the application uniquely in the
 *              organization
 */
public void unSubscribeFromApplicationStatus(String appId) {
	try {
		String topic = "iot-2/app/" + appId + "/mon";
		mqttAsyncClient.unsubscribe(topic).waitForCompletion(DEFAULT_ACTION_TIMEOUT);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
Example #20
Source File: ManagerMQTT.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void connect() {

    String[] listtopics = worktopics.toArray(new String[worktopics.size()]);
    int[] listqos = new int[workqos.size()];
    for (int i = 0; i < workqos.size(); i++) {
        listqos[i] = workqos.get(i);
    }

    try {
        mqttClient = new MqttClient(url, clientid, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        if (!Strings.isNullOrEmpty(username)) {
            options.setUserName(username);
            options.setPassword(password.toCharArray());
        }
        options.setConnectionTimeout(timeout);
        options.setKeepAliveInterval(keepalive);
        options.setMqttVersion(version);
        options.setCleanSession(true);
        options.setAutomaticReconnect(false);
        options.setMaxInflight(maxinflight);
        options.setSSLProperties(sslproperties);
        options.setWill(topicsys + "app/" + clientid, new StringFormatSwitch().devalue(MiniVarBoolean.FALSE), 0, true);
        mqttClient.connect(options);
        mqttClient.setCallback(this);
        if (listtopics.length > 0) {
            mqttClient.subscribe(listtopics, listqos);
        }
        statusPublish(MiniVarBoolean.TRUE);
    } catch (MqttException ex) {
        logger.log(Level.WARNING, null, ex);
        throw new RuntimeException(String.format(resources.getString("exception.mqtt"), url), ex);
    }
}
 
Example #21
Source File: DeviceClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Simply log error when connection is lost
 */
public void connectionLost(Throwable e) {
	if (e instanceof MqttException) {
		MqttException e2 = (MqttException) e;
		LOG.warn("Connection lost: Reason Code: " + e2.getReasonCode() + " Cause: "
				+ ExceptionUtils.getRootCauseMessage(e2));
	} else {
		LOG.warn("Connection lost: " + e.getMessage());
	}

}
 
Example #22
Source File: MqttUtils.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static List<CompletableFuture<Void>> publish(IMqttClient client, String address, List<MqttMessage> messages) throws MqttException {

        List<CompletableFuture<Void>> futures = Stream.generate(CompletableFuture<Void>::new)
                .limit(messages.size())
                .collect(Collectors.toList());
        Iterator<CompletableFuture<Void>> resultItr = futures.iterator();
        client.setCallback((MqttDeliveryCompleteCallback) token -> resultItr.next().complete(null));
        for (MqttMessage message : messages) {
            client.publish(address, message);
        }

        return futures;
    }
 
Example #23
Source File: MqttClientReconnectsToRestartedBrokerIntegrationTest.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws InterruptedException, MqttException {
	if (client.isConnected()) {
		client.close();
	}
	if (broker != null) {
		broker.stopServer();
	}
}
 
Example #24
Source File: MaestroMqttClient.java    From maestro-java with Apache License 2.0 5 votes vote down vote up
/**
 * Disconnects from the maestro broker
 * @throws MaestroConnectionException if failed to disconnect cleanly (should be safe to ignore in most cases)
 */
public void disconnect() throws MaestroConnectionException {
    try {
        if (mqttClient.isConnected()) {
            mqttClient.disconnect();
        }
    }
    catch (MqttException e) {
        throw new MaestroConnectionException("Unable to disconnect cleanly from Maestro: " + e.getMessage(), e);
    }
}
 
Example #25
Source File: IotCoreClientTest.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnDisconnectCallbackInvokedClientClosed() {
    MqttException mockMqttException = mock(MqttException.class);
    when(mockMqttException.getReasonCode())
            .thenReturn((int) MqttException.REASON_CODE_CONNECTION_LOST);
    when(mockMqttException.getCause()).thenReturn(new EOFException("Fake disconnect"));

    mClientConnectionStateSpy.set(true);
    mClientMqttCallback.connectionLost(mockMqttException);

    verify(mMockConnectionCallbackExecutor).execute(any(Runnable.class));
}
 
Example #26
Source File: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void disconnect() throws MqttException {
    // Disconnect the client
    // Issue the disconnect and then use the token to wait until
    // the disconnect completes.
    log.info("Disconnecting");
    IMqttToken discToken = client.disconnect(null, null);
    discToken.waitForCompletion();
    log.info("Disconnected");
}
 
Example #27
Source File: MqttEventSink.java    From TNT4J with Apache License 2.0 5 votes vote down vote up
private void writeLine(String msg) throws IOException {
	incrementBytesSent(msg.length());
	try {
		MqttMessage message = factory.newMqttMessage(msg);
		factory.publish(this, mqttClient, message);
	} catch (MqttException mqe) {
		throw new IOException(mqe);
	}
}
 
Example #28
Source File: MqttAcknowledgementTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@After
public void clean() throws MqttException {
   messageArrived = false;
   messageIds.clear();
   if (subscriber.isConnected()) {
      subscriber.disconnect();
   }
   if (sender.isConnected()) {
      sender.disconnect();
   }
   subscriber.close();
   sender.close();
}
 
Example #29
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testClose() {
    try {
        this.mqttClient.disconnect();
        this.mqttClient.close();

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example #30
Source File: Producer.java    From jmqtt with Apache License 2.0 5 votes vote down vote up
private static MqttClient getMqttClient(){
    try {
        MqttClient pubClient = new MqttClient(broker,clientId,new MemoryPersistence());
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setWill("lwt","this is a will message".getBytes(),1,false);
        connectOptions.setCleanSession(true);
        System.out.println("Connecting to broker: " + broker);
        pubClient.connect(connectOptions);
        return pubClient;
    } catch (MqttException e) {
        e.printStackTrace();
    }
    return null;
}