List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:com.sangupta.swift.netty.proxy.ProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext channelHandlerContext) { final Channel inboundChannel = channelHandlerContext.channel(); // Start the connection attempt. Bootstrap bootstrap = new Bootstrap(); bootstrap.group(inboundChannel.eventLoop()).channel(channelHandlerContext.channel().getClass()) .handler(new ProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture channelFuture = bootstrap.connect(remoteHost, remotePort); outboundChannel = channelFuture.channel(); channelFuture.addListener(new ChannelFutureListener() { @Override//from www . jav a 2 s.c o m public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:com.sangupta.swift.netty.proxy.ProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext channelHandlerContext, Object message) { if (outboundChannel.isActive()) { outboundChannel.writeAndFlush(message).addListener(new ChannelFutureListener() { @Override/*w w w . j a v a 2 s .c o m*/ public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk channelHandlerContext.channel().read(); } else { future.channel().close(); } } }); } }
From source file:com.slyak.services.proxy.handler.Socks5CommandRequestHandler.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext requestChannelContext, final DefaultSocks5CommandRequest msg) throws Exception { if (Socks5CommandType.CONNECT.equals(msg.type())) { log.debug("Start to connect remote server : {}:{}", msg.dstAddr(), msg.dstPort()); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(remoteEventLoopGroup).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override/* w w w. ja va 2 s . c o m*/ protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new IdleStateHandler(0, 0, 30)); pipeline.addLast(new IdleEventHandler()); pipeline.addLast(new Remote2RequestHandler(requestChannelContext.channel())); pipeline.addLast(ExceptionHandler.INSTANCE); } }); final ChannelFuture future = bootstrap.connect(msg.dstAddr(), msg.dstPort()); this.remoteChannel = future.channel(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture connectFuture) throws Exception { if (connectFuture.isSuccess()) { log.debug("Connected to remote server"); requestChannelContext.pipeline().addLast(new Request2RemoteHandler(remoteChannel)); Socks5CommandResponse response = new DefaultSocks5CommandResponse( Socks5CommandStatus.SUCCESS, Socks5AddressType.IPv4); //add client to dest handler to receive response requestChannelContext.writeAndFlush(response); } else { log.debug("Failed to connect to remote server"); Socks5CommandResponse commandResponse = new DefaultSocks5CommandResponse( Socks5CommandStatus.FAILURE, Socks5AddressType.IPv4); requestChannelContext.writeAndFlush(commandResponse); } } }); } else { log.debug("Fire channel read"); requestChannelContext.fireChannelRead(msg); } }
From source file:com.sohail.alam.http.common.utils.HttpResponseSender.java
License:Apache License
/** * Send channel future.//from w w w . j a v a 2 s .c o m * * @param ctx the ctx * @param status the status * @param headersMap the headers map * @param data the data * @param useDefaultListener use default listener * * @return the channel future */ public static ChannelFuture send(ChannelHandlerContext ctx, HttpResponseStatus status, Map<String, String> headersMap, byte[] data, boolean useDefaultListener) { final HttpResponse response; // Create the headers map if null if (headersMap == null) { headersMap = new HashMap<String, String>(); } // If data is not null then add content length header and send Full Http Response if (data != null) { ByteBuf dataBuffer = copiedBuffer(data); response = new DefaultFullHttpResponse(HTTP_1_1, status, dataBuffer); // If no content length is supplied then calculate it and add it if (headersMap.get(CONTENT_LENGTH) == null) { headersMap.put(CONTENT_LENGTH, String.valueOf(data.length)); } } // If data is null then add content length header to 0 else { response = new DefaultHttpResponse(HTTP_1_1, status); headersMap.put(CONTENT_LENGTH, String.valueOf(0)); } // Iterate all headers from map and set response headers for (String header : headersMap.keySet()) { response.headers().set(header, headersMap.get(header)); } // Send the response ChannelFuture future = ctx.channel().write(response); // Use default future listener if needed if (useDefaultListener) { future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOGGER.debug("Response sent successfully:\n{}", response); } else { LOGGER.debug("FAILED TO SEND RESPONSE!!\n{}", response); } } }); } return future; }
From source file:com.sohail.alam.http.server.SetupServer.java
License:Apache License
public void initialize() { final ServerBootstrap serverBootstrap = new ServerBootstrap(); final EventLoopGroup boss = new NioEventLoopGroup(); final EventLoopGroup worker = new NioEventLoopGroup(); serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, ServerProperties.PROP.SO_BACKLOG) .childOption(ChannelOption.TCP_NODELAY, ServerProperties.PROP.TCP_NODELAY) .childOption(ChannelOption.SO_KEEPALIVE, ServerProperties.PROP.SO_KEEPALIVE) .childOption(ChannelOption.SO_REUSEADDR, ServerProperties.PROP.SO_REUSEADDR) .childHandler(new HttpChannelInitializer()); try {// ww w . j av a 2s . c om ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(ip, port)).sync(); if (future.isSuccess()) { LoggerManager.LOGGER.info("Http Server Started Successfully @ {}:{}", ip, port); } else { boss.shutdownGracefully(); worker.shutdownGracefully(); LoggerManager.LOGGER.fatal("Http Server Start Failed. Can not bind to {}:{}", ip, port); } } catch (Exception e) { LoggerManager.LOGGER.fatal("Exception Caught while starting Http Server", e); } }
From source file:com.spotify.ffwd.debug.NettyDebugServer.java
License:Apache License
public AsyncFuture<Void> start() { final ResolvableFuture<Void> future = async.future(); final ServerBootstrap s = new ServerBootstrap(); s.channel(NioServerSocketChannel.class); s.group(boss, worker);/* ww w . j ava 2s . co m*/ s.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { connected.add(ch); log.info("Connected {}", ch); ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connected.remove(ch); log.info("Disconnected {}", ch); } }); } }); s.bind(localAddress).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (!f.isSuccess()) { future.fail(f.cause()); return; } log.info("Bound to {}", localAddress); if (!server.compareAndSet(null, f.channel())) { f.channel().close(); future.fail(new IllegalStateException("server already started")); return; } future.resolve(null); } }); return future; }
From source file:com.spotify.ffwd.debug.NettyDebugServer.java
License:Apache License
public AsyncFuture<Void> stop() { final Channel server = this.server.getAndSet(null); if (server == null) { throw new IllegalStateException("server not started"); }//w w w .ja v a2 s. c om final ResolvableFuture<Void> serverClose = async.future(); server.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (!f.isSuccess()) { serverClose.fail(f.cause()); return; } serverClose.resolve(null); } }); final ResolvableFuture<Void> channelGroupClose = async.future(); connected.close().addListener(new ChannelGroupFutureListener() { @Override public void operationComplete(ChannelGroupFuture f) throws Exception { if (!f.isSuccess()) { channelGroupClose.fail(f.cause()); return; } channelGroupClose.resolve(null); } }); return async.collectAndDiscard(ImmutableList.<AsyncFuture<Void>>of(serverClose, channelGroupClose)); }
From source file:com.spotify.ffwd.protocol.RetryingProtocolConnection.java
License:Apache License
private void trySetup(final int attempt) { log.info("Attempt {}", action); final ChannelFuture connect = action.setup(); connect.addListener(new ChannelFutureListener() { @Override//from ww w.j ava 2 s .c o m public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { log.info("Successful {}", action); setChannel(future.channel()); return; } final long delay = policy.delay(attempt); log.warn("Failed {} (attempt: {}), retrying in {}s: {}", action, attempt + 1, TimeUnit.SECONDS.convert(delay, TimeUnit.MILLISECONDS), future.cause().getMessage()); timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (stopped.get()) { return; } trySetup(attempt + 1); } }, delay, TimeUnit.MILLISECONDS); } }); }
From source file:com.spotify.ffwd.protocol.RetryingProtocolConnection.java
License:Apache License
@Override public void send(Object message) { final Channel c = channel.get(); if (c == null) { return;/*from w w w .j a va2 s. c o m*/ } c.writeAndFlush(message).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.error("failed to send metric", future.cause()); } } }); }
From source file:com.spotify.folsom.client.DefaultRawMemcacheClient.java
License:Apache License
public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address, final int outstandingRequestLimit, final boolean binary, final Executor executor, final long timeoutMillis) { final ChannelInboundHandler decoder; if (binary) { decoder = new BinaryMemcacheDecoder(); } else {// w w w . j a va2 s .c om decoder = new AsciiMemcacheDecoder(); } final ChannelHandler initializer = new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ch.pipeline().addLast(new TcpTuningHandler(), decoder, // Downstream new MemcacheEncoder()); } }; final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create(); final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer) .channel(NioSocketChannel.class) .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE); final ChannelFuture connectFuture = bootstrap .connect(new InetSocketAddress(address.getHostText(), address.getPort())); connectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { // Create client final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(), outstandingRequestLimit, executor, timeoutMillis); clientFuture.set(client); } else { clientFuture.setException(future.cause()); } } }); return onExecutor(clientFuture, executor); }