本文整理匯總了Java中org.fusesource.mqtt.client.BlockingConnection.disconnect方法的典型用法代碼示例。如果您正苦於以下問題:Java BlockingConnection.disconnect方法的具體用法?Java BlockingConnection.disconnect怎麽用?Java BlockingConnection.disconnect使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.fusesource.mqtt.client.BlockingConnection的用法示例。
在下文中一共展示了BlockingConnection.disconnect方法的33個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Java代碼示例。
示例1: callBroker
點讚 3
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
private static void callBroker(String truststorePath, String truststorePass, String keystorePath, String keystorePass) throws Exception {
BlockingConnection connection = null;
try {
connection = retrieveMQTTConnection("ssl://localhost:1883", truststorePath, truststorePass, keystorePath, keystorePass);
// Subscribe to topics
Topic[] topics = {new Topic("test/+/some/#", QoS.AT_MOST_ONCE)};
connection.subscribe(topics);
// Publish Messages
String payload = "This is message 1";
connection.publish("test/1/some/la", payload.getBytes(), QoS.AT_LEAST_ONCE, false);
Message message = connection.receive(5, TimeUnit.SECONDS);
System.out.println("Message received: " + new String(message.getPayload()));
} catch (Exception e) {
throw e;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:26,
示例2: testConnectionWithNullPassword
點讚 3
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 30000, expected = EOFException.class)
public void testConnectionWithNullPassword() throws Exception {
for (String version : Arrays.asList("3.1", "3.1.1")) {
BlockingConnection connection = null;
try {
MQTT mqtt = createMQTTConnection("test-" + version, true);
mqtt.setUserName(fullUser);
mqtt.setPassword((String) null);
mqtt.setConnectAttemptsMax(1);
mqtt.setVersion(version);
connection = mqtt.blockingConnection();
connection.connect();
fail("Connect should fail");
} finally {
if (connection != null && connection.isConnected()) connection.disconnect();
}
}
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:20,
示例3: testConnectWithLargePassword
點讚 3
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testConnectWithLargePassword() throws Exception {
for (String version : Arrays.asList("3.1", "3.1.1")) {
String longString = new String(new char[65535]);
BlockingConnection connection = null;
try {
MQTT mqtt = createMQTTConnection("test-" + version, true);
mqtt.setUserName(longString);
mqtt.setPassword(longString);
mqtt.setConnectAttemptsMax(1);
mqtt.setVersion(version);
connection = mqtt.blockingConnection();
connection.connect();
BlockingConnection finalConnection = connection;
assertTrue("Should be connected", Wait.waitFor(() -> finalConnection.isConnected(), 5000, 100));
} finally {
if (connection != null && connection.isConnected()) connection.disconnect();
}
}
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:22,
示例4: testTurnOffInactivityMonitor
點讚 3
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 60 * 1000)
public void testTurnOffInactivityMonitor() throws Exception {
stopBroker();
protocolConfig = "transport.useInactivityMonitor=false";
startBroker();
MQTT mqtt = createMQTTConnection();
mqtt.setClientId("foo3");
mqtt.setKeepAlive((short) 2);
final BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
assertTrue("KeepAlive didn't work properly", Wait.waitFor(() -> connection.isConnected()));
connection.disconnect();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:17,
示例5: testServiceBinding
點讚 3
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testServiceBinding() throws Exception {
MockHandler mock = _testKit.replaceService("StoreReference");
MQTT mqtt = new MQTT();
BlockingConnection connection = mqtt.blockingConnection();
try {
connection.connect();
connection.publish(TOPIC_INPUT, MESSAGE_INPUT.getBytes(), QoS.AT_LEAST_ONCE, false);
Thread.sleep(1000);
LinkedBlockingQueue received = mock.getMessages();
Assert.assertNotNull(received);
Exchange exchange = received.iterator().next();
Assert.assertEquals(MESSAGE_OUTPUT, exchange.getMessage().getContent(String.class));
} finally {
connection.disconnect();
}
}
開發者ID:jboss-switchyard,項目名稱:switchyard,代碼行數:19,
示例6: startMqttServerMock
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
private void startMqttServerMock() {
String broker = "tcp://appliance4.uniquid.co:1883";
String topic = "test";
Topic[] topics = {new Topic(topic, QoS.AT_LEAST_ONCE)};
BlockingConnection connection = null;
try{
MQTT mqtt = new MQTT();
mqtt.setHost(broker);
connection = mqtt.blockingConnection();
connection.connect();
connection.subscribe(topics);
// blocks!!!
Message message = connection.receive();
byte[] payload = message.getPayload();
message.ack();
Assert.assertNotNull(message);
FunctionRequestMessage rpcProviderRequest = (FunctionRequestMessage) new JSONMessageSerializer().deserialize(payload);
Assert.assertNotNull(rpcProviderRequest);
FunctionResponseMessage rpcProviderResponse = new FunctionResponseMessage();
rpcProviderResponse.setProvider("test");
rpcProviderResponse.setError(0);
rpcProviderResponse.setResult("result");
rpcProviderResponse.setId(rpcProviderRequest.getId());
connection.publish(rpcProviderRequest.getUser(), new JSONMessageSerializer().serialize(rpcProviderResponse), QoS.AT_LEAST_ONCE, false);
connection.disconnect();
} catch (Throwable t) {
Assert.fail();
}
}
開發者ID:uniquid,項目名稱:uniquid-utils,代碼行數:40,
示例7: startMqttServerMockException
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
private void startMqttServerMockException() {
String broker = "tcp://appliance4.uniquid.co:1883";
String topic = "test";
Topic[] topics = {new Topic(topic, QoS.AT_LEAST_ONCE)};
BlockingConnection connection = null;
try{
MQTT mqtt = new MQTT();
mqtt.setHost(broker);
connection = mqtt.blockingConnection();
connection.connect();
connection.subscribe(topics);
// blocks!!!
Message message = connection.receive();
byte[] payload = message.getPayload();
message.ack();
Assert.assertNotNull(message);
FunctionRequestMessage functionRequestMessage = (FunctionRequestMessage) new JSONMessageSerializer().deserialize(payload);
Assert.assertNotNull(functionRequestMessage);
FunctionResponseMessage functionResponseMessage = new FunctionResponseMessage();
functionResponseMessage.setProvider("sender");
functionResponseMessage.setResult("result");
functionResponseMessage.setError(0);
connection.disconnect();
} catch (Throwable t) {
Assert.fail();
}
}
開發者ID:uniquid,項目名稱:uniquid-utils,代碼行數:37,
示例8: testDeployment
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testDeployment() throws Exception {
BlockingConnection publishConnection = null;
BlockingConnection subscribeConnection = null;
try {
Topic outputTopic = new Topic(TOPIC_OUTPUT, QoS.AT_LEAST_ONCE);
MQTT mqtt = new MQTT();
mqtt.setUserName(USER_NAME);
mqtt.setPassword(PASSWORD);
subscribeConnection = mqtt.blockingConnection();
subscribeConnection.connect();
subscribeConnection.subscribe(new Topic[]{outputTopic});
publishConnection = mqtt.blockingConnection();
publishConnection.connect();
publishConnection.publish(TOPIC_INPUT, MESSAGE_INPUT.getBytes(), QoS.AT_LEAST_ONCE, false);
Message message = subscribeConnection.receive(1000, TimeUnit.MILLISECONDS);
Assert.assertNotNull("No output message from " + TOPIC_OUTPUT, message);
Assert.assertEquals(MESSAGE_OUTPUT, new String(message.getPayload()));
Assert.assertNull("More than one message received from " + TOPIC_OUTPUT,
subscribeConnection.receive(1000, TimeUnit.MILLISECONDS));
} finally {
if (publishConnection != null) {
publishConnection.disconnect();
}
}
}
開發者ID:jboss-switchyard,項目名稱:switchyard,代碼行數:29,
示例9: crlNotRevokedTest
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void crlNotRevokedTest() throws Exception {
ActiveMQServer server1 = initServer();
BlockingConnection connection1 = null;
try {
server1.start();
while (!server1.isStarted()) {
Thread.sleep(50);
}
connection1 = retrieveMQTTConnection("ssl://localhost:1883", "truststore.jks", "changeit", "client_not_revoked.jks", "changeit");
// Subscribe to topics
Topic[] topics = {new Topic("test/+/some/#", QoS.AT_MOST_ONCE)};
connection1.subscribe(topics);
// Publish Messages
String payload1 = "This is message 1";
connection1.publish("test/1/some/la", payload1.getBytes(), QoS.AT_LEAST_ONCE, false);
Message message1 = connection1.receive(5, TimeUnit.SECONDS);
assertEquals(payload1, new String(message1.getPayload()));
} finally {
if (connection1 != null) {
connection1.disconnect();
}
if (server1.isStarted()) {
server1.stop();
}
}
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:37,
示例10: testValidZeroLengthClientId
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 30 * 1000)
public void testValidZeroLengthClientId() throws Exception {
MQTT mqtt = createMQTTConnection();
mqtt.setClientId("");
mqtt.setCleanSession(true);
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
connection.disconnect();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:11,
示例11: main
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
/**
* Only execution point for this application.
* @param args command line args.
* @throws Exception if something goes wrong.
*/
public static void main(final String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(MESSAGE_PAYLOAD)));
String payload = reader.readLine();
reader.close();
BlockingConnection publishConnection = null;
BlockingConnection subscribeConnection = null;
try {
Topic outputTopic = new Topic(TOPIC_OUTPUT, QoS.AT_LEAST_ONCE);
MQTT mqtt = new MQTT();
mqtt.setUserName(USER_NAME);
mqtt.setPassword(PASSWORD);
subscribeConnection = mqtt.blockingConnection();
subscribeConnection.connect();
subscribeConnection.subscribe(new Topic[]{outputTopic});
publishConnection = mqtt.blockingConnection();
publishConnection.connect();
publishConnection.publish(TOPIC_INPUT, payload.getBytes(), QoS.AT_LEAST_ONCE, false);
System.out.println("Published a message to " + TOPIC_INPUT + ": " + payload);
Message msg = subscribeConnection.receive(60000, TimeUnit.MILLISECONDS);
if (msg != null) {
System.out.println("Received a message from " + TOPIC_OUTPUT + ": " + new String(msg.getPayload()));
} else {
System.out.println("No message was received from " + TOPIC_OUTPUT);
}
} finally {
if (publishConnection != null && publishConnection.isConnected()) {
publishConnection.disconnect();
}
if (subscribeConnection != null && subscribeConnection.isConnected()) {
subscribeConnection.disconnect();
}
Dispatch.shutdown();
}
}
開發者ID:jboss-switchyard,項目名稱:switchyard,代碼行數:43,
示例12: testClientConnectionFailure
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 60 * 1000)
public void testClientConnectionFailure() throws Exception {
MQTT mqtt = createMQTTConnection("reconnect", false);
mqtt.setKeepAlive((short) 1);
final BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
Wait.waitFor(() -> connection.isConnected());
final String TOPIC = "TopicA";
final byte[] qos = connection.subscribe(new Topic[]{new Topic(TOPIC, QoS.EXACTLY_ONCE)});
assertEquals(QoS.EXACTLY_ONCE.ordinal(), qos[0]);
connection.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, false);
// kill transport
connection.kill();
// FIXME Wait for the previous connection to timeout. This is not required in ActiveMQ. Needs investigating.
Thread.sleep(10000);
final BlockingConnection newConnection = mqtt.blockingConnection();
newConnection.connect();
Wait.waitFor(() -> newConnection.isConnected());
assertEquals(QoS.EXACTLY_ONCE.ordinal(), qos[0]);
Message msg = newConnection.receive(1000, TimeUnit.MILLISECONDS);
assertNotNull(msg);
assertEquals(TOPIC, new String(msg.getPayload()));
msg.ack();
newConnection.disconnect();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:31,
示例13: testCleanSession
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 60 * 1000)
public void testCleanSession() throws Exception {
final String CLIENTID = "cleansession";
final MQTT mqttNotClean = createMQTTConnection(CLIENTID, false);
BlockingConnection notClean = mqttNotClean.blockingConnection();
final String TOPIC = "TopicA";
notClean.connect();
notClean.subscribe(new Topic[]{new Topic(TOPIC, QoS.EXACTLY_ONCE)});
notClean.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, false);
notClean.disconnect();
// MUST receive message from previous not clean session
notClean = mqttNotClean.blockingConnection();
notClean.connect();
Message msg = notClean.receive(10000, TimeUnit.MILLISECONDS);
assertNotNull(msg);
assertEquals(TOPIC, new String(msg.getPayload()));
msg.ack();
notClean.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, false);
notClean.disconnect();
// MUST NOT receive message from previous not clean session
final MQTT mqttClean = createMQTTConnection(CLIENTID, true);
final BlockingConnection clean = mqttClean.blockingConnection();
clean.connect();
msg = clean.receive(10000, TimeUnit.MILLISECONDS);
assertNull(msg);
clean.subscribe(new Topic[]{new Topic(TOPIC, QoS.EXACTLY_ONCE)});
clean.publish(TOPIC, TOPIC.getBytes(), QoS.EXACTLY_ONCE, false);
clean.disconnect();
// MUST NOT receive message from previous clean session
notClean = mqttNotClean.blockingConnection();
notClean.connect();
msg = notClean.receive(1000, TimeUnit.MILLISECONDS);
assertNull(msg);
notClean.disconnect();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:39,
示例14: testPingKeepsInactivityMonitorAlive
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 60 * 1000)
public void testPingKeepsInactivityMonitorAlive() throws Exception {
MQTT mqtt = createMQTTConnection();
mqtt.setClientId("foo");
mqtt.setKeepAlive((short) 2);
final BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
assertTrue("KeepAlive didn't work properly", Wait.waitFor(() -> connection.isConnected()));
connection.disconnect();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:13,
示例15: testPublishDollarTopics
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Ignore
@Test(timeout = 60 * 1000)
// TODO Make dollar topics configurable in code base.
public void testPublishDollarTopics() throws Exception {
MQTT mqtt = createMQTTConnection();
final String clientId = "publishDollar";
mqtt.setClientId(clientId);
mqtt.setKeepAlive((short) 2);
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
final String DOLLAR_TOPIC = "$TopicA";
connection.subscribe(new Topic[]{new Topic(DOLLAR_TOPIC, QoS.EXACTLY_ONCE)});
connection.publish(DOLLAR_TOPIC, DOLLAR_TOPIC.getBytes(), QoS.EXACTLY_ONCE, true);
Message message = connection.receive(10, TimeUnit.SECONDS);
assertNull("Publish enabled for $ Topics by default", message);
connection.disconnect();
stopBroker();
protocolConfig = "transport.publishDollarTopics=true";
startBroker();
mqtt = createMQTTConnection();
mqtt.setClientId(clientId);
mqtt.setKeepAlive((short) 2);
connection = mqtt.blockingConnection();
connection.connect();
connection.subscribe(new Topic[]{new Topic(DOLLAR_TOPIC, QoS.EXACTLY_ONCE)});
connection.publish(DOLLAR_TOPIC, DOLLAR_TOPIC.getBytes(), QoS.EXACTLY_ONCE, true);
message = connection.receive(10, TimeUnit.SECONDS);
assertNotNull(message);
message.ack();
assertEquals("Message body", DOLLAR_TOPIC, new String(message.getPayload()));
connection.disconnect();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:40,
示例16: doTestJmsMapping
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
public void doTestJmsMapping(String destinationName) throws Exception {
// start up jms consumer
Connection jmsConn = cf.createConnection();
Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createQueue(destinationName);
MessageConsumer consumer = session.createConsumer(dest);
jmsConn.start();
// set up mqtt producer
MQTT mqtt = createMQTTConnection();
mqtt.setClientId("foo3");
mqtt.setKeepAlive((short) 2);
final BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
int messagesToSend = 5;
// publish
for (int i = 0; i < messagesToSend; ++i) {
connection.publish("test/foo", "hello world".getBytes(), QoS.AT_LEAST_ONCE, false);
}
connection.disconnect();
for (int i = 0; i < messagesToSend; i++) {
javax.jms.Message message = consumer.receive(2 * 1000);
assertNotNull(message);
assertTrue(message instanceof BytesMessage);
BytesMessage bytesMessage = (BytesMessage) message;
int length = (int) bytesMessage.getBodyLength();
byte[] buffer = new byte[length];
bytesMessage.readBytes(buffer);
assertEquals("hello world", new String(buffer));
}
jmsConn.close();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:40,
示例17: testDeployment
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testDeployment() throws Exception {
BlockingConnection publishConnection = null;
BlockingConnection subscribeConnection = null;
try {
Topic outputTopic = new Topic(TOPIC_OUTPUT, QoS.AT_LEAST_ONCE);
MQTT mqtt = new MQTT();
mqtt.setUserName(USER_NAME);
mqtt.setPassword(PASSWORD);
subscribeConnection = mqtt.blockingConnection();
subscribeConnection.connect();
subscribeConnection.subscribe(new Topic[]{outputTopic});
publishConnection = mqtt.blockingConnection();
publishConnection.connect();
publishConnection.publish(TOPIC_INPUT, MESSAGE_INPUT.getBytes(), QoS.AT_LEAST_ONCE, false);
Message message = subscribeConnection.receive(1000, TimeUnit.MILLISECONDS);
Assert.assertNotNull("No output message from " + TOPIC_OUTPUT, message);
Assert.assertEquals(MESSAGE_OUTPUT, new String(message.getPayload()));
Assert.assertNull("More than one message received from " + TOPIC_OUTPUT,
subscribeConnection.receive(1000, TimeUnit.MILLISECONDS));
} finally {
if (publishConnection != null && publishConnection.isConnected()) {
publishConnection.disconnect();
}
if (subscribeConnection != null && subscribeConnection.isConnected()) {
subscribeConnection.disconnect();
}
}
}
開發者ID:jboss-switchyard,項目名稱:switchyard,代碼行數:32,
示例18: testPingOnMQTT
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 60 * 1000)
public void testPingOnMQTT() throws Exception {
stopBroker();
protocolConfig = "maxInactivityDuration=-1";
startBroker();
MQTT mqtt = createMQTTConnection();
mqtt.setClientId("test-mqtt");
mqtt.setKeepAlive((short) 2);
final BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
assertTrue("KeepAlive didn't work properly", Wait.waitFor(() -> connection.isConnected()));
connection.disconnect();
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:16,
示例19: testBrokerRestartAfterSubHashWithConfigurationQueues
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 60 * 1000)
public void testBrokerRestartAfterSubHashWithConfigurationQueues() throws Exception {
// Add some pre configured queues
CoreQueueConfiguration coreQueueConfiguration = new CoreQueueConfiguration();
coreQueueConfiguration.setName("DLQ");
coreQueueConfiguration.setRoutingType(RoutingType.ANYCAST);
coreQueueConfiguration.setAddress("DLA");
CoreAddressConfiguration coreAddressConfiguration = new CoreAddressConfiguration();
coreAddressConfiguration.setName("DLA");
coreAddressConfiguration.addRoutingType(RoutingType.ANYCAST);
coreAddressConfiguration.addQueueConfiguration(coreQueueConfiguration);
getServer().getConfiguration().getAddressConfigurations().add(coreAddressConfiguration);
getServer().stop();
getServer().start();
getServer().waitForActivation(10, TimeUnit.SECONDS);
for (int i = 0; i < 2; i++) {
MQTT mqtt = createMQTTConnection("myClient", false);
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
connection.subscribe(new Topic[]{new Topic("#", QoS.AT_MOST_ONCE)});
connection.disconnect();
getServer().stop();
getServer().start();
getServer().waitForActivation(10, TimeUnit.SECONDS);
}
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:34,
示例20: testSendingUpdate
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testSendingUpdate() throws Exception {
// fill the model with data
SignalKModel model = SignalKModelFactory.getMotuTestInstance();
// create MQTT connection
MQTT mqtt = new MQTT();
mqtt.setHost("localhost", 1883);
BlockingConnection connection = mqtt.blockingConnection();
logger.debug("Opened MQTT socket, connecting.. ");
connection.connect();
logger.debug("connected" + connection.toString());
connection
.publish(
"signalk.put",
FileUtils
.readFileToByteArray(new File(
"src/test/resources/samples/windAngleUpdate.json.txt")),
QoS.AT_LEAST_ONCE, false);
latch.await(2, TimeUnit.SECONDS);
log.debug("model:" + model);
assertEquals(2.0,
model.getValue(vessels_dot_self_dot + env_wind_angleApparent));
assertEquals(6.8986404,
model.getValue(vessels_dot_self_dot + env_wind_speedApparent));
// disconnect
connection.disconnect();
}
開發者ID:SignalK,項目名稱:signalk-server-java,代碼行數:33,
示例21: testMQTTConsumer
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testMQTTConsumer() throws Exception {
String conUrl = TestUtils.getResourceValue(getClass(), "/tcp-connection");
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("mqtt:bar?subscribeTopicName=" + BrokerSetup.TEST_TOPIC + "&host=" + conUrl).
transform(body().prepend("Hello ")).to("seda:end");
}
});
camelctx.start();
PollingConsumer consumer = camelctx.getEndpoint("seda:end").createPollingConsumer();
consumer.start();
try {
MQTT mqtt = new MQTT();
mqtt.setHost(conUrl);
BlockingConnection connection = mqtt.blockingConnection();
Topic topic = new Topic(BrokerSetup.TEST_TOPIC, QoS.AT_MOST_ONCE);
connection.connect();
try {
connection.publish(topic.name().toString(), "Kermit".getBytes(), QoS.AT_LEAST_ONCE, false);
} finally {
connection.disconnect();
}
String result = consumer.receive(3000).getIn().getBody(String.class);
Assert.assertEquals("Hello Kermit", result);
} finally {
camelctx.stop();
}
}
開發者ID:wildfly-extras,項目名稱:wildfly-camel,代碼行數:39,
示例22: testReadNoClientId
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 60 * 1000)
public void testReadNoClientId() throws Exception {
final String topicName = "READ_TOPIC_NO_CLIENT_ID";
Read mqttReader = MqttIO.read()
.withConnectionConfiguration(
MqttIO.ConnectionConfiguration.create("tcp://localhost:" + port, topicName))
.withMaxNumRecords(10);
PCollection output = pipeline.apply(mqttReader);
PAssert.that(output).containsInAnyOrder(
"This is test 0".getBytes(),
"This is test 1".getBytes(),
"This is test 2".getBytes(),
"This is test 3".getBytes(),
"This is test 4".getBytes(),
"This is test 5".getBytes(),
"This is test 6".getBytes(),
"This is test 7".getBytes(),
"This is test 8".getBytes(),
"This is test 9".getBytes()
);
// produce messages on the brokerService in another thread
// This thread prevents to block the pipeline waiting for new messages
MQTT client = new MQTT();
client.setHost("tcp://localhost:" + port);
final BlockingConnection publishConnection = client.blockingConnection();
publishConnection.connect();
Thread publisherThread = new Thread() {
public void run() {
try {
LOG.info("Waiting pipeline connected to the MQTT broker before sending "
+ "messages ...");
boolean pipelineConnected = false;
while (!pipelineConnected) {
Thread.sleep(1000);
for (Connection connection : brokerService.getBroker().getClients()) {
if (!connection.getConnectionId().isEmpty()) {
pipelineConnected = true;
}
}
}
for (int i = 0; i < 10; i++) {
publishConnection.publish(topicName, ("This is test " + i).getBytes(),
QoS.EXACTLY_ONCE, false);
}
} catch (Exception e) {
// nothing to do
}
}
};
publisherThread.start();
pipeline.run();
publishConnection.disconnect();
publisherThread.join();
}
開發者ID:apache,項目名稱:beam,代碼行數:57,
示例23: testRead
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 30 * 1000)
public void testRead() throws Exception {
PCollection output = pipeline.apply(
MqttIO.read()
.withConnectionConfiguration(
MqttIO.ConnectionConfiguration.create(
"tcp://localhost:" + port,
"READ_TOPIC",
"READ_PIPELINE"))
.withMaxReadTime(Duration.standardSeconds(3)));
PAssert.that(output).containsInAnyOrder(
"This is test 0".getBytes(),
"This is test 1".getBytes(),
"This is test 2".getBytes(),
"This is test 3".getBytes(),
"This is test 4".getBytes(),
"This is test 5".getBytes(),
"This is test 6".getBytes(),
"This is test 7".getBytes(),
"This is test 8".getBytes(),
"This is test 9".getBytes()
);
// produce messages on the brokerService in another thread
// This thread prevents to block the pipeline waiting for new messages
MQTT client = new MQTT();
client.setHost("tcp://localhost:" + port);
final BlockingConnection publishConnection = client.blockingConnection();
publishConnection.connect();
Thread publisherThread = new Thread() {
public void run() {
try {
LOG.info("Waiting pipeline connected to the MQTT broker before sending "
+ "messages ...");
boolean pipelineConnected = false;
while (!pipelineConnected) {
Thread.sleep(1000);
for (Connection connection : brokerService.getBroker().getClients()) {
if (connection.getConnectionId().startsWith("READ_PIPELINE")) {
pipelineConnected = true;
}
}
}
for (int i = 0; i < 10; i++) {
publishConnection.publish("READ_TOPIC", ("This is test " + i).getBytes(),
QoS.EXACTLY_ONCE, false);
}
} catch (Exception e) {
// nothing to do
}
}
};
publisherThread.start();
pipeline.run();
publisherThread.join();
publishConnection.disconnect();
}
開發者ID:apache,項目名稱:beam,代碼行數:59,
示例24: testWrite
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testWrite() throws Exception {
final int numberOfTestMessages = 200;
MQTT client = new MQTT();
client.setHost("tcp://localhost:" + port);
final BlockingConnection connection = client.blockingConnection();
connection.connect();
connection.subscribe(new Topic[]{new Topic(Buffer.utf8("WRITE_TOPIC"), QoS.EXACTLY_ONCE)});
final Set messages = new ConcurrentSkipListSet<>();
Thread subscriber = new Thread() {
public void run() {
try {
for (int i = 0; i < numberOfTestMessages; i++) {
Message message = connection.receive();
messages.add(new String(message.getPayload()));
message.ack();
}
} catch (Exception e) {
LOG.error("Can't receive message", e);
}
}
};
subscriber.start();
ArrayList data = new ArrayList<>();
for (int i = 0; i < numberOfTestMessages; i++) {
data.add(("Test " + i).getBytes());
}
pipeline.apply(Create.of(data))
.apply(MqttIO.write()
.withConnectionConfiguration(
MqttIO.ConnectionConfiguration.create(
"tcp://localhost:" + port,
"WRITE_TOPIC")));
pipeline.run();
subscriber.join();
connection.disconnect();
assertEquals(numberOfTestMessages, messages.size());
for (int i = 0; i < numberOfTestMessages; i++) {
assertTrue(messages.contains("Test " + i));
}
}
開發者ID:apache,項目名稱:beam,代碼行數:47,
示例25: testRetainedMessage
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test(timeout = 120 * 1000)
public void testRetainedMessage() throws Exception {
MQTT mqtt = createMQTTConnection();
mqtt.setKeepAlive((short) 60);
final String RETAIN = "RETAIN";
final String TOPICA = "TopicA";
final String[] clientIds = {null, "foo", "durable"};
for (String clientId : clientIds) {
LOG.info("Testing now with Client ID: {}", clientId);
mqtt.setClientId(clientId);
mqtt.setCleanSession(!"durable".equals(clientId));
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
// set retained message and check
connection.publish(TOPICA, RETAIN.getBytes(), QoS.EXACTLY_ONCE, true);
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
Message msg = connection.receive(5000, TimeUnit.MILLISECONDS);
assertNotNull("No retained message for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
// test duplicate subscription
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(15000, TimeUnit.MILLISECONDS);
assertNotNull("No retained message on duplicate subscription for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
connection.unsubscribe(new String[]{TOPICA});
// clear retained message and check that we don't receive it
connection.publish(TOPICA, "".getBytes(), QoS.AT_MOST_ONCE, true);
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(500, TimeUnit.MILLISECONDS);
assertNull("Retained message not cleared for " + clientId, msg);
connection.unsubscribe(new String[]{TOPICA});
// set retained message again and check
connection.publish(TOPICA, RETAIN.getBytes(), QoS.EXACTLY_ONCE, true);
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(5000, TimeUnit.MILLISECONDS);
assertNotNull("No reset retained message for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
// re-connect and check
connection.disconnect();
connection = mqtt.blockingConnection();
connection.connect();
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(5000, TimeUnit.MILLISECONDS);
assertNotNull("No reset retained message for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
connection.unsubscribe(new String[]{TOPICA});
connection.disconnect();
}
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:68,
示例26: testRetainedMessageOnVirtualTopics
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Ignore
@Test(timeout = 120 * 1000)
public void testRetainedMessageOnVirtualTopics() throws Exception {
MQTT mqtt = createMQTTConnection();
mqtt.setKeepAlive((short) 60);
final String RETAIN = "RETAIN";
final String TOPICA = "VirtualTopic/TopicA";
final String[] clientIds = {null, "foo", "durable"};
for (String clientId : clientIds) {
LOG.info("Testing now with Client ID: {}", clientId);
mqtt.setClientId(clientId);
mqtt.setCleanSession(!"durable".equals(clientId));
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
// set retained message and check
connection.publish(TOPICA, RETAIN.getBytes(), QoS.EXACTLY_ONCE, true);
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
Message msg = connection.receive(5000, TimeUnit.MILLISECONDS);
assertNotNull("No retained message for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
// test duplicate subscription
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(15000, TimeUnit.MILLISECONDS);
assertNotNull("No retained message on duplicate subscription for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
connection.unsubscribe(new String[]{TOPICA});
// clear retained message and check that we don't receive it
connection.publish(TOPICA, "".getBytes(), QoS.AT_MOST_ONCE, true);
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(500, TimeUnit.MILLISECONDS);
assertNull("Retained message not cleared for " + clientId, msg);
connection.unsubscribe(new String[]{TOPICA});
// set retained message again and check
connection.publish(TOPICA, RETAIN.getBytes(), QoS.EXACTLY_ONCE, true);
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(5000, TimeUnit.MILLISECONDS);
assertNotNull("No reset retained message for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
// re-connect and check
connection.disconnect();
connection = mqtt.blockingConnection();
connection.connect();
connection.subscribe(new Topic[]{new Topic(TOPICA, QoS.AT_LEAST_ONCE)});
msg = connection.receive(5000, TimeUnit.MILLISECONDS);
assertNotNull("No reset retained message for " + clientId, msg);
assertEquals(RETAIN, new String(msg.getPayload()));
msg.ack();
assertNull(connection.receive(500, TimeUnit.MILLISECONDS));
LOG.info("Test now unsubscribing from: {} for the last time", TOPICA);
connection.unsubscribe(new String[]{TOPICA});
connection.disconnect();
}
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:70,
示例27: testNoStaleSubscriptionAcrossNetwork
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testNoStaleSubscriptionAcrossNetwork() throws Exception {
// before we get started, we want an async way to be able to know when
// the durable consumer has been networked so we can assert that it indeed
// would have a durable subscriber. for example, when we subscribe on remote broker,
// a network-sub would be created on local broker and we want to listen for when that
// even happens. we do that with advisory messages and a latch:
CountDownLatch consumerNetworked = listenForConsumersOn(broker);
// create a subscription with Clean == 0 (durable sub for QoS==1 && QoS==2)
// on the remote broker. this sub should still be there after we disconnect
MQTT remoteMqtt = createMQTTTcpConnection("foo", false, remoteBrokerMQTTPort);
BlockingConnection remoteConn = remoteMqtt.blockingConnection();
remoteConn.connect();
remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)});
assertTrue("No destination detected!", consumerNetworked.await(1, TimeUnit.SECONDS));
assertQueueExistsOn(remoteBroker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar");
assertQueueExistsOn(broker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar");
remoteConn.disconnect();
// now we reconnect the same sub on the local broker, again with clean==0
MQTT localMqtt = createMQTTTcpConnection("foo", false, localBrokerMQTTPort);
BlockingConnection localConn = localMqtt.blockingConnection();
localConn.connect();
localConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)});
// now let's connect back up to remote broker and send a message
remoteConn = remoteMqtt.blockingConnection();
remoteConn.connect();
remoteConn.publish("foo/bar", "Hello, World!".getBytes(), QoS.AT_LEAST_ONCE, false);
// now we should see that message on the local broker because the subscription
// should have been properly networked... we'll give a sec of grace for the
// networking and forwarding to have happened properly
org.fusesource.mqtt.client.Message msg = localConn.receive(100, TimeUnit.SECONDS);
assertNotNull(msg);
msg.ack();
String response = new String(msg.getPayload());
assertEquals("Hello, World!", response);
assertEquals("foo/bar", msg.getTopic());
// Now... we SHOULD NOT see a message on the remote broker because we already
// consumed it on the local broker... having the same message on the remote broker
// would effectively give us duplicates in a distributed topic scenario:
remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)});
msg = remoteConn.receive(500, TimeUnit.MILLISECONDS);
assertNull("We have duplicate messages across the cluster for a distributed topic", msg);
}
開發者ID:apache,項目名稱:activemq-artemis,代碼行數:51,
示例28: testSubscribe
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testSubscribe() throws Exception {
// fill the model with data
SignalKModel model = SignalKModelFactory.getMotuTestInstance();
model.putAll(TestHelper.getBasicModel().getFullData());
// create MQTT connection
MQTT mqtt = new MQTT();
mqtt.setHost("localhost", 1883);
BlockingConnection connection = mqtt.blockingConnection();
logger.debug("Opened MQTT socket, connecting.. ");
connection.connect();
// StompFrame connect = connection.receive();
// if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) {
// throw new Exception ("Not connected");
// }
logger.debug("connected" + connection.toString());
// create a private receive queue
String uuid = UUID.randomUUID().toString();
Topic[] topics = { new Topic("signalk/" + uuid
+ "/vessels/motu/navigation", QoS.AT_LEAST_ONCE) };
connection.subscribe(topics);
// subscribe
Json subMsg = getSubscribe("vessels." + SignalKConstants.self, "navigation", 1000, 0,
FORMAT_DELTA, POLICY_FIXED);
subMsg.set(Constants.REPLY_TO.toString(), "signalk." + uuid
+ ".vessels.motu.navigation");
subMsg.set(WebsocketConstants.CONNECTION_KEY, uuid);
subMsg.set(nz.co.fortytwo.signalk.util.ConfigConstants.OUTPUT_TYPE,
nz.co.fortytwo.signalk.util.ConfigConstants.OUTPUT_MQTT);
// HashMap headers = new HashMap();
// queue>signalk.3202a939-1681-4a74-ad4b-3a90212e4f33.vessels.motu.navigation
// set private queue to receive data
// headers.put("reply-to","/queue/signalk."+uuid+".vessels.motu.navigation");
// headers.put(WebsocketConstants.CONNECTION_KEY, uuid);
connection.publish("signalk.put", subMsg.toString().getBytes(),
QoS.AT_LEAST_ONCE, false);
logger.debug("Sent subscribe msg: " + subMsg);
// listen for messages
Message message = connection.receive(5, TimeUnit.SECONDS);
String body = new String(message.getPayload());
logger.debug("Body: " + body);
message.ack();
assertNotNull(body);
Json reply = Json.read(body);
assertNotNull(reply.at(SignalKConstants.CONTEXT));
assertNotNull(reply.at(SignalKConstants.UPDATES));
// unsubscribe
subMsg = getSubscribe("vessels." + SignalKConstants.self, "navigation", 1000, 0,
FORMAT_DELTA, POLICY_FIXED);
// connection.send("/queue/signalk.put", subMsg.toString(),null,
// headers);
// connection.unsubscribe("/queue/signalk."+uuid+".vessels.motu.navigation");
// disconnect
connection.disconnect();
}
開發者ID:SignalK,項目名稱:signalk-server-java,代碼行數:63,
示例29: testSendingList
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testSendingList() throws Exception {
// fill the model with data
SignalKModel model = SignalKModelFactory.getMotuTestInstance();
model.putAll(TestHelper.getBasicModel().getFullData());
// create MQTT connection
MQTT mqtt = new MQTT();
mqtt.setHost("localhost", 1883);
BlockingConnection connection = mqtt.blockingConnection();
logger.debug("Opened MQTT socket, connecting.. ");
connection.connect();
// StompFrame connect = connection.receive();
// if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) {
// throw new Exception ("Not connected");
// }
logger.debug("connected" + connection.toString());
// create a private receive queue
String uuid = UUID.randomUUID().toString();
Topic[] topics = { new Topic("signalk/" + uuid
+ "/vessels/motu/navigation", QoS.AT_LEAST_ONCE) };
connection.subscribe(topics);
latch.await(2, TimeUnit.SECONDS);
// send get
Json subMsg = getList("vessels." + SignalKConstants.self, "navigation.position.*");
subMsg.set(Constants.REPLY_TO.toString(), "signalk." + uuid
+ ".vessels.motu.navigation");
subMsg.set(WebsocketConstants.CONNECTION_KEY, uuid);
// HashMap headers = new HashMap();
// queue>signalk.3202a939-1681-4a74-ad4b-3a90212e4f33.vessels.motu.navigation
// set private queue to receive data
// headers.put("reply-to","/queue/signalk."+uuid+".vessels.motu.navigation");
// headers.put(WebsocketConstants.CONNECTION_KEY, uuid);
connection.publish("signalk.put", subMsg.toString().getBytes(),
QoS.AT_LEAST_ONCE, false);
logger.debug("Sent get msg: " + subMsg);
// listen for messages
Message message = connection.receive(5, TimeUnit.SECONDS);
String body = new String(message.getPayload());
logger.debug("Body: " + body);
message.ack();
assertNotNull(body);
Json reply = Json.read(body);
assertNotNull(reply.at(SignalKConstants.CONTEXT));
assertNotNull(reply.at(SignalKConstants.PATHLIST));
// unsubscribe
// disconnect
connection.disconnect();
}
開發者ID:SignalK,項目名稱:signalk-server-java,代碼行數:59,
示例30: testSendingGetFull
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testSendingGetFull() throws Exception {
// fill the model with data
SignalKModel model = SignalKModelFactory.getMotuTestInstance();
model.putAll(TestHelper.getBasicModel().getFullData());
// create MQTT connection
MQTT mqtt = new MQTT();
mqtt.setHost("localhost", 1883);
BlockingConnection connection = mqtt.blockingConnection();
logger.debug("Opened MQTT socket, connecting.. ");
connection.connect();
// StompFrame connect = connection.receive();
// if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) {
// throw new Exception ("Not connected");
// }
logger.debug("connected" + connection.toString());
// create a private receive queue
String uuid = UUID.randomUUID().toString();
Topic[] topics = { new Topic("signalk/" + uuid
+ "/vessels/motu/navigation", QoS.AT_LEAST_ONCE) };
connection.subscribe(topics);
latch.await(2, TimeUnit.SECONDS);
// send get
Json subMsg = getGet("vessels." + SignalKConstants.self, env_wind + ".*",
SignalKConstants.FORMAT_FULL);
subMsg.set(Constants.REPLY_TO.toString(), "signalk." + uuid
+ ".vessels.motu.navigation");
subMsg.set(WebsocketConstants.CONNECTION_KEY, uuid);
// HashMap headers = new HashMap();
// queue>signalk.3202a939-1681-4a74-ad4b-3a90212e4f33.vessels.motu.navigation
// set private queue to receive data
// headers.put("reply-to","/queue/signalk."+uuid+".vessels.motu.navigation");
// headers.put(WebsocketConstants.CONNECTION_KEY, uuid);
connection.publish("signalk.put", subMsg.toString().getBytes(),
QoS.AT_LEAST_ONCE, false);
logger.debug("Sent get msg: " + subMsg);
// listen for messages
Message message = connection.receive(5, TimeUnit.SECONDS);
String body = new String(message.getPayload());
logger.debug("Body: " + body);
message.ack();
assertNotNull(body);
Json reply = Json.read(body);
assertNotNull(reply.at(SignalKConstants.vessels));
assertNotNull(reply.at(SignalKConstants.vessels).at(SignalKConstants.self).at(env)
.at("wind"));
// unsubscribe
// connection.unsubscribe("/queue/signalk."+uuid+"."+vessels_dot_self_dot+env_wind);
// disconnect
connection.disconnect();
}
開發者ID:SignalK,項目名稱:signalk-server-java,代碼行數:60,
示例31: testMQTTProducer
點讚 2
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
@Test
public void testMQTTProducer() throws Exception {
String conUrl = TestUtils.getResourceValue(getClass(), "/tcp-connection");
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").
transform(body().prepend("Hello ")).
to("mqtt:foo?publishTopicName=" + BrokerSetup.TEST_TOPIC + "&host=" + conUrl);
}
});
camelctx.start();
try {
MQTT mqtt = new MQTT();
mqtt.setHost(conUrl);
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
try {
Topic topic = new Topic(BrokerSetup.TEST_TOPIC, QoS.AT_MOST_ONCE);
connection.subscribe(new Topic[] { topic });
ProducerTemplate producer = camelctx.createProducerTemplate();
producer.asyncSendBody("direct:start", "Kermit");
Message message = connection.receive(10, TimeUnit.SECONDS);
message.ack();
String result = new String(message.getPayload());
Assert.assertEquals("Hello Kermit", result);
} finally {
connection.disconnect();
}
} finally {
camelctx.stop();
}
}
開發者ID:wildfly-extras,項目名稱:wildfly-camel,代碼行數:42,
示例32: updateOnMQTT
點讚 1
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
private void updateOnMQTT() {
// Create empty json object
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put(level);
// populate sender
jsonObject.put("series", jsonArray);
jsonObject.put("message", opened ? "OPENED" : "CLOSED");
BlockingConnection connection = null;
try {
final MQTT mqtt = new MQTT();
mqtt.setHost(mqttbroker);
connection = mqtt.blockingConnection();
connection.connect();
final String destinationTopic = "/outbox/" + tankname + "/status";
final String sender = tankname;
// to subscribe
final Topic[] topics = { new Topic(sender, QoS.AT_LEAST_ONCE) };
/*byte[] qoses = */connection.subscribe(topics);
// consume
connection.publish(destinationTopic, jsonObject.toString().getBytes(), QoS.AT_LEAST_ONCE, false);
} catch (Throwable t) {
LOGGER.error(MARKER, "Exception", t);
} finally {
// disconnect
try {
if (connection != null)
connection.disconnect();
} catch (Exception ex) {
LOGGER.error(MARKER, "Catched Exception", ex);
}
}
}
開發者ID:uniquid,項目名稱:tank-java,代碼行數:55,
示例33: createChart
點讚 1
import org.fusesource.mqtt.client.BlockingConnection; //導入方法依賴的package包/類
private void createChart() {
BlockingConnection connection = null;
try {
final MQTT mqtt = new MQTT();
mqtt.setHost(mqttbroker);
connection = mqtt.blockingConnection();
connection.connect();
final String destinationTopic = "/outbox/" + tankname + "/deviceInfo";
final String sender = tankname;
// to subscribe
final Topic[] topics = { new Topic(sender, QoS.AT_LEAST_ONCE) };
/*byte[] qoses = */connection.subscribe(topics);
String message = "{\"deviceInfo\":{\"name\":\"Tank\",\"endPoints\":{\"status\":{\"values\":{\"labels\": [\" \"],\"series\": [0],\"message\":\"CLOSED\"},\"total\": 100,\"centerSum\": 1,\"card-type\": \"crouton-chart-donut\"}},\"description\": \"Uniquid Java Tank Simulator\",\"status\": \"good\"}}";
// consume
connection.publish(destinationTopic, message.getBytes(), QoS.AT_LEAST_ONCE, false);
} catch (Throwable t) {
LOGGER.error(MARKER, "Exception", t);
} finally {
// disconnect
try {
if (connection != null)
connection.disconnect();
} catch (Exception ex) {
LOGGER.error(MARKER, "Catched Exception", ex);
}
}
}
開發者ID:uniquid,項目名稱:tank-java,代碼行數:46,
注:本文中的org.fusesource.mqtt.client.BlockingConnection.disconnect方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。