Example usage for io.netty.util.concurrent Promise setFailure

List of usage examples for io.netty.util.concurrent Promise setFailure

Introduction

In this page you can find the example usage for io.netty.util.concurrent Promise setFailure.

Prototype

Promise<V> setFailure(Throwable cause);

Source Link

Document

Marks this future as a failure and notifies all listeners.

Usage

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

License:Apache License

/**
 * Publish a message to the given payload, using the given qos and optional retain
 *
 * @param topic   The topic to publish to
 * @param payload The payload to send// w ww  .  j a v  a 2 s  .  c  om
 * @param qos     The qos to use while publishing
 * @param retain  true if you want to retain the message on the server, false otherwise
 * @return A future which will be completed when the message is delivered to the server
 */
@Override
public Future<Void> publish(String topic, ByteBuf payload, MqttQoS qos, boolean retain) {
    Promise<Void> future = new DefaultPromise<>(this.eventLoop.next());
    MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retain, 0);
    MqttPublishVariableHeader variableHeader = new MqttPublishVariableHeader(topic,
            getNewMessageId().messageId());
    MqttPublishMessage message = new MqttPublishMessage(fixedHeader, variableHeader, payload);
    MqttPendingPublish pendingPublish = new MqttPendingPublish(variableHeader.messageId(), future,
            payload.retain(), message, qos);
    ChannelFuture channelFuture = this.sendAndFlushPacket(message);

    if (channelFuture != null) {
        pendingPublish.setSent(true);
        if (channelFuture.cause() != null) {
            future.setFailure(channelFuture.cause());
            return future;
        }
    }
    if (pendingPublish.isSent() && pendingPublish.getQos() == MqttQoS.AT_MOST_ONCE) {
        pendingPublish.getFuture().setSuccess(null); //We don't get an ACK for QOS 0
    } else if (pendingPublish.isSent()) {
        this.pendingPublishes.put(pendingPublish.getMessageId(), pendingPublish);
        pendingPublish.startPublishRetransmissionTimer(this.eventLoop.next(), this::sendAndFlushPacket);
    }
    return future;
}