Java Code Examples for org.eclipse.paho.client.mqttv3.MqttMessage#setRetained()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttMessage#setRetained() . 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: ManagerMQTT.java    From helloiot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void publish(EventMessage message) {

    // To be executed in Executor thread
    if (mqttClient == null) {
        return;
    }

    logger.log(Level.INFO, "Publishing message to broker. {0}", message.getTopic());
    try {
        MqttMessage mm = new MqttMessage(message.getMessage());
        mm.setQos(message.getProperty("mqtt.qos").asInt());
        mm.setRetained(message.getProperty("mqtt.retained").asBoolean());
        mqttClient.publish(message.getTopic(), mm);
    } catch (MqttException ex) {
        // TODO: Review in case of paho exception too much publications              
        logger.log(Level.WARNING, "Cannot publish message to broker. " + message.getTopic(), ex);
        // throw new RuntimeException(ex); 
    }
}
 
Example 2
Source File: MqttTestClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void publish(String topic, byte[] payload, int qos, boolean retained) throws MqttException, MqttPersistenceException {
    MqttMessage message = new MqttMessage(payload);
    message.setQos(qos);
    message.setRetained(retained);
    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 3
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private int publish(String strTopic, byte[] contents) throws Exception {
		
		log.debug("PUBLISH] topic=" + strTopic + ", contents=" + new String(contents, "UTF-8"));
		
//		MqttTopic mqttTopic = mqttClient.getTopic(strTopic);

		MqttMessage message = new MqttMessage(contents);
		message.setQos(pubQoS);
		message.setRetained(false);

		mqttClient.publish(strTopic, message);
		
		return 1;
		
//		MqttDeliveryToken token = null;
//		token = mqttTopic.publish(message);
//		token.waitForCompletion();
//
//		log.debug("[MqttClientHandler.publish] publish. topic : " + strTopic);
//		
//		return token.getMessageId();
	}
 
Example 4
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + User.getEncodedUserId(loggedInUserId) + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + User.getEncodedUserId(userId), message);
        Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + User.getEncodedUserId(userId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: AsyncClient.java    From mqtt-jmeter with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void publish(String topicName, int qos, byte[] payload, boolean isRetained) throws MqttException {
    // Construct the message to send
    MqttMessage message = new MqttMessage(payload);
    message.setRetained(isRetained);
    message.setQos(qos);

    // Send the message to the server, control is returned as soon
    // as the MQTT client has accepted to deliver the message.
    // Use the delivery token to wait until the message has been
    // delivered
    IMqttDeliveryToken pubToken = client.publish(topicName, message, null, null);
    pubToken.waitForCompletion();
    log.info("Published");
}
 
Example 6
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private int publish(String strTopic, byte[] contents) throws Exception {
		
		log.debug("PUBLISH] topic=" + strTopic + ", contents=" + new String(contents, "UTF-8"));
		
//		MqttTopic mqttTopic = mqttClient.getTopic(strTopic);

		MqttMessage message = new MqttMessage(contents);
		message.setQos(pubQoS);
		message.setRetained(false);

		mqttClient.publish(strTopic, message);
		
		return 1;
		
//		MqttDeliveryToken token = null;
//		token = mqttTopic.publish(message);
//		token.waitForCompletion();
//
//		log.debug("[MqttClientHandler.publish] publish. topic : " + strTopic);
//		
//		return token.getMessageId();
	}
 
Example 7
Source File: MqttTestClient.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void publish(String topic, byte[] payload, int qos, boolean retained) throws MqttException, MqttPersistenceException {
    MqttMessage message = new MqttMessage(payload);
    message.setQos(qos);
    message.setRetained(retained);
    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 8
Source File: MqttIndegoAdapter.java    From iot-device-bosch-indego-controller with Apache License 2.0 5 votes vote down vote up
/**
 * Publishes a single topic on the MQTT broker
 * 
 * @param mqttClient the broker connection
 * @param topic the topic to publish (relative to configured topic root)
 * @param data the data to publish
 * @param retained if the data should be retained
 * @throws MqttPersistenceException
 * @throws MqttException
 */
private void publish (MqttClient mqttClient, String topic, String data, boolean retained) throws MqttPersistenceException, MqttException
{
    if ( LOG.isDebugEnabled() ) {
        LOG.debug(String.format("Publishing '%s' to topic '%s' (retained = %s)", data, topic, retained));
    }

    MqttMessage msg = new MqttMessage(data.getBytes());
    msg.setQos(configuration.getMqttQos());
    msg.setRetained(retained);
    mqttClient.publish(configuration.getMqttTopicRoot() + topic, msg);
}
 
Example 9
Source File: MqttConnection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Publish a message on a topic
 * 
 * @param topic
 *            the topic on which to publish - represented as a string, not
 *            an MqttTopic object
 * @param payload
 *            the content of the message to publish
 * @param qos
 *            the quality of service requested
 * @param retained
 *            whether the MQTT server should retain this message
 * @param invocationContext
 *            arbitrary data to be passed back to the application
 * @param activityToken
 *            arbitrary string to be passed back to the activity
 * @return token for tracking the operation
 */
public IMqttDeliveryToken publish(String topic, byte[] payload, int qos,
		boolean retained, String invocationContext, String activityToken) {
	final Bundle resultBundle = new Bundle();
	resultBundle.putString(MqttServiceConstants.CALLBACK_ACTION,
			MqttServiceConstants.SEND_ACTION);
	resultBundle.putString(MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN,
			activityToken);
	resultBundle.putString(
			MqttServiceConstants.CALLBACK_INVOCATION_CONTEXT,
			invocationContext);

	IMqttDeliveryToken sendToken = null;

	if ((myClient != null) && (myClient.isConnected())) {
		IMqttActionListener listener = new MqttConnectionListener(
				resultBundle);
		try {
			MqttMessage message = new MqttMessage(payload);
			message.setQos(qos);
			message.setRetained(retained);
			sendToken = myClient.publish(topic, payload, qos, retained,
					invocationContext, listener);
			storeSendDetails(topic, message, sendToken, invocationContext,
					activityToken);
		} catch (Exception e) {
			handleException(resultBundle, e);
		}
	} else {
		resultBundle.putString(MqttServiceConstants.CALLBACK_ERROR_MESSAGE,
				NOT_CONNECTED);
		service.traceError(MqttServiceConstants.SEND_ACTION, NOT_CONNECTED);
		service.callbackToActivity(clientHandle, Status.ERROR, resultBundle);
	}

	return sendToken;
}
 
Example 10
Source File: TestConsumeMQTT.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void internalPublish(PublishMessage publishMessage) {
    MqttMessage mqttMessage = new MqttMessage();
    mqttMessage.setPayload(publishMessage.getPayload().array());
    mqttMessage.setRetained(publishMessage.isRetainFlag());
    mqttMessage.setQos(publishMessage.getQos().ordinal());

    try {
        mqttTestClient.publish(publishMessage.getTopicName(), mqttMessage);
    } catch (MqttException e) {
        fail("Should never get an MqttException when publishing using test client");
    }
}
 
Example 11
Source File: EngineTemperatureSensor.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Void call() throws Exception {
    
    if ( !client.isConnected()) {
        log.info("[I31] Client not connected.");
        return null;
    }
        
    MqttMessage msg = readEngineTemp();
    msg.setQos(0);
    msg.setRetained(true);
    client.publish(TOPIC,msg);        
    
    return null;        
}
 
Example 12
Source File: ApplicationClient.java    From iot-java with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Publish command to the IBM Watson IoT Platform. <br>
 * This method will attempt to create a JSON obejct out of the payload
 * 
 * @param typeId    object of String which denotes deviceType
 * @param deviceId  object of String which denotes deviceId
 * @param commandId object of String which denotes command
 * @param data      Payload data
 * @param qos       Quality of Service, in int - can have values 0,1,2
 * 
 * @return Whether the send was successful.
 */
@SuppressWarnings("unchecked")
public boolean publishCommand(String typeId, String deviceId, String commandId, Object data, int qos) {
	if (data == null) {
		throw new NullPointerException("Data object for event publish can not be null");
	}

	// Find the codec for the data class
	@SuppressWarnings("rawtypes")
	MessageCodec codec = messageCodecs.get(data.getClass());

	// Check that a codec is registered
	if (codec == null) {
		LOG.warn("Unable to encode command data of class " + data.getClass().getName());
		return false;
	}

	byte[] payload = codec.encode(data, new DateTime());
	String topic = "iot-2/type/" + typeId + "/id/" + deviceId + "/cmd/" + commandId + "/fmt/"
			+ codec.getMessageFormat();
	LOG.debug("Publishing command to " + topic);

	MqttMessage msg = new MqttMessage(payload);
	msg.setQos(qos);
	msg.setRetained(false);

	try {
		mqttAsyncClient.publish(topic, msg);
	} catch (MqttException e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 13
Source File: BlockingClient.java    From mqtt-jmeter with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void publish(String topicName, int qos, byte[] payload, boolean isRetained) throws MqttException {
    // Create and configure a message
    MqttMessage message = new MqttMessage(payload);
    message.setRetained(isRetained);
    message.setQos(qos);

    // Send the message to the server, control is not returned until
    // it has been delivered to the server meeting the specified
    // quality of service.
    client.publish(topicName, message);
}
 
Example 14
Source File: Engine.java    From winthing with Apache License 2.0 5 votes vote down vote up
private MqttMessage serialize(final Message message) {
    final byte[] payload;
    if (message.getPayload().isPresent()) {
        payload = gson.toJson(message.getPayload().get()).getBytes(CHARSET);
    } else {
        payload = new byte[0];
    }
    final MqttMessage mqttMessage = new MqttMessage(payload);
    mqttMessage.setQos(message.getQualityOfService().ordinal());
    mqttMessage.setRetained(message.isRetained());
    return mqttMessage;
}
 
Example 15
Source File: TestConsumeMQTT.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void internalPublish(PublishMessage publishMessage) {
    MqttMessage mqttMessage = new MqttMessage();
    mqttMessage.setPayload(publishMessage.getPayload().array());
    mqttMessage.setRetained(publishMessage.isRetainFlag());
    mqttMessage.setQos(publishMessage.getQos().ordinal());

    try {
        mqttTestClient.publish(publishMessage.getTopicName(), mqttMessage);
    } catch (MqttException e) {
        fail("Should never get an MqttException when publishing using test client");
    }
}
 
Example 16
Source File: MqttAndroidClient.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Publishes a message to a topic on the server.
 * <p>
 * A convenience method, which will create a new {@link MqttMessage} object
 * with a byte array payload, the specified QoS and retained, then publish it.
 * </p>
 * 
 * @param topic
 *            to deliver the message to, for example "finance/stock/ibm".
 * @param payload
 *            the byte array to use as the payload
 * @param qos
 *            the Quality of Service to deliver the message at. Valid values
 *            are 0, 1 or 2.
 * @param retained
 *            whether or not this message should be retained by the server.
 * @param userContext
 *            optional object used to pass context to the callback. Use null
 *            if not required.
 * @param callback
 *            optional listener that will be notified when message delivery
 *            has completed to the requested quality of service
 * @return token used to track and wait for the publish to complete. The
 *         token will be passed to any callback that has been set.
 * @throws MqttPersistenceException
 *             when a problem occurs storing the message
 * @throws IllegalArgumentException
 *             if value of QoS is not 0, 1 or 2.
 * @throws MqttException
 *             for other errors encountered while publishing the message.
 *             For instance client not connected.
 * @see #publish(String, MqttMessage, Object, IMqttActionListener)
 */
@Override
public IMqttDeliveryToken publish(String topic, byte[] payload, int qos,
		boolean retained, Object userContext, IMqttActionListener callback)
		throws MqttException, MqttPersistenceException {

	MqttMessage message = new MqttMessage(payload);
	message.setQos(qos);
	message.setRetained(retained);
	MqttDeliveryTokenAndroid token = new MqttDeliveryTokenAndroid(
			this, userContext, callback, message);
	String activityToken = storeToken(token);
	IMqttDeliveryToken internalToken = mqttService.publish(clientHandle,
			topic, payload, qos, retained, null, activityToken);
	token.setDelegate(internalToken);
	return token;
}
 
Example 17
Source File: ManagerMQTT.java    From helloiot with GNU General Public License v3.0 4 votes vote down vote up
private void statusPublish(MiniVar value) throws MqttException {
    MqttMessage mm = new MqttMessage(new StringFormatSwitch().devalue(value));
    mm.setQos(0);
    mm.setRetained(true);
    mqttClient.publish(topicsys + "app/" + clientid, mm);
}
 
Example 18
Source File: PublishMQTT.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowfile = session.get();
    if (flowfile == null) {
        return;
    }

    if(mqttClient == null || !mqttClient.isConnected()){
        logger.info("Was disconnected from client or was never connected, attempting to connect.");
        try {
            reconnect();
        } catch (MqttException e) {
            context.yield();
            session.transfer(flowfile, REL_FAILURE);
            logger.error("MQTT client is disconnected and re-connecting failed. Transferring FlowFile to fail and yielding", e);
            return;
        }
    }

    // get the MQTT topic
    String topic = context.getProperty(PROP_TOPIC).evaluateAttributeExpressions(flowfile).getValue();

    if (topic == null || topic.isEmpty()) {
        logger.warn("Evaluation of the topic property returned null or evaluated to be empty, routing to failure");
        session.transfer(flowfile, REL_FAILURE);
        return;
    }

    // do the read
    final byte[] messageContent = new byte[(int) flowfile.getSize()];
    session.read(flowfile, new InputStreamCallback() {
        @Override
        public void process(final InputStream in) throws IOException {
            StreamUtils.fillBuffer(in, messageContent, true);
        }
    });

    int qos = context.getProperty(PROP_QOS).evaluateAttributeExpressions(flowfile).asInteger();
    final MqttMessage mqttMessage = new MqttMessage(messageContent);
    mqttMessage.setQos(qos);
    mqttMessage.setPayload(messageContent);
    mqttMessage.setRetained(context.getProperty(PROP_RETAIN).evaluateAttributeExpressions(flowfile).asBoolean());

    try {
        mqttClientConnectLock.readLock().lock();
        final StopWatch stopWatch = new StopWatch(true);
        try {
            /*
             * Underlying method waits for the message to publish (according to set QoS), so it executes synchronously:
             *     MqttClient.java:361 aClient.publish(topic, message, null, null).waitForCompletion(getTimeToWait());
             */
            mqttClient.publish(topic, mqttMessage);
        } finally {
            mqttClientConnectLock.readLock().unlock();
        }

        session.getProvenanceReporter().send(flowfile, broker, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        session.transfer(flowfile, REL_SUCCESS);
    } catch(MqttException me) {
        logger.error("Failed to publish message.", me);
        session.transfer(flowfile, REL_FAILURE);
    }
}
 
Example 19
Source File: PublishMQTT.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowfile = session.get();
    if (flowfile == null) {
        return;
    }

    if (!isConnected()){
        synchronized (this) {
            if (!isConnected()) {
                initializeClient(context);
            }
        }
    }

    // get the MQTT topic
    String topic = context.getProperty(PROP_TOPIC).evaluateAttributeExpressions(flowfile).getValue();

    if (topic == null || topic.isEmpty()) {
        logger.warn("Evaluation of the topic property returned null or evaluated to be empty, routing to failure");
        session.transfer(flowfile, REL_FAILURE);
        return;
    }

    // do the read
    final byte[] messageContent = new byte[(int) flowfile.getSize()];
    session.read(flowfile, new InputStreamCallback() {
        @Override
        public void process(final InputStream in) throws IOException {
            StreamUtils.fillBuffer(in, messageContent, true);
        }
    });

    int qos = context.getProperty(PROP_QOS).evaluateAttributeExpressions(flowfile).asInteger();
    final MqttMessage mqttMessage = new MqttMessage(messageContent);
    mqttMessage.setQos(qos);
    mqttMessage.setPayload(messageContent);
    mqttMessage.setRetained(context.getProperty(PROP_RETAIN).evaluateAttributeExpressions(flowfile).asBoolean());

    try {
        final StopWatch stopWatch = new StopWatch(true);
        /*
         * Underlying method waits for the message to publish (according to set QoS), so it executes synchronously:
         *     MqttClient.java:361 aClient.publish(topic, message, null, null).waitForCompletion(getTimeToWait());
         */
        mqttClient.publish(topic, mqttMessage);

        session.getProvenanceReporter().send(flowfile, broker, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        session.transfer(flowfile, REL_SUCCESS);
    } catch(MqttException me) {
        logger.error("Failed to publish message.", me);
        session.transfer(flowfile, REL_FAILURE);
    }
}
 
Example 20
Source File: MQTTRetainMessageManagerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() throws MqttException {
   publishCount.set(0);
   mqttPublisher = new MqttClientService("publisher", null);
   mqttPublisher.init();

   final MqttMessage clearRetainedMessage = new MqttMessage(new byte[] {});
   clearRetainedMessage.setRetained(true);
   clearRetainedMessage.setQos(1);
   mqttPublisher.publish(topic, clearRetainedMessage);

   mqttConsumerCount = new MqttClientService("consumer-count", null);
   mqttConsumerCount.init();
   mqttConsumerCount.setMessageConsumer(message -> publishCount.incrementAndGet());

   arrivedCountBeforePublish.set(0);
   mqttConsumerBeforePublish = new MqttClientService("consumer-before",
      message -> {
         final String payload = new String(message.getPayload());
         lastMessageArrivedOnConsumerBeforePublish.set(message);
         arrivedCountBeforePublish.incrementAndGet();
         log.debugf("[MQTT][before ][retained: %s][duplicate: %s][qos: %s] %s",
               message.isRetained(), message.isDuplicate(), message.getQos(), payload);
      });
   mqttConsumerBeforePublish.init();

   arrivedCountAferPublish.set(0);
   arrivedCountAferPublish2.set(0);
   mqttConsumerAfterPublish = new MqttClientService("consumer-after",
      message -> {
         final String payload = new String(message.getPayload());
         lastMessageArrivedOnConsumerAfterPublish.set(message);
         arrivedCountAferPublish.incrementAndGet();
         log.infof("[MQTT][after  ][retained: %s][duplicate: %s][qos: %s] %s",
               message.isRetained(), message.isDuplicate(), message.getQos(), payload);
      });
   mqttConsumerAfterPublish2 = new MqttClientService("consumer-after2",
      message -> {
         final String payload = new String(message.getPayload());
         lastMessageArrivedOnConsumerAfterPublish2.set(message);
         arrivedCountAferPublish2.incrementAndGet();
         log.infof("[MQTT][after2 ][retained: %s][duplicate: %s][qos: %s] %s",
               message.isRetained(), message.isDuplicate(), message.getQos(), payload);
      });
   mqttConsumerAfterPublish.init();
   mqttConsumerAfterPublish2.init();
}