Example usage for io.netty.handler.codec.mqtt MqttTopicSubscription MqttTopicSubscription

List of usage examples for io.netty.handler.codec.mqtt MqttTopicSubscription MqttTopicSubscription

Introduction

In this page you can find the example usage for io.netty.handler.codec.mqtt MqttTopicSubscription MqttTopicSubscription.

Prototype

public MqttTopicSubscription(String topicFilter, MqttQoS qualityOfService) 

Source Link

Usage

From source file:io.vertx.mqtt.impl.MqttClientImpl.java

License:Apache License

/**
 * See {@link MqttClient#subscribe(Map, Handler)} for more details
 *///  w w w .j  av a 2  s  .  c om
@Override
public MqttClient subscribe(Map<String, Integer> topics, Handler<AsyncResult<Integer>> subscribeSentHandler) {

    Map<String, Integer> invalidTopics = topics.entrySet().stream().filter(e -> !isValidTopicFilter(e.getKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    if (invalidTopics.size() > 0) {
        String msg = String.format("Invalid Topic Filters: %s", invalidTopics);
        log.error(msg);
        MqttException exception = new MqttException(MqttException.MQTT_INVALID_TOPIC_FILTER, msg);
        if (subscribeSentHandler != null) {
            subscribeSentHandler.handle(Future.failedFuture(exception));
        }
        return this;
    }

    MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.SUBSCRIBE, false, AT_LEAST_ONCE, false,
            0);

    MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(nextMessageId());
    List<MqttTopicSubscription> subscriptions = topics.entrySet().stream()
            .map(e -> new MqttTopicSubscription(e.getKey(), valueOf(e.getValue())))
            .collect(Collectors.toList());

    MqttSubscribePayload payload = new MqttSubscribePayload(subscriptions);

    io.netty.handler.codec.mqtt.MqttMessage subscribe = MqttMessageFactory.newMessage(fixedHeader,
            variableHeader, payload);

    this.write(subscribe);

    if (subscribeSentHandler != null) {
        subscribeSentHandler.handle(Future.succeededFuture(variableHeader.messageId()));
    }
    return this;
}

From source file:net.anyflow.lannister.session.WillTest.java

License:Apache License

@Test
public void testWillSend() throws Exception {
    String willTopic = "will";
    String message = "ASTALAVISTA";

    String client0Id = TestUtil.newClientId();
    ConnectOptions options = new ConnectOptions();
    options.clientId(client0Id);/*w ww  .j  ava  2  s  .  c o  m*/
    options.will(new Message(-1, willTopic, null, message.getBytes(CharsetUtil.UTF_8), MqttQoS.AT_LEAST_ONCE,
            false));
    options.cleanSession(false);

    MqttClient client0 = new MqttClient("mqtt://localhost:" + Settings.SELF.mqttPort());
    MqttConnectReturnCode ret = client0.connectOptions(options).connect();

    Assert.assertEquals(MqttConnectReturnCode.CONNECTION_ACCEPTED, ret);
    Assert.assertTrue(client0.isConnected());

    Assert.assertTrue(Session.NEXUS.get(client0Id).will() != null
            && Session.NEXUS.get(client0Id).will().topicName().equals(willTopic));

    // ================= client1 creation

    class MessageWrapper {
        private IMessage message = null;

        public IMessage getMessage() {
            return message;
        }

        public void setMessage(IMessage message) {
            this.message = message;
        }
    }

    MessageWrapper wrapper = new MessageWrapper();

    String client1Id = TestUtil.newClientId();
    ConnectOptions options1 = new ConnectOptions();
    options1.clientId(client1Id);

    MqttClient client1 = new MqttClient("mqtt://localhost:" + Settings.SELF.mqttPort());
    ret = client1.connectOptions(options1).receiver(m -> {
        wrapper.setMessage(m);

        synchronized (wrapper) {
            wrapper.notify();
        }
    }).connect();

    client1.subscribe(new MqttTopicSubscription(willTopic, MqttQoS.AT_LEAST_ONCE));

    Assert.assertEquals(MqttConnectReturnCode.CONNECTION_ACCEPTED, ret);
    Assert.assertTrue(client1.isConnected());

    Thread.sleep(500); // for client1 connecting & subscribing

    client0.disconnect(false); // abnormal disconnect

    Thread.sleep(500); // for client0's will to null

    synchronized (wrapper) {
        wrapper.wait(5000);
    }

    IMessage will = wrapper.getMessage();

    Assert.assertNull(Session.NEXUS.get(client0Id).will());
    Assert.assertNotNull(will);
    Assert.assertTrue(will.topicName().equals(willTopic));
    Assert.assertNull(Topic.NEXUS.get(will.topicName()).retainedMessage());
    Assert.assertTrue(message.equals(new String(wrapper.getMessage().message())));
}

From source file:org.thingsboard.mqtt.MqttClientImpl.java

License:Apache License

private Future<Void> createSubscription(String topic, MqttHandler handler, boolean once, MqttQoS qos) {
    if (this.pendingSubscribeTopics.contains(topic)) {
        Optional<Map.Entry<Integer, MqttPendingSubscription>> subscriptionEntry = this.pendingSubscriptions
                .entrySet().stream().filter((e) -> e.getValue().getTopic().equals(topic)).findAny();
        if (subscriptionEntry.isPresent()) {
            subscriptionEntry.get().getValue().addHandler(handler, once);
            return subscriptionEntry.get().getValue().getFuture();
        }//  w w  w. j  a v  a2  s .com
    }
    if (this.serverSubscriptions.contains(topic)) {
        MqttSubscription subscription = new MqttSubscription(topic, handler, once);
        this.subscriptions.put(topic, subscription);
        this.handlerToSubscribtion.put(handler, subscription);
        return this.channel.newSucceededFuture();
    }

    Promise<Void> future = new DefaultPromise<>(this.eventLoop.next());
    MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.SUBSCRIBE, false, MqttQoS.AT_LEAST_ONCE,
            false, 0);
    MqttTopicSubscription subscription = new MqttTopicSubscription(topic, qos);
    MqttMessageIdVariableHeader variableHeader = getNewMessageId();
    MqttSubscribePayload payload = new MqttSubscribePayload(Collections.singletonList(subscription));
    MqttSubscribeMessage message = new MqttSubscribeMessage(fixedHeader, variableHeader, payload);

    final MqttPendingSubscription pendingSubscription = new MqttPendingSubscription(future, topic, message);
    pendingSubscription.addHandler(handler, once);
    this.pendingSubscriptions.put(variableHeader.messageId(), pendingSubscription);
    this.pendingSubscribeTopics.add(topic);
    pendingSubscription.setSent(this.sendAndFlushPacket(message) != null); //If not sent, we will send it when the connection is opened

    pendingSubscription.startRetransmitTimer(this.eventLoop.next(), this::sendAndFlushPacket);

    return future;
}