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:io.reactivex.netty.util.MultipleFutureListener.java

License:Apache License

public MultipleFutureListener(final ChannelPromise completionPromise) {
    if (null == completionPromise) {
        throw new NullPointerException("Promise can not be null.");
    }//from   w ww.  j  av a2s  .co m
    this.completionPromise = completionPromise;
    completionObservable = Observable.create(new Observable.OnSubscribe<Void>() {
        @Override
        public void call(final Subscriber<? super Void> subscriber) {
            if (listeningToCount.get() == 0) {
                MultipleFutureListener.this.completionPromise.trySuccess();
            }
            MultipleFutureListener.this.completionPromise.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        subscriber.onCompleted();
                    } else {
                        subscriber.onError(future.cause());
                    }
                }
            });
        }
    });
}

From source file:io.soliton.protobuf.AbstractRpcServer.java

License:Apache License

/**
 * Starts this server.// w  w w  .j a  v  a2s  . c  om
 * <p/>
 * <p>This is a synchronous operation.</p>
 */
public void startUp() throws Exception {
    logger.info(String.format("Starting RPC server on port %d", port));
    ServerBootstrap bootstrap = new ServerBootstrap();

    ChannelFuture futureChannel = bootstrap.group(parentGroup, childGroup).channel(channelClass)
            .childHandler(channelInitializer()).bind(port).awaitUninterruptibly();

    if (futureChannel.isSuccess()) {
        this.channel = futureChannel.channel();
        logger.info("RPC server started successfully.");
    } else {
        logger.info("Failed to start RPC server.");
        throw new Exception(futureChannel.cause());
    }
}

From source file:io.soliton.protobuf.json.HttpJsonRpcClient.java

License:Apache License

@Override
public <O extends Message> ListenableFuture<O> encodeMethodCall(final ClientMethod<O> method, Message input) {
    clientLogger.logMethodCall(method);//  ww w. j  a v  a2  s. c  o  m
    final JsonResponseFuture<O> responseFuture = handler.newProvisionalResponse(method);

    JsonObject request = new JsonRpcRequest(method.serviceName(), method.name(),
            new JsonPrimitive(responseFuture.requestId()), Messages.toJson(input)).toJson();

    ByteBuf requestBuffer = Unpooled.buffer();
    JsonWriter writer = new JsonWriter(
            new OutputStreamWriter(new ByteBufOutputStream(requestBuffer), Charsets.UTF_8));
    GSON.toJson(request, writer);
    try {
        writer.flush();
    } catch (IOException ioe) {
        // Deliberately ignored, as this doesn't involve any I/O
    }

    String host = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();

    QueryStringEncoder encoder = new QueryStringEncoder(rpcPath);
    encoder.addParam("pp", "0");
    HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            encoder.toString(), requestBuffer);
    httpRequest.headers().set(HttpHeaders.Names.HOST, host);
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, JsonRpcProtocol.CONTENT_TYPE);
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestBuffer.readableBytes());

    channel.writeAndFlush(httpRequest).addListener(new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess()) {
                clientLogger.logLinkError(method, future.cause());
                handler.finish(responseFuture.requestId());
                responseFuture.setException(future.cause());
            }
        }

    });

    return responseFuture;
}

From source file:io.soliton.protobuf.quartz.QuartzClient.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  w w  . j a v a2 s.  c  o  m*/
 */
@Override
public <O extends Message> ListenableFuture<O> encodeMethodCall(final ClientMethod<O> method, Message input) {
    // Channel was manually closed earlier
    if (refuseNewRequests.get()) {
        return Futures.immediateFailedFuture(new RuntimeException("Client is closed"));
    }

    // Channel was closed by the server - we make an attempt to reopen.
    if (shouldCreateNewChannel.get()) {
        try {
            reopenChannel();
            channel.closeFuture().addListener(new ChannelCloser());
        } catch (IOException ioe) {
            return Futures.immediateFailedFuture(ioe);
        }
    }

    // Normal operation mode
    clientLogger.logMethodCall(method);
    final EnvelopeFuture<O> output = handler.newProvisionalResponse(method);
    Envelope request = Envelope.newBuilder().setRequestId(output.requestId()).setService(method.serviceName())
            .setMethod(method.name()).setPayload(input.toByteString()).build();

    HttpRequest httpRequest = handler.convertRequest(request);
    channel.writeAndFlush(httpRequest).addListener(new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess()) {
                clientLogger.logLinkError(method, future.cause());
                handler.finish(output.requestId());
                output.setException(future.cause());
            }
        }

    });

    return output;
}

From source file:io.soliton.protobuf.socket.RpcClient.java

License:Apache License

/**
 * {@inheritDoc}//from  w  ww  . ja v  a  2s  .  c  o  m
 */
@Override
public <O extends Message> ListenableFuture<O> encodeMethodCall(final ClientMethod<O> method, Message input) {
    clientLogger.logMethodCall(method);
    final EnvelopeFuture<O> output = handler.newProvisionalResponse(method);
    Envelope request = Envelope.newBuilder().setRequestId(output.requestId()).setService(method.serviceName())
            .setMethod(method.name()).setPayload(input.toByteString()).build();
    // TODO(julien): might be nice to couple the future returned from writeAndFlush
    // into the one returned to the user, so that calling cancel on the userland
    // future may also cancel the outgoing request if it isn't done yet.
    channel.writeAndFlush(request).addListener(new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess()) {
                clientLogger.logLinkError(method, future.cause());
                handler.finish(output.requestId());
                output.setException(future.cause());
            }
        }

    });
    return output;
}

From source file:io.undertow.websockets.utils.WebSocketTestClient.java

License:Open Source License

/**
 * Send the WebSocketFrame and call the FrameListener once a frame was received as response or
 * when an Exception was caught./*  w w w.  j  ava 2  s . co  m*/
 */
public WebSocketTestClient send(WebSocketFrame frame, final FrameListener listener) {
    ch.pipeline().addLast("responseHandler" + count.incrementAndGet(),
            new SimpleChannelInboundHandler<Object>() {

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof CloseWebSocketFrame) {
                        closed = true;
                    }
                    listener.onFrame((WebSocketFrame) msg);
                    ctx.pipeline().remove(this);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    cause.printStackTrace();
                    listener.onError(cause);
                    ctx.pipeline().remove(this);
                }
            });
    ChannelFuture cf = ch.writeAndFlush(frame).syncUninterruptibly();
    if (!cf.isSuccess()) {
        listener.onError(cf.cause());
    }
    return this;
}

From source file:io.urmia.proxy.DirectWriteBackHttpProxyBackendHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override/* ww w. j a v  a2 s  . co m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                //log.info("success on write back to inbound");
                ctx.channel().read();
            } else {
                log.warn("fail on write to back to inbound: {}", future.cause());
                future.channel().close();
            }
        }
    });

}

From source file:io.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private Channel openOutboundChannel(final ChannelHandlerContext ctx, String remoteHost, int remotePort,
        final int index) {

    log.info("proxy opening outbound channel to({}): {}:{}", index, remoteHost, remotePort);

    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new HttpProxyBackendInitializer(ctx, index, directWriteBack))
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    Channel outboundChannel = f.channel();
    f.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override/* ww  w.j a v  a2  s  .  c  om*/
        public void operationComplete(ChannelFuture futureC) throws Exception {
            if (futureC.isSuccess()) {
                futureC.channel().writeAndFlush(initHttpRequest)
                        .addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(ChannelFuture futureW) throws Exception {
                                if (futureW.isSuccess())
                                    onSuccessfulWrite(ctx, index);
                                else {
                                    log.info("unable to write http request: {}", futureW.cause());
                                    ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index));
                                }
                            }
                        });
            } else {
                ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index));
            }
        }
    });

    return outboundChannel;
}

From source file:io.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private void writeToAllOutbounds(final ChannelHandlerContext ctx, final HttpContent msg) {

    writeSet.clear();/*  w  ww  . j  av  a2  s  .c  om*/

    final int contentSize = msg.content().writableBytes();

    int i = 0;

    for (final Channel outboundChannel : outboundChannels) {

        final int chIdx = i++;

        outboundChannel.writeAndFlush(msg.duplicate()) // duplicate because different widx
                .addListener(new GenericFutureListener<ChannelFuture>() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            writtenSizes[chIdx].addAndGet(contentSize);
                            onSuccessfulWrite(ctx, chIdx);
                        } else {
                            log.error("error to write to outbound", future.cause());
                            future.channel().close();
                        }

                    }
                });
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsQueryContext.java

License:Apache License

private void onQueryWriteCompletion(ChannelFuture writeFuture) {
    if (!writeFuture.isSuccess()) {
        setFailure("failed to send a query", writeFuture.cause());
        return;/*ww  w.  j a va  2 s.c o m*/
    }

    // Schedule a query timeout task if necessary.
    final long queryTimeoutMillis = parent.queryTimeoutMillis();
    if (queryTimeoutMillis > 0) {
        timeoutFuture = parent.ch.eventLoop().schedule(new OneTimeTask() {
            @Override
            public void run() {
                if (promise.isDone()) {
                    // Received a response before the query times out.
                    return;
                }

                setFailure("query timed out after " + queryTimeoutMillis + " milliseconds", null);
            }
        }, queryTimeoutMillis, TimeUnit.MILLISECONDS);
    }
}