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

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

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:com.gxkj.demo.netty.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from  w  ww. java  2s .c  om*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                ctx.pipeline().remove(getName());
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.channel().pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientInitializer(promise));

    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

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
 *///from   w w  w  .  j av a  2 s  . 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}/* w ww.j a v a 2s. c  o m*/
 * @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}/*from  www.  j  av  a2s . c om*/
 * @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());
            }
        };
    });
}

From source file:com.hipishare.chat.server.handler.SecureChatHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    LOG.info("[]?channel");
    SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    if (null != sslHandler) {
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override//from  w ww  .j  a va  2  s. co  m
            public void operationComplete(Future<Channel> future) throws Exception {
                if (future.isSuccess()) {
                    LOG.info("SSL??");
                    channels.add(ctx.channel());
                }
            }
        });
    }
}

From source file:com.hop.hhxx.example.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override//from   w  w w .  j a  va  2 s.c om
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(ctx.channel()));
                            ctx.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new io.netty.example.socksproxy.DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, request.dstAddrType()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(ctx.channel()));
                            ctx.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.ibasco.agql.core.transport.NettyPooledTransport.java

License:Open Source License

/**
 * <p>Acquires a {@link Channel} from the {@link ChannelPool}</p>
 *
 * @param message/*from  w  w  w. j a  v a2s  . com*/
 *         An {@link AbstractRequest} that will be used as the lookup reference for the {@link
 *         io.netty.channel.pool.ChannelPoolMap} key
 *
 * @return A {@link CompletableFuture} containing the acquired {@link Channel}
 */
@Override
public CompletableFuture<Channel> getChannel(M message) {
    final CompletableFuture<Channel> channelFuture = new CompletableFuture<>();
    //Retrieve our channel pool based on the message
    final ChannelPool pool = poolMap.get(message);

    log.debug("Acquiring channel from pool '{}' for message : {}", pool, message);

    //Acquire a channel from the pool and listen for completion
    pool.acquire().addListener((Future<Channel> future) -> {
        if (future.isSuccess()) {
            log.debug("Successfully acquired Channel from pool");
            Channel channel = future.get();
            channel.attr(ChannelAttributes.CHANNEL_POOL).set(pool);
            channelFuture.complete(channel);
        } else {
            log.debug("Failed to acquire Channel from Pool");
            channelFuture.completeExceptionally(new ConnectException(future.cause()));
        }
    });
    return channelFuture;
}

From source file:com.jfastnet.peers.netty.FutureGenericFutureListener.java

License:Apache License

@Override
public void operationComplete(final Future<? super Void> future) throws Exception {
    if (!future.isSuccess()) {
        if (callerObj != null) {
            log.error("Operation failed for '{}'. Caller: {}, Message: {}, toString: {}",
                    new Object[] { action, callerObj.getClass().getSimpleName(),
                            messageObj.getClass().getSimpleName(), messageObj.toString(), future.cause() });
            if (messageObj instanceof Message) {
                Message message = (Message) messageObj;
                if (message.payload instanceof ByteBuf) {
                    ByteBuf payload = (ByteBuf) message.payload;
                    int writerIndex = payload.writerIndex();
                    log.error("Size of failed message: {}", writerIndex);
                }/*  w ww. jav  a2 s  .c  om*/
            }
        } else if (msgType == null) {
            log.error("Operation failed", future.cause());
        } else {
            log.error("Operation failed for {}", msgType, future.cause());
        }
    }
}

From source file:com.king.platform.net.http.netty.ChannelManager.java

License:Apache License

private void sendOnChannel(final Channel channel, final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {

    httpRequestContext.attachedToChannel(channel);

    scheduleTimeOutTasks(requestEventBus, httpRequestContext, httpRequestContext.getTotalRequestTimeoutMillis(),
            httpRequestContext.getIdleTimeoutMillis());

    ChannelFuture channelFuture = channel.writeAndFlush(httpRequestContext);
    channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override/*from   w  w  w  .j  av a 2 s . c  om*/
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (!future.isSuccess()) {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }
        }
    });

    logger.trace("Wrote {} to channel {}", httpRequestContext, channel);
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Connects to the hostname and port./*from   w ww.j ava  2s. c  o  m*/
 * 
 * @param hostname
 * @param port
 */
public ListenableFuture<KixmppClient> connect(String hostname, int port, String domain) {
    checkAndSetState(State.CONNECTING, State.DISCONNECTED);

    this.jid = new KixmppJid(domain);
    try {
        this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(
                new URI("ws://" + hostname + ":" + port), WebSocketVersion.V13, null, false,
                new DefaultHttpHeaders());
    } catch (Exception e) {
        throw new RuntimeException("Unable to set up handshaker.", e);
    }

    setUp();

    // set this in case we get disconnected
    deferredDisconnect = SettableFuture.create();
    deferredLogin = SettableFuture.create();

    final SettableFuture<KixmppClient> responseFuture = SettableFuture.create();

    connectListener.set(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.isSuccess()) {
                if (state.compareAndSet(State.CONNECTING, State.CONNECTED)) {
                    logger.info("Kixmpp Client connected to [{}]",
                            ((ChannelFuture) future).channel().remoteAddress());

                    channel.set(((ChannelFuture) future).channel());
                    responseFuture.set(KixmppClient.this);
                }
            } else {
                state.set(State.DISCONNECTED);
                responseFuture.setException(future.cause());
            }
        }
    });

    ChannelFuture future = bootstrap.connect(hostname, port);

    switch (type) {
    case TCP:
        future.addListener(connectListener.get());
        break;
    case WEBSOCKET:
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (!future.isSuccess()) {
                    state.set(State.DISCONNECTED);
                    responseFuture.setException(future.cause());
                }
            }
        });
        break;
    }

    return responseFuture;
}