Example usage for io.netty.util.concurrent Future cause

List of usage examples for io.netty.util.concurrent Future cause

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future 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:com.flowpowered.networking.session.BasicSession.java

License:MIT License

public ChannelFuture sendWithFuture(Message message) {
    if (!channel.isActive()) {
        throw new IllegalStateException("Trying to send a message when a session is inactive!");
    }/*w  w  w .  ja  va2s  .  co  m*/
    return channel.writeAndFlush(message).addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.cause() != null) {
                onOutboundThrowable(future.cause());
            }
        }
    });
}

From source file:com.github.milenkovicm.kafka.NoTopicTest.java

License:Apache License

@Test
public void test_producer_no_topic_async() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    String topic = "test_producer_no_topic__async";
    ProducerProperties properties = new ProducerProperties();
    properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true);
    //createTopic(topic);

    KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties);
    final Future<Void> connect = producer.connect();

    connect.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override/*from   www. j  a v  a2s  . c  o  m*/
        public void operationComplete(Future<? super Void> future) throws Exception {
            latch.countDown();
        }
    });

    latch.await(5, TimeUnit.SECONDS);

    Assert.assertThat(connect.isDone(), is(true));
    Assert.assertThat(connect.isSuccess(), is(false));
    Assert.assertThat(connect.cause(), notNullValue());
    Assert.assertThat(((KafkaException) connect.cause()).error, is(Error.LEADER_NOT_AVAILABLE));

    producer.disconnect();
}

From source file:com.github.mrstampy.gameboot.netty.AbstractNettyProcessor.java

License:Open Source License

private void log(Future<? super Void> f, Response response, ChannelHandlerContext ctx) {
    ResponseCode rc = response.getResponseCode();
    Integer id = response.getId();
    if (f.isSuccess()) {
        log.debug("Successfully sent response code {}, id {} to {}", rc, id, ctx.channel());
    } else {/*from w w  w. jav a 2s .co  m*/
        log.error("Could not send response code {}, id {} to {}", rc, id, ctx.channel(), f.cause());
    }
}

From source file:com.github.mrstampy.gameboot.otp.netty.client.ClientHandler.java

License:Open Source License

private void validate(Future<? super Channel> f, ChannelHandlerContext ctx) {
    if (f.isSuccess()) {
        log.debug("Handshake successful with {}", ctx.channel());
    } else {/*w w w  .  j a va 2s. co  m*/
        log.error("Handshake unsuccessful, disconnecting {}", ctx.channel(), f.cause());
        ctx.close();
    }
}

From source file:com.github.mrstampy.gameboot.otp.netty.OtpEncryptedNettyHandler.java

License:Open Source License

private void log(Future<? super Void> f, ChannelHandlerContext ctx, String type) {
    if (f.isSuccess()) {
        log.debug("Successful send of {} to {}, closing channel", type, ctx.channel().remoteAddress());
    } else {//from   w  w w.  j ava2s .  c o m
        log.error("Unsuccessful send of {} to {}, closing channel", type, ctx.channel().remoteAddress(),
                f.cause());
    }

    ctx.close();
}

From source file:com.github.spapageo.jannel.client.ClientSession.java

License:Open Source License

/**
 * Asynchronously sends an sms/* ww  w. jav  a 2 s  .  c o  m*/
 * @param sms           the sms to send
 * @param timeoutMillis the timeout for an open window slot to appear
 * @return the future on the operation
 * @throws InterruptedException   when the operation was interrupted
 */
@SuppressWarnings("unchecked")
@Nonnull
public WindowFuture<Sms, Ack> sendSms(final Sms sms, final long timeoutMillis) throws InterruptedException {

    // Generate UUID if null
    if (sms.getId() == null) {
        sms.setId(UUID.randomUUID());
    }

    // Apply the current client id if null
    if (sms.getBoxId() == null)
        sms.setBoxId(configuration.getClientId());

    WindowFuture future = sendWindow.offer(sms.getId(), sms, timeoutMillis,
            configuration.getRequestExpiryTimeout());

    sendMessage(sms).addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> channelFuture) throws Exception {
            if (!channelFuture.isSuccess() && !channelFuture.isCancelled()) {
                sendWindow.fail(sms.getId(), channelFuture.cause());
            } else if (channelFuture.isCancelled()) {
                sendWindow.cancel(sms.getId(), true);
            }
        }
    });

    return future;
}

From source file:com.github.wolf480pl.ircd.netty.NettySession.java

License:Open Source License

public ChannelFuture sendWithFuture(Message msg) {
    getLogger().debug("" + getRemoteAddress() + " <- " + msg);
    if (!channel.isActive()) {
        throw new IllegalStateException("Trying to send a message when a session is inactive!");
    }/*from   www . j  a  v a 2 s  . c  o m*/
    return channel.writeAndFlush(msg).addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.cause() != null) {
                handler.onOutboundThrowable(NettySession.this, future.cause());
            }
        }
    });

}

From source file:com.heliosapm.streams.tracing.writers.NetWriter.java

License:Apache License

/**
 * Attempts to connect to the specified host/port and updates the channel tracking structures accordingly
 * @param uri The <b><code>host:port</code></b> pair
 *//* www  .jav a 2s.c  o  m*/
protected void connect(final String uri) {
    String _host = null;
    int _port = -1;
    try {
        final String[] hostPort = StringHelper.splitString(uri, ':', true);
        _host = hostPort[0];
        _port = Integer.parseInt(hostPort[1]);
    } catch (Exception ex) {
        log.warn("Invalid Remote URI [{}]", uri);
    }
    final ChannelFuture cf = bootstrap.connect(_host, _port);
    cf.addListener(new GenericFutureListener<Future<Void>>() {
        @Override
        public void operationComplete(final Future<Void> f) throws Exception {
            if (f.isSuccess()) {
                final Channel channel = cf.channel();
                ChannelFuture closeFuture = channel.closeFuture();
                closeFutures.put(uri, closeFuture);
                disconnected.remove(new DelayedReconnect(uri));
                closeFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                    @Override
                    public void operationComplete(final Future<? super Void> future) throws Exception {
                        closeFutures.remove(uri);
                        if (group.isShutdown() || group.isShuttingDown() || group.isTerminated()) {
                            /* No Op */
                        } else {
                            final DelayedReconnect dc = new DelayedReconnect(uri);
                            if (!disconnected.contains(dc)) {
                                disconnected.add(dc);
                            }
                        }
                        channels.remove(channel); // may have been removed already
                        fireDisconnected();
                    }
                });
                channels.add(channel);
                fireConnected();
                log.info("Channel [{}] connected to [{}]", channel, uri);
            } else {
                final DelayedReconnect dc = new DelayedReconnect(uri);
                if (!disconnected.contains(dc)) {
                    disconnected.add(dc);
                }
                log.warn("Channel failed to connect to [{}]", uri, f.cause());
            }
        }
    });
}

From source file:com.heliosapm.tsdblite.handlers.http.HttpRequestManager.java

License:Apache License

/**
 * {@inheritDoc}/*from   www .j ava  2s  .  com*/
 * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object)
 */
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final HttpRequest msg) throws Exception {
    try {
        final String uri = msg.uri();
        final Channel channel = ctx.channel();
        if (uri.endsWith("/favicon.ico")) {
            final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, favicon);
            resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon");
            resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize);
            ctx.writeAndFlush(resp);
            return;
        } else if (uri.equals("/api/put") || uri.equals("/api/metadata")) {
            final ChannelPipeline p = ctx.pipeline();
            //            p.addLast(loggingHandler, jsonAdapter, new JsonObjectDecoder(true), traceHandler);
            p.addLast(jsonAdapter, new JsonObjectDecoder(true), traceHandler);
            //            if(msg instanceof FullHttpRequest) {
            //               ByteBuf b = ((FullHttpRequest)msg).content().copy();
            //               ctx.fireChannelRead(b);
            //            }
            ctx.fireChannelRead(msg);
            p.remove("requestManager");
            log.info("Switched to JSON Trace Processor");
            return;
        }
        final TSDBHttpRequest r = new TSDBHttpRequest(msg, ctx.channel(), ctx);
        final HttpRequestHandler handler = requestHandlers.get(r.getRoute());
        if (handler == null) {
            r.send404().addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> f) throws Exception {
                    log.info("404 Not Found for {} Complete: success: {}", r.getRoute(), f.isSuccess());
                    if (!f.isSuccess()) {
                        log.error("Error sending 404", f.cause());
                    }
                };
            });
            return;
        }
        handler.process(r);
    } catch (Exception ex) {
        log.error("HttpRequest Routing Error", ex);
    }
}

From source file:com.heliosapm.tsdblite.handlers.http.SubmitTracesHandler.java

License:Apache License

/**
 * {@inheritDoc}//w  ww.j a va 2  s.com
 * @see com.heliosapm.tsdblite.handlers.http.HttpRequestHandler#process(com.heliosapm.tsdblite.handlers.http.TSDBHttpRequest)
 */
@Override
protected void process(final TSDBHttpRequest request) {
    log.debug("Processing [{}]", request.getRequest());
    if (!request.hasContent()) {
        request.send400("No content sent for route [", request.getRoute(), "]");
        return;
    }
    final ByteBuf content = request.getContent();
    final Trace[] traces;
    try {
        if (content.getByte(0) == '{') {
            traces = new Trace[] { JSON.parseToObject(content, Trace.class) };
        } else {
            traces = JSON.parseToObject(content, Trace[].class);
        }
    } catch (JSONException jex) {
        log.error("Failed to parse JSON payload", jex);
        request.send400("Invalid JSON payload for route [", request.getRoute(), "]:", jex.toString());
        return;
    }
    final ElapsedTime et = SystemClock.startClock();
    for (Trace trace : traces) {
        //log.debug("TRACE: {}", trace);
        metricCache.submit(trace);
    }
    request.send204().addListener(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(final Future<? super Void> f) throws Exception {
            if (f.isSuccess()) {
                log.info("Traces Processed: {}", et.printAvg("traces", traces.length));
            } else {
                log.error("Traces failed", f.cause());
            }
        };
    });
}