Example usage for io.netty.channel ChannelFuture cause

List of usage examples for io.netty.channel ChannelFuture cause

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture cause.

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:org.springframework.boot.context.embedded.netty.NettyEmbeddedServletContainer.java

License:Apache License

@Override
public void start() throws EmbeddedServletContainerException {
    ServerBootstrap b = new ServerBootstrap();
    groups(b);/*from  w  ww  .j  a v a 2 s .  c  om*/
    servletExecutor = new DefaultEventExecutorGroup(50);
    b.childHandler(new NettyEmbeddedServletInitializer(servletExecutor, context));

    // Don't yet need the complexity of lifecycle state, listeners etc, so tell the context it's initialised here
    context.setInitialised(true);

    ChannelFuture future = b.bind(address).awaitUninterruptibly();
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable cause = future.cause();
    if (null != cause) {
        throw new EmbeddedServletContainerException("Could not start Netty server", cause);
    }
    logger.info(context.getServerInfo() + " started on port: " + getPort());
}

From source file:org.springframework.http.client.Netty4ClientHttpRequest.java

License:Apache License

@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(final HttpHeaders headers) throws IOException {
    final SettableListenableFuture<ClientHttpResponse> responseFuture = new SettableListenableFuture<ClientHttpResponse>();

    ChannelFutureListener connectionListener = new ChannelFutureListener() {
        @Override/* w  ww  .j a  va  2  s .  c  o  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                Channel channel = future.channel();
                channel.pipeline().addLast(new RequestExecuteHandler(responseFuture));
                FullHttpRequest nettyRequest = createFullHttpRequest(headers);
                channel.writeAndFlush(nettyRequest);
            } else {
                responseFuture.setException(future.cause());
            }
        }
    };

    this.bootstrap.connect(this.uri.getHost(), getPort(this.uri)).addListener(connectionListener);

    return responseFuture;
}

From source file:org.stem.client.Connection.java

License:Apache License

public Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException {
    this.name = name;
    this.address = address;
    this.factory = factory;
    dispatcher = new Dispatcher();

    Bootstrap bootstrap = factory.createNewBootstrap();
    bootstrap.handler(new ChannelHandler(this));

    ChannelFuture future = bootstrap.connect(address);
    writeCounter.incrementAndGet();//from w  w  w .  j  a  v a  2  s  .  co  m
    try {
        this.channel = future.awaitUninterruptibly().channel();
        if (!future.isSuccess()) {
            if (logger.isDebugEnabled())
                logger.debug(String.format("%s Error connecting to %s%s", this, address,
                        extractMessage(future.cause())));
            throw defunct(new ClientTransportException(address, "Can't connect", future.cause()));
        }
    } finally {
        writeCounter.decrementAndGet();
    }

    logger.trace("{} Connection opened successfully", this);
    isInitialized = true;
}

From source file:org.stem.client.Connection.java

License:Apache License

private ChannelFutureListener writeHandler(final Message.Request request, final ResponseHandler handler) {
    return new ChannelFutureListener() {
        @Override/*w w w  .  j a v  a 2 s  .c o m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            writeCounter.decrementAndGet();
            if (!future.isSuccess()) {
                logger.debug("{} Error writing request {}", Connection.this, request);
                dispatcher.removeHandler(handler.streamId, true);

                ConnectionException e;
                if (future.cause() instanceof ClosedChannelException) {
                    e = new ClientTransportException(address, "Error writing to closed channel");
                } else {
                    e = new ClientTransportException(address, "Error writing", future.cause());
                }

                // No retries yet
                handler.callback.onException(Connection.this, defunct(e),
                        System.nanoTime() - handler.startTime);
            } else {
                logger.trace("{} request sent successfully", Connection.this);
            }
        }
    };
}

From source file:org.stem.client.old.StorageNodeClient.java

License:Apache License

public void start() throws IOException {
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    channel = future.awaitUninterruptibly().channel();

    if (!future.isSuccess()) {
        throw new IOException("Connection failed", future.cause());
    }//from  ww  w.  j  av a 2  s .  c  o  m
    this.connected = true;
}

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  .jav  a2  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;
}

From source file:org.thingsplode.synapse.endpoint.Endpoint.java

License:Apache License

public DispatchedFuture<Command, CommandResult> dispatchCommand(ConnectionContext connection, Command command,
        long timeToLive) {
    if (!bidirectionalCommsEnabled) {
        throw new UnsupportedOperationException(
                "Dispatching from the endpoint is only supported with protocols which are supporting bidirectional communication (eg. websocket, mqtt). Please enable such protocol if you need dispatching throug them.");
    }/*from   w  ww.j  av a2  s. co  m*/
    command.getHeader().setMsgId(msgIdGeneratorStrategy.getNextId());
    DispatchedFuture<Command, CommandResult> dispatcherFuture = new DispatchedFuture<>(command,
            connection.getCtx().channel(), timeToLive);
    if (lifecycle == ComponentLifecycle.UNITIALIZED) {
        dispatcherFuture.completeExceptionally(new IllegalStateException("The endpoing is not initialized."));
        return dispatcherFuture;
    } else {
        messageStore.beforeDispatch(dispatcherFuture);
        ChannelFuture cf = connection.getCtx().channel().writeAndFlush(command);
        cf.addListener((ChannelFutureListener) (ChannelFuture future) -> {
            if (!future.isSuccess()) {
                //the message could not be sent
                //todo: build a retry mechanism?
                messageStore.responseReceived(command.getHeader().getMsgId());
                dispatcherFuture.completeExceptionally(future.cause());
                future.channel().close();
            } else if (logger.isTraceEnabled()) {
                logger.trace(command.getClass().getSimpleName()
                        + " message is succesfully dispatched with Msg. Id.: "
                        + command.getHeader().getMsgId());
            }
        });
    }
    return dispatcherFuture;
}

From source file:org.thingsplode.synapse.endpoint.handlers.HttpRequestHandler.java

License:Apache License

private void upgradeToWebsocket(ChannelHandlerContext ctx, FullHttpRequest httpRequest) {

    String wsUrl = "ws://" + httpRequest.headers().get(HttpHeaderNames.HOST) + "/" + endpointId;
    //todo: configure frame size
    WebSocketServerHandshakerFactory wsHandshakeFactory = new WebSocketServerHandshakerFactory(wsUrl, null,
            false);/*from  w  ww  .j  a  va 2s .com*/
    WebSocketServerHandshaker handshaker = wsHandshakeFactory.newHandshaker(httpRequest);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), httpRequest)
                .addListener((ChannelFutureListener) new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            logger.debug("Switching to websocket. Replacing the "
                                    + Endpoint.HTTP_RESPONSE_HANDLER + " with " + Endpoint.WS_RESPONSE_HANDLER);
                            ctx.pipeline().replace(Endpoint.HTTP_REQUEST_HANDLER, Endpoint.WS_REQUEST_HANDLER,
                                    new WebsocketRequestHandler(handshaker));
                            ctx.pipeline().replace(Endpoint.HTTP_RESPONSE_HANDLER, Endpoint.WS_RESPONSE_HANDLER,
                                    new WebsocketResponseHandler());
                            ctx.pipeline().addAfter(Endpoint.WS_RESPONSE_HANDLER, Endpoint.WS_COMMAND_HANDLER,
                                    new Command2WsEncoder());
                            if (ctx.pipeline().get(Endpoint.RESPONSE_INTROSPECTOR) != null) {
                                ctx.pipeline().addAfter(Endpoint.RESPONSE_INTROSPECTOR,
                                        Endpoint.WS_REQUEST_INTROSPECTOR, new WebsocketIntrospector());
                            }
                        } else {
                            String msg = "Dispatching upgrade acknowledgement was not successfull due to ";
                            if (future.cause() != null) {
                                logger.error(msg + future.cause().getClass().getSimpleName() + " with message: "
                                        + future.cause().getMessage(), future.cause());
                            } else {
                                logger.error(msg + " unknown reasons.");
                            }
                        }
                    }
                });
    }
}

From source file:org.thingsplode.synapse.endpoint.handlers.HttpResponseHandler.java

License:Apache License

public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, String errorMsg,
        HttpRequest request) {//from  w w w.  j av a2s.  com
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + errorMsg + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    if (request != null && request.headers().contains(AbstractMessage.PROP_MESSAGE_ID)) {
        response.headers().set(AbstractMessage.PROP_CORRELATION_ID,
                request.headers().get(AbstractMessage.PROP_MESSAGE_ID));
    }
    writeResponseWithKeepaliveHandling(ctx, response,
            request != null ? HttpHeaders.isKeepAlive(request) : false)
                    .addListener((ChannelFutureListener) (ChannelFuture future) -> {
                        Throwable th = future.cause();
                        if (th != null) {
                            logger.error(
                                    "Sending response from Endpoint was not successful: " + th.getMessage(),
                                    th);
                        }
                        if (logger.isDebugEnabled() && future.isSuccess()) {
                            logger.debug("Error Response message was succesfully dispatched at the endpoint.");
                        }
                    });
}

From source file:org.thingsplode.synapse.endpoint.handlers.WebsocketResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Response response) throws Exception {
    byte[] content = serializationService.getSerializer(MediaType.APPLICATION_JSON).marshall(response);
    TextWebSocketFrame wsFrame = new TextWebSocketFrame(Unpooled.wrappedBuffer(content));
    ChannelFuture cf = ctx.writeAndFlush(wsFrame)
            .addListener((ChannelFutureListener) new ChannelFutureListener() {
                @Override//from  w ww.ja v a2s  .co m
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        logger.error(
                                "Closing channel due to an error while sending response to websocket client -> "
                                        + (future.cause() != null ? future.cause().getMessage()
                                                : "unknown reason."));
                        ctx.channel().close();
                    }
                }
            });
    if (!response.getHeader().isKeepAlive()) {
        cf.addListener((ChannelFutureListener) (ChannelFuture future) -> {
            ctx.writeAndFlush(new CloseWebSocketFrame(true, 0));
        }).addListener(ChannelFutureListener.CLOSE);
    }
}