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

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttMessage#setPayload() . 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: MqttSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
public Message sendMessage(Message message, IPipeLineSession session, String soapHeader) throws SenderException, TimeOutException {
	try {
		if(!client.isConnected()) {
			super.open();
		}

		log.debug(message);
		MqttMessage MqttMessage = new MqttMessage();
		MqttMessage.setPayload(message.asByteArray());
		MqttMessage.setQos(getQos());
		client.publish(getTopic(), MqttMessage);
	}
	catch (Exception e) {
		throw new SenderException(e);
	}
	return message;
}
 
Example 2
Source File: MqttSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
public Message sendMessage(Message message, IPipeLineSession session, String soapHeader) throws SenderException, TimeOutException {
	try {
		if(!client.isConnected()) {
			super.open();
		}

		log.debug(message);
		MqttMessage MqttMessage = new MqttMessage();
		MqttMessage.setPayload(message.asByteArray());
		MqttMessage.setQos(getQos());
		client.publish(getTopic(), MqttMessage);
	}
	catch (Exception e) {
		throw new SenderException(e);
	}
	return message;
}
 
Example 3
Source File: MqttAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (EventFilter.match(event, config)) {
        try {
            MqttMessage message = new MqttMessage();
            String jsonSt = marshaller.marshal(event);
            message.setPayload(jsonSt.getBytes(StandardCharsets.UTF_8));
            client.publish(
                    getValue(config, TOPIC_PROPERTY, TOPIC_DEFAULT),
                    message);
        } catch (Exception e) {
            LOGGER.warn("Error sending to MQTT server " + client.getServerURI(), e);
            try {
                client.disconnect();
                client.connect();
            } catch (MqttException e1) {
                e1.printStackTrace();
            }
        }
    }
}
 
Example 4
Source File: MqttSourceTaskTest.java    From kafka-connect-mqtt with MIT License 6 votes vote down vote up
@Test
public void testPoll() throws Exception {
    // empty queue
    assertEquals(mTask.mQueue.size(), 0);

    // add dummy message to queue
    MqttMessage mqttMessage = new MqttMessage();
    mqttMessage.setPayload("test_message".getBytes(StandardCharsets.UTF_8));
    mTask.messageArrived("test_topic", mqttMessage);

    // check message to be process
    assertEquals(mTask.mQueue.size(), 1);

    // generate and validate SourceRecord
    List<SourceRecord> sourceRecords = mTask.poll();

    assertEquals(sourceRecords.size(), 1);
    assertEquals(sourceRecords.get(0).key(), "test_topic");
    assertEquals(new String((byte[]) sourceRecords.get(0).value(), "UTF-8"), "test_message");

    // empty queue
    assertEquals(mTask.mQueue.size(), 0);
}
 
Example 5
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 6
Source File: MQTTProducer.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private MqttMessage getMessage( Object[] row ) throws KettleStepException {
  MqttMessage mqttMessage = new MqttMessage();
  try {
    mqttMessage.setQos( Integer.parseInt( meta.qos ) );
  } catch ( NumberFormatException e ) {
    throw new KettleStepException(
      getString( PKG, "MQTTProducer.Error.QOS", meta.qos ) );
  }
  //noinspection ConstantConditions
  mqttMessage.setPayload( getFieldData( row, meta.messageField )
    .map( this::dataAsBytes )
    .orElse( null ) ); //allow nulls to pass through
  return mqttMessage;
}
 
Example 7
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 8
Source File: MqttCollectorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void test() throws Exception {
    // install decanter
    System.out.println(executeCommand("feature:install decanter-collector-mqtt", new RolePrincipal("admin")));

    Thread.sleep(500);

    // create event handler
    List<Event> received = new ArrayList();
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            received.add(event);
        }
    };
    Hashtable serviceProperties = new Hashtable();
    serviceProperties.put(EventConstants.EVENT_TOPIC, "decanter/collect/*");
    bundleContext.registerService(EventHandler.class, eventHandler, serviceProperties);

    // send MQTT message
    MqttClient client = new MqttClient("tcp://localhost:1883", "d:decanter:collector:test");
    client.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload("This is a test".getBytes(StandardCharsets.UTF_8));
    client.publish("decanter", message);

    System.out.println("Waiting messages ...");
    while (received.size() == 0) {
        Thread.sleep(500);
    }

    Assert.assertEquals(1, received.size());

    Assert.assertEquals("decanter/collect/mqtt/decanter", received.get(0).getTopic());
    Assert.assertTrue(((String) received.get(0).getProperty("payload")).contains("This is a test"));
    Assert.assertEquals("root", received.get(0).getProperty("karafName"));
    Assert.assertEquals("mqtt", received.get(0).getProperty("type"));

}
 
Example 9
Source File: MqttCollectorTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void sendDecanterMessage() throws Exception {
    DispatcherMock dispatcherMock = new DispatcherMock();
    ComponentContext componentContext = new ComponentContextMock();
    componentContext.getProperties().put("server.uri", "tcp://localhost:11883");
    componentContext.getProperties().put("client.id", "decanter");
    componentContext.getProperties().put("topic", "decanter");
    JsonUnmarshaller unmarshaller = new JsonUnmarshaller();
    MqttCollector collector = new MqttCollector();
    collector.dispatcher = dispatcherMock;
    collector.unmarshaller = unmarshaller;
    collector.activate(componentContext);

    MqttClient mqttClient = new MqttClient("tcp://localhost:11883", "client");
    mqttClient.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload("{ \"foo\" : \"bar\" }".getBytes());
    mqttClient.publish("decanter", message);
    mqttClient.disconnect();

    Thread.sleep(200L);

    Assert.assertEquals(1, dispatcherMock.getPostEvents().size());
    Event event = dispatcherMock.getPostEvents().get(0);
    Assert.assertEquals("bar", event.getProperty("foo"));
    Assert.assertEquals("mqtt", event.getProperty("type"));
}
 
Example 10
Source File: PahoExampleActivity.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
public void publishMessage(){

        try {
            MqttMessage message = new MqttMessage();
            message.setPayload(publishMessage.getBytes());
            mqttAndroidClient.publish(publishTopic, message);
            addToHistory("Message Published");
            if(!mqttAndroidClient.isConnected()){
                addToHistory(mqttAndroidClient.getBufferedMessageCount() + " messages in buffer.");
            }
        } catch (MqttException e) {
            System.err.println("Error Publishing: " + e.getMessage());
            e.printStackTrace();
        }
    }
 
Example 11
Source File: MqttExporter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private MqttMessage valueToMessage ( final DataItemValue value )
{
    final MqttMessage message = new MqttMessage ();
    try
    {
        message.setPayload ( gson.toJson ( value ).getBytes ( "UTF-8" ) );
    }
    catch ( final UnsupportedEncodingException e )
    {
        logger.warn ( "could not convert value", e );
    }
    message.setRetained ( true );
    return message;
}
 
Example 12
Source File: Publication.java    From EMQ-Android-Toolkit with Apache License 2.0 5 votes vote down vote up
public MqttMessage getMessage() {
    MqttMessage message = new MqttMessage();
    message.setPayload(payload.getBytes());
    message.setQos(QoS);
    message.setRetained(isRetained());
    return message;
}
 
Example 13
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 14
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 15
Source File: Publisher.java    From mqtt-sample-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws MqttException {

    String messageString = "Hello World from Java!";

    if (args.length == 2 ) {
      messageString = args[1];
    }


    System.out.println("== START PUBLISHER ==");


    MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
    client.connect();
    MqttMessage message = new MqttMessage();
    message.setPayload(messageString.getBytes());
    client.publish("iot_data", message);

    System.out.println("\tMessage '"+ messageString +"' to 'iot_data'");

    client.disconnect();

    System.out.println("== END PUBLISHER ==");

  }
 
Example 16
Source File: TestConsumeMqttCommon.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testOnStoppedFinish() throws Exception {
    testRunner.setProperty(ConsumeMQTT.PROP_QOS, "2");

    testRunner.assertValid();

    MqttMessage innerMessage = new MqttMessage();
    innerMessage.setPayload(ByteBuffer.wrap("testMessage".getBytes()).array());
    innerMessage.setQos(2);
    MQTTQueueMessage testMessage = new MQTTQueueMessage("testTopic", innerMessage);

    ConsumeMQTT consumeMQTT = (ConsumeMQTT) testRunner.getProcessor();
    consumeMQTT.onScheduled(testRunner.getProcessContext());
    reconnect(consumeMQTT, testRunner.getProcessContext());

    Thread.sleep(PUBLISH_WAIT_MS);

    assertTrue(isConnected(consumeMQTT));

    consumeMQTT.processSessionFactory = testRunner.getProcessSessionFactory();

    Field f = ConsumeMQTT.class.getDeclaredField("mqttQueue");
    f.setAccessible(true);
    LinkedBlockingQueue<MQTTQueueMessage> queue = (LinkedBlockingQueue<MQTTQueueMessage>) f.get(consumeMQTT);
    queue.add(testMessage);

    consumeMQTT.onUnscheduled(testRunner.getProcessContext());
    consumeMQTT.onStopped(testRunner.getProcessContext());

    testRunner.assertTransferCount(ConsumeMQTT.REL_MESSAGE, 1);
    assertProvenanceEvents(1);

    List<MockFlowFile> flowFiles = testRunner.getFlowFilesForRelationship(ConsumeMQTT.REL_MESSAGE);
    MockFlowFile flowFile = flowFiles.get(0);

    flowFile.assertContentEquals("testMessage");
    flowFile.assertAttributeEquals(BROKER_ATTRIBUTE_KEY, broker);
    flowFile.assertAttributeEquals(TOPIC_ATTRIBUTE_KEY, "testTopic");
    flowFile.assertAttributeEquals(QOS_ATTRIBUTE_KEY, "2");
    flowFile.assertAttributeEquals(IS_DUPLICATE_ATTRIBUTE_KEY, "false");
    flowFile.assertAttributeEquals(IS_RETAINED_ATTRIBUTE_KEY, "false");
}
 
Example 17
Source File: TestConsumeMqttCommon.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testOnStoppedFinish() throws Exception {
    testRunner.setProperty(ConsumeMQTT.PROP_QOS, "2");

    testRunner.assertValid();

    MqttMessage innerMessage = new MqttMessage();
    innerMessage.setPayload(ByteBuffer.wrap("testMessage".getBytes()).array());
    innerMessage.setQos(2);
    MQTTQueueMessage testMessage = new MQTTQueueMessage("testTopic", innerMessage);

    ConsumeMQTT consumeMQTT = (ConsumeMQTT) testRunner.getProcessor();
    consumeMQTT.onScheduled(testRunner.getProcessContext());
    reconnect(consumeMQTT);

    Thread.sleep(PUBLISH_WAIT_MS);

    assertTrue(isConnected(consumeMQTT));

    consumeMQTT.processSessionFactory = testRunner.getProcessSessionFactory();

    Field f = ConsumeMQTT.class.getDeclaredField("mqttQueue");
    f.setAccessible(true);
    LinkedBlockingQueue<MQTTQueueMessage> queue = (LinkedBlockingQueue<MQTTQueueMessage>) f.get(consumeMQTT);
    queue.add(testMessage);

    consumeMQTT.onUnscheduled(testRunner.getProcessContext());
    consumeMQTT.onStopped(testRunner.getProcessContext());

    testRunner.assertTransferCount(ConsumeMQTT.REL_MESSAGE, 1);
    assertProvenanceEvents(1);

    List<MockFlowFile> flowFiles = testRunner.getFlowFilesForRelationship(ConsumeMQTT.REL_MESSAGE);
    MockFlowFile flowFile = flowFiles.get(0);

    flowFile.assertContentEquals("testMessage");
    flowFile.assertAttributeEquals(BROKER_ATTRIBUTE_KEY, broker);
    flowFile.assertAttributeEquals(TOPIC_ATTRIBUTE_KEY, "testTopic");
    flowFile.assertAttributeEquals(QOS_ATTRIBUTE_KEY, "2");
    flowFile.assertAttributeEquals(IS_DUPLICATE_ATTRIBUTE_KEY, "false");
    flowFile.assertAttributeEquals(IS_RETAINED_ATTRIBUTE_KEY, "false");
}
 
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: MqttProducer.java    From iot-ocp with Apache License 2.0 3 votes vote down vote up
public void run(String topic, String data) throws MqttPersistenceException, MqttException {
	
	MqttMessage message = new MqttMessage();
	message.setQos(QOS);
	
	message.setPayload(data.getBytes());
	client.publish(topic, message);
			
}