org.eclipse.paho.client.mqttv3.MqttMessage Java Examples
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttMessage.
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: SolaceController.java From solace-samples-cloudfoundry-java with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/message", method = RequestMethod.POST) public ResponseEntity<String> sendMessage(@RequestBody SimpleMessage message) { if( mqttClient == null ) return new ResponseEntity<>("{'description': 'Unable to perform operation, the MqttClient was not initialized'}", HttpStatus.INTERNAL_SERVER_ERROR); if (!mqttClient.isConnected()) { logger.error("mqttClient was not connected, Could not send message"); return new ResponseEntity<>("{'description': 'Unable to perform operation, the MqttClient was not connected!'}", HttpStatus.INTERNAL_SERVER_ERROR); } logger.info( "Sending message on topic: " + message.getTopic() + " with body: " + message.getBody()); try { MqttMessage mqttMessage = new MqttMessage(message.getBody().getBytes()); mqttMessage.setQos(0); mqttClient.publish(message.getTopic(), mqttMessage); numMessagesSent.incrementAndGet(); } catch (MqttException e) { logger.error("sendMessage failed.", e); return new ResponseEntity<>("{'description': '" + e.getMessage() + "'}", HttpStatus.BAD_REQUEST); } return new ResponseEntity<>("{'description': 'Message sent on topic " + message.getTopic() + "'}", HttpStatus.OK); }
Example #2
Source File: ManualReceive.java From karaf-decanter with Apache License 2.0 | 6 votes |
private void receive() throws Exception { MqttClient client = new MqttClient(SERVER, "test"); MqttCallback callback = new MqttCallback() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println(message); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } @Override public void connectionLost(Throwable cause) { cause.printStackTrace(); } }; client.connect(); client.subscribe(TOPIC_FILTER); client.setCallback(callback); System.in.read(); client.disconnect(); client.close(); }
Example #3
Source File: MainActivity.java From Sparkplug with Eclipse Public License 1.0 | 6 votes |
public void disconnect(Connection connection){ try { SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date()); deathPayload = connection.addBdSeqNum(deathPayload); byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload()); String topic = "spBv1.0/" + connection.getGroupId() + "/NDEATH/" + connection.getEdgeNodeId(); connection.getClient().publish(topic, deathBytes, 0, false, null, null); connection.getMessages().add(0, new PublishedMessage(topic, new MqttMessage(deathBytes))); HistoryFragment.notifyDataSetChanged(); connection.getClient().disconnect(); } catch( Exception ex){ Log.e(TAG, "Exception occurred during disconnect: " + ex.getMessage()); } }
Example #4
Source File: ClientCallback.java From smarthome with Eclipse Public License 2.0 | 6 votes |
@Override public void messageArrived(String topic, MqttMessage message) { byte[] payload = message.getPayload(); logger.trace("Received message on topic '{}' : {}", topic, new String(payload)); List<MqttMessageSubscriber> matches = new ArrayList<>(); synchronized (subscribers) { subscribers.values().forEach(subscriberList -> { if (topic.matches(subscriberList.regexMatchTopic)) { logger.trace("Topic match for '{}' using regex {}", topic, subscriberList.regexMatchTopic); subscriberList.forEach(consumer -> matches.add(consumer)); } else { logger.trace("No topic match for '{}' using regex {}", topic, subscriberList.regexMatchTopic); } }); } try { matches.forEach(subscriber -> subscriber.processMessage(topic, payload)); } catch (Exception e) { logger.error("MQTT message received. MqttMessageSubscriber#processMessage() implementation failure", e); } }
Example #5
Source File: MqttExporter.java From neoscada with Eclipse Public License 1.0 | 6 votes |
/** * convert received mqtt message and write it to item * * @param hive * @param session * @param itemId * @param message * @throws InvalidSessionException * @throws PermissionDeniedException * @throws InvalidItemException * @throws MqttException */ private void writeMessageToItem ( final Hive hive, final Session session, final String itemId, final MqttMessage message ) throws InvalidSessionException, PermissionDeniedException, InvalidItemException, MqttException { final DataItemValue div = messageToValue ( itemId, message ); if ( div != null ) { if ( div.getValue () != null ) { hive.startWrite ( session, itemId, div.getValue (), null, null ); } if ( div.getAttributes () != null && !div.getAttributes ().isEmpty () ) { hive.startWriteAttributes ( session, itemId, div.getAttributes (), null, null ); } } }
Example #6
Source File: MqttStreamer.java From ignite with Apache License 2.0 | 6 votes |
/** * Implements the {@link MqttCallback#messageArrived(String, MqttMessage)} to receive an MQTT message. * * {@inheritDoc} */ @Override public void messageArrived(String topic, MqttMessage message) throws Exception { if (getMultipleTupleExtractor() != null) { Map<K, V> entries = getMultipleTupleExtractor().extract(message); if (log.isTraceEnabled()) log.trace("Adding cache entries: " + entries); getStreamer().addData(entries); } else { Map.Entry<K, V> entry = getSingleTupleExtractor().extract(message); if (log.isTraceEnabled()) log.trace("Adding cache entry: " + entry); getStreamer().addData(entry); } }
Example #7
Source File: UartModeFragment.java From Bluefruit_LE_Connect_Android_V2 with MIT License | 6 votes |
@MainThread @Override public void onMqttMessageArrived(String topic, @NonNull MqttMessage mqttMessage) { if (!(mUartData instanceof UartPacketManager)) { Log.e(TAG, "Error send with invalid uartData class"); return; } if (mBlePeripheralsUart.size() == 0) { Log.e(TAG, "mBlePeripheralsUart not initialized"); return; } BlePeripheralUart blePeripheralUart = mBlePeripheralsUart.get(0); final String message = new String(mqttMessage.getPayload()); ((UartPacketManager) mUartData).send(blePeripheralUart, message, true); // Don't republish to mqtt something received from mqtt /* mMainHandler.post(new Runnable() { @Override public void run() { } })*/ }
Example #8
Source File: ManagerMQTT.java From helloiot with GNU General Public License v3.0 | 6 votes |
@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 #9
Source File: MqttTestClient.java From localization_nifi with Apache License 2.0 | 6 votes |
@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 #10
Source File: MqttCallBackImpl.java From jmeter-bzm-plugins with Apache License 2.0 | 6 votes |
@Override public void messageArrived(String topic, MqttMessage message) throws Exception { messages.add("[RECIVED at "+ System.currentTimeMillis() + "] -- "+ clientID + " -- TOPIC: " + topic + " NEW MESSAGE ARRIVED: "+ message); if(logLevel.toLowerCase().equals("info")){ //Console Log System.out.println("--"+ clientID + "-- TOPIC: " + topic + " NEW MESSAGE ARRIVED "); //File Log log.info("--"+ clientID + "-- TOPIC: " + topic + " NEW MESSAGE ARRIVED "); }else if(logLevel.toLowerCase().equals("debug")){ //Console Log System.out.println("--"+ clientID + "-- TOPIC: " + topic + " NEW MESSAGE ARRIVED: "+ message); //File Log log.info("--"+ clientID + "-- TOPIC: " + topic + " NEW MESSAGE ARRIVED: "+ message); } }
Example #11
Source File: MQTTClient.java From amazon-mq-workshop with Apache License 2.0 | 6 votes |
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 #12
Source File: MqttPublisher.java From quarks with Apache License 2.0 | 6 votes |
@Override public void accept(T t) { // right now, the caller of accept() doesn't do anything to // log or tolerate an unwind. address those issues here. String topicStr = topic.apply(t); try { MqttMessage message = new MqttMessage(payload.apply(t)); message.setQos(qos.apply(t)); message.setRetained(retain.apply(t)); logger.trace("{} sending to topic:{}", id(), topicStr); connector.notIdle(); connector.client().publish(topicStr, message); } catch (Exception e) { logger.error("{} sending to topic:{} failed.", id(), topicStr, e); } }
Example #13
Source File: MQTTOverWebSocketTest.java From WeEvent with Apache License 2.0 | 6 votes |
@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 #14
Source File: MqttAppender.java From karaf-decanter with Apache License 2.0 | 6 votes |
@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 #15
Source File: MyIoTCallbacks.java From iot-starter-for-android with Eclipse Public License 1.0 | 6 votes |
/** * Process incoming messages to the MQTT client. * * @param topic The topic the message was received on. * @param mqttMessage The message that was received * @throws Exception Exception that is thrown if the message is to be rejected. */ @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { Log.d(TAG, ".messageArrived() entered"); int receiveCount = app.getReceiveCount(); app.setReceiveCount(++receiveCount); //String runningActivity = app.getCurrentRunningActivity(); //if (runningActivity != null && runningActivity.equals(IoTPagerFragment.class.getName())) { Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT); actionIntent.putExtra(Constants.INTENT_DATA, Constants.INTENT_DATA_RECEIVED); context.sendBroadcast(actionIntent); //} String payload = new String(mqttMessage.getPayload()); Log.d(TAG, ".messageArrived - Message received on topic " + topic + ": message is " + payload); // TODO: Process message try { // send the message through the application logic MessageConductor.getInstance(context).steerMessage(payload, topic); } catch (JSONException e) { Log.e(TAG, ".messageArrived() - Exception caught while steering a message", e.getCause()); e.printStackTrace(); } }
Example #16
Source File: MqttClientHandler.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
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 #17
Source File: MqttMessageBus.java From FROST-Server with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void messageArrived(String topic, MqttMessage mqttMessage) throws IOException { String serialisedEcMessage = new String(mqttMessage.getPayload(), StringHelper.UTF8); EntityChangedMessage ecMessage = parser.parseObject(EntityChangedMessage.class, serialisedEcMessage); if (!recvQueue.offer(ecMessage)) { LOGGER.error("Failed to add message to receive-queue. Increase {}{} (currently {}) to allow a bigger buffer, or increase {}{} (currently {}) to empty the buffer quicker.", PREFIX_BUS, TAG_RECV_QUEUE_SIZE, recvQueueSize, PREFIX_BUS, TAG_RECV_WORKER_COUNT, recvPoolSize); } }
Example #18
Source File: MQTTTest.java From greycat with Apache License 2.0 | 5 votes |
@Test public void testBadNodeFromMQTT() { final int[] counter = {0}; // Verify that the test reaches its expected end try { String content = "{\"id\":\"98\",\n" + "\"time\":123,\n" + "\"values\":{\"value\":{\"value\":\"12\",\"type\":\"DOUBLE\"}}}"; MqttMessage message = new MqttMessage(content.getBytes()); plugin.getHandler().messageArrived(topic, message); newTask() .travelInTime("123") .readIndex("theIndex", "98") .thenDo(ctx -> { counter[0]++; ctx.continueTask(); }) .thenDo(ctx -> { Assert.assertNull(ctx.result().get(0)); ctx.continueTask(); }) .thenDo(ctx -> { Assert.assertEquals(1, counter[0]); }) .execute(graph1, null); } catch (Exception e) { e.printStackTrace(); } }
Example #19
Source File: MQTTWrapper.java From lwm2m_over_mqtt with Eclipse Public License 1.0 | 5 votes |
public void publish(String topic, String content) { try { MqttMessage message = new MqttMessage(content.getBytes()); message.setQos(QOS); LOG.info("publish :: {"+topic+" ["+message+" ]}"); mqttClient.publish(topic, message); } catch (MqttException me) { LOG.error("reason "+me.getReasonCode()); LOG.error("msg "+me.getMessage()); LOG.error("loc "+me.getLocalizedMessage()); LOG.error("cause "+me.getCause()); LOG.error("excep "+me); me.printStackTrace(); } }
Example #20
Source File: DumbProcessor.java From kafka-connect-mqtt with MIT License | 5 votes |
@Override public MqttMessageProcessor process(String topic, MqttMessage message) { log.debug("processing data for topic: {}; with message {}", topic, message); this.mTopic = topic; this.mMessage = message; return this; }
Example #21
Source File: TestUtils.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
static void assertMqttEquals(TestMqttMessage expected, io.smallrye.reactive.messaging.mqtt.server.MqttMessage message) { Assertions.assertEquals(expected.getId(), message.getMessageId()); Assertions.assertEquals(expected.getTopic(), message.getTopic()); Assertions.assertEquals(expected.getBody(), new String(message.getPayload())); Assertions.assertEquals(expected.isRetained(), message.isRetain()); Assertions.assertFalse(message.isDuplicate()); }
Example #22
Source File: Bridge.java From MQTTKafkaBridge with Apache License 2.0 | 5 votes |
@Override public void messageArrived(String topic, MqttMessage message) throws Exception { byte[] payload = message.getPayload(); System.out.println(new String(message.getPayload())); //Updated based on Kafka v0.8.1.1 KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, new String(message.getPayload())); kafkaProducer.send(data); }
Example #23
Source File: MainActivity.java From Sparkplug with Eclipse Public License 1.0 | 5 votes |
public void publish(Connection connection, String topic, SparkplugBPayload payload, int qos, boolean retain){ try { SparkplugBPayloadEncoder encoder = new SparkplugBPayloadEncoder(); byte[] bytes = encoder.getBytes(payload); connection.getClient().publish(topic, bytes, qos, retain); connection.getMessages().add(0, new PublishedMessage(topic, new MqttMessage(bytes))); HistoryFragment.notifyDataSetChanged(); } catch( Exception e){ Log.e(TAG, "Exception occurred during publish: " + e.getMessage()); } }
Example #24
Source File: MqttSourceTask.java From kafka-connect-mqtt with MIT License | 5 votes |
/** * This method is called when a message arrives from the server. * * @param topic name of the topic on the message was published to * @param message the actual message. * * @throws Exception if a terminal error has occurred, and the client should be * shut down. */ @Override public void messageArrived(String topic, MqttMessage message) throws Exception { log.debug("[{}] New message on '{}' arrived.", mMqttClientId, topic); this.mQueue.add( mConfig.getConfiguredInstance(MqttSourceConstant.MESSAGE_PROCESSOR, MqttMessageProcessor.class) .process(topic, message) ); }
Example #25
Source File: MqttCollectorTest.java From karaf-decanter with Apache License 2.0 | 5 votes |
@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 #26
Source File: TrainLocationClient.java From osgi.iot.contest.sdk with Apache License 2.0 | 5 votes |
@Override public void messageArrived(String topic, MqttMessage msg) throws Exception { // info("messageArrived on topic=<{}>: {}", topic, msg); byte[] payload = msg.getPayload(); String json = new String(payload); if (!json.startsWith("{")) { // json: TRAIN1=DisConnected String[] split = json.split("=", 2); info("connection: train={}, status={}", split[0], split[1]); return; } // json: {"train":"TRAIN1","location":"010E9EF905","time":"432"} @SuppressWarnings("unchecked") Map<String, Object> map = dtos.decoder(Map.class).get(new ByteArrayInputStream(payload)); info("location: {}", map); String trainId = (String) map.get("train"); String location = (String) map.get("location"); if (location != null) { String tag = location.toString(); Integer code = tag2code.get(tag); if (code == null || code == 0) { warn("unknown tag <{}>", tag); } else { String segment = code2segment.get(code); if (segment == null) { warn("no segment defined for code <{}>", code); } else { trigger(trainId, segment); } } } }
Example #27
Source File: Publication.java From EMQ-Android-Toolkit with Apache License 2.0 | 5 votes |
public MqttMessage getMessage() { MqttMessage message = new MqttMessage(); message.setPayload(payload.getBytes()); message.setQos(QoS); message.setRetained(isRetained()); return message; }
Example #28
Source File: MqttService.java From android-mqtt-service with Apache License 2.0 | 5 votes |
/** * Received Message from broker */ @Override public void messageArrived(MqttTopic topic, MqttMessage message) throws Exception { Log.i(DEBUG_TAG," Topic:\t" + topic.getName() + " Message:\t" + new String(message.getPayload()) + " QoS:\t" + message.getQos()); }
Example #29
Source File: SolaceController.java From solace-samples-cloudfoundry-java with Apache License 2.0 | 5 votes |
@Override public void messageArrived(String topic, MqttMessage message) throws Exception { logger.info("Received message : " + message); numMessagesReceived.incrementAndGet(); synchronized (simpleMqttCallback) { lastReceivedMessage = new SimpleMessage(); lastReceivedMessage.setTopic(topic); lastReceivedMessage.setBody(new String(message.getPayload())); } logger.info("Received message kept: " + lastReceivedMessage); }
Example #30
Source File: TrafficService.java From AirMapSDK-Android with Apache License 2.0 | 5 votes |
/** * Called when a message is received from the server * * @param topic The topic the message was sent to * @param message The message itself */ @Override public void messageArrived(String topic, MqttMessage message) throws Exception { String messageString = message.toString(); Timber.v("Got message %s", messageString); if (topic.contains("/alert/")) { receivedTraffic(messageString, AirMapTraffic.TrafficType.Alert); } else if (topic.contains("/sa/")) { receivedTraffic(messageString, AirMapTraffic.TrafficType.SituationalAwareness); } }