List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:com.tc.websocket.server.handler.ProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { ByteBuf buf = (ByteBuf) msg;/*ww w.j av a2 s . com*/ String data = new String(ByteBufUtil.getBytes(buf)); if (data.contains(Const.UPGRADE_WEBSOCKET) || data.contains(Const.GET_WEBSOCKET)) { proxy.set(false); } else if (data.contains(StringCache.HTTP_1_1)) { proxy.set(true); } if (proxy.get() == false) { writeToFile("frontend." + ctx.channel().id(), ByteBufUtil.getBytes(buf)); } if (Config.getInstance().isCertAuth()) { SslHandler sslhandler = (SslHandler) ctx.channel().pipeline().get("ssl"); try { X509Certificate cert = sslhandler.engine().getSession().getPeerCertificateChain()[0]; Principal p = cert.getSubjectDN(); /* Added by Miguel */ LdapName ldapDN = new LdapName(p.getName()); String username = ""; String thumbprint = getThumbPrint(cert.getEncoded()); for (Rdn rdn : ldapDN.getRdns()) { //System.out.println(rdn.getType() + " -> " + rdn.getValue()); if (rdn.getType().equals("CN")) { username = rdn.getValue().toString(); break; } } /* End Added by Miguel*/ String sessionId = parseSessionID(data); if (sessionId != null) { String current = System.getProperty("user.dir"); //System.out.println("Current working directory in Java : " + current); //File sessionFile = new File("c:/sessions/" + sessionId + ".txt"); File sessionFile = new File(current + "/data/sessions/" + sessionId + ".txt"); //only write the file if it hasn't been written yet. if (sessionFile.createNewFile()) { FileUtils.write(sessionFile, p.getName().replaceAll("\"", "").replaceAll("\\+", ",") + "\n" + username + "\n" + thumbprint); } } } catch (Exception e) { LOG.log(Level.SEVERE, null, e); } } if (proxy.get()) { ctx.channel().config().setAutoRead(false); if (outboundChannel.isActive()) { outboundChannel.writeAndFlush(buf).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } } else { //make sure the backend handler knows its a websocket connection. this.handler.setWebsocket(true); //get handle on the pipeline. ChannelPipeline pipeline = ctx.pipeline(); //apply the websocket handlers builder.apply(pipeline); //remove this handler. pipeline.remove(this); //fire the event to move on to the next handler. ctx.fireChannelRead(msg); } }
From source file:com.tesora.dve.parlb.MysqlClientHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .handler(new LoadBalancerServerHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(peServerAddress); outboundChannel = f.channel();//from w ww . j a v a2s .c o m f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { 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.test.AbstractBootstrap.java
License:Apache License
private ChannelFuture doBind(final SocketAddress localAddress) { final ChannelFuture regFuture = initAndRegister(); final Channel channel = regFuture.channel(); if (regFuture.cause() != null) { return regFuture; }//from ww w . j a v a2 s . c o m if (regFuture.isDone()) { // At this point we know that the registration was complete and successful. ChannelPromise promise = channel.newPromise(); doBind0(regFuture, channel, localAddress, promise); return promise; } else { // Registration future is almost always fulfilled already, but just in case it's not. final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel); regFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause != null) { // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an // IllegalStateException once we try to access the EventLoop of the Channel. promise.setFailure(cause); } else { // Registration was successful, so set the correct executor to use. // See https://github.com/netty/netty/issues/2586 promise.executor = channel.eventLoop(); } doBind0(regFuture, channel, localAddress, promise); } }); return promise; } }
From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java
License:Apache License
public RpcCommand invokeSyncImpl(final Channel channel, final RpcCommand request, final long timeoutMillis) throws InterruptedException, RpcTooMuchRequestException, RpcSendRequestException, RpcTimeoutException { //check channel writable if (!channel.isWritable()) { throw new RpcTooMuchRequestException( String.format("Invoke request too much, the channel[%s] is not writable", channel.toString())); }/*from w ww . j a v a 2s .co m*/ final int opaque = request.getOpaque(); try { final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null); this.responseTable.put(opaque, responseFuture); final SocketAddress addr = channel.remoteAddress(); channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { responseFuture.setSendRequestOK(true); return; } else { responseFuture.setSendRequestOK(false); } responseTable.remove(opaque); responseFuture.setCause(f.cause()); responseFuture.putResponse(null); LOGGER.warn("send a request command to channel <" + addr + "> failed."); } }); RpcCommand responseCommand = responseFuture.waitResponse(timeoutMillis); if (null == responseCommand) { if (responseFuture.isSendRequestOK()) { throw new RpcTimeoutException(RpcHelper.parseSocketAddressAddr(addr), timeoutMillis, responseFuture.getCause()); } else { throw new RpcSendRequestException(RpcHelper.parseSocketAddressAddr(addr), responseFuture.getCause()); } } return responseCommand; } finally { this.responseTable.remove(opaque); } }
From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java
License:Apache License
public void invokeAsyncImpl(final Channel channel, final RpcCommand request, final long timeoutMillis, final InvokeCallback invokeCallback) throws InterruptedException, RpcTooMuchRequestException, RpcTimeoutException, RpcSendRequestException { //check channel writable if (!channel.isWritable()) { throw new RpcTooMuchRequestException( String.format("Invoke request too much, the channel[%s] is not writable", channel.toString())); }//from w w w . j a v a2s . c om final int opaque = request.getOpaque(); boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS); if (acquired) { final OnceSemaphore once = new OnceSemaphore(this.semaphoreAsync); final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, invokeCallback, once); this.responseTable.put(opaque, responseFuture); try { channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { responseFuture.setSendRequestOK(true); return; } else { responseFuture.setSendRequestOK(false); } responseFuture.putResponse(null); responseTable.remove(opaque); try { responseFuture.executeInvokeCallback(); } catch (Throwable e) { LOGGER.warn("execute callback in writeAndFlush addListener, and callback throw", e); } finally { responseFuture.release(); } LOGGER.warn("send a request command to channel <{}> failed.", RpcHelper.parseChannelRemoteAddr(channel)); } }); } catch (Exception e) { responseFuture.release(); LOGGER.warn("send a request command to channel <" + RpcHelper.parseChannelRemoteAddr(channel) + "> Exception", e); throw new RpcSendRequestException(RpcHelper.parseChannelRemoteAddr(channel), e); } } else { if (timeoutMillis <= 0) { throw new RpcTooMuchRequestException("invokeAsyncImpl invoke too fast"); } else { String info = String.format( "invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", // timeoutMillis, // this.semaphoreAsync.getQueueLength(), // this.semaphoreAsync.availablePermits()// ); LOGGER.warn(info); throw new RpcTimeoutException(info); } } }
From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java
License:Apache License
public void invokeOneWayImpl(final Channel channel, final RpcCommand request, final long timeoutMillis) throws InterruptedException, RpcTooMuchRequestException, RpcTimeoutException, RpcSendRequestException { //check channel writable if (!channel.isWritable()) { throw new RpcTooMuchRequestException( String.format("Invoke request too much, the channel[%s] is not writable", channel.toString())); }/* w ww. ja v a 2 s .c o m*/ request.setOneWayRpc(true); boolean acquired = this.semaphoreOneWay.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS); if (acquired) { final OnceSemaphore once = new OnceSemaphore(this.semaphoreOneWay); try { channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { once.release(); if (!f.isSuccess()) { LOGGER.warn( "send a request command to channel <" + channel.remoteAddress() + "> failed."); } } }); } catch (Exception e) { once.release(); LOGGER.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed."); throw new RpcSendRequestException(RpcHelper.parseChannelRemoteAddr(channel), e); } } else { if (timeoutMillis <= 0) { throw new RpcTooMuchRequestException("invokeOneWayImpl invoke too fast"); } else { String info = String.format( "invokeOneWayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", // timeoutMillis, // this.semaphoreAsync.getQueueLength(), // this.semaphoreAsync.availablePermits()// ); LOGGER.warn(info); throw new RpcTimeoutException(info); } } }
From source file:com.turn.ttorrent.client.io.PeerClient.java
License:Apache License
@Nonnull public ChannelFuture connect(@Nonnull final PeerConnectionListener listener, @Nonnull final byte[] infoHash, @Nonnull final SocketAddress remoteAddress) { final ChannelFuture future; synchronized (lock) { // connect -> initAndRegister grabs this, so we can safely synchronize here. bootstrap.handler(new PeerClientHandshakeHandler(listener, infoHash, listener.getLocalPeerId())); future = bootstrap.connect(remoteAddress); }/*from www .ja v a2 s. c om*/ future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { LOG.trace("Succeeded: {}", future.get()); } catch (Exception e) { // LOG.error("Connection to " + remoteAddress + " failed.", e); listener.handlePeerConnectionFailed(remoteAddress, e); Channel channel = future.channel(); if (channel.isOpen()) channel.close(); // .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } } }); return future; }
From source file:com.twitter.http2.HttpStreamEncoder.java
License:Apache License
private ChannelPromise getMessageFuture(final ChannelHandlerContext ctx, final ChannelPromise promise, final int streamId, HttpMessage message) { if (message instanceof StreamedHttpMessage && !((StreamedHttpMessage) message).getContent().isClosed()) { final Pipe<HttpContent> pipe = ((StreamedHttpMessage) message).getContent(); ChannelPromise writeFuture = ctx.channel().newPromise(); writeFuture.addListener(new ChannelFutureListener() { @Override// w ww. jav a 2s. c o m public void operationComplete(ChannelFuture future) throws Exception { // Channel's thread // First frame has been written if (future.isSuccess()) { pipe.receive().addListener(new ChunkListener(ctx, streamId, pipe, promise)); } else if (future.isCancelled()) { pipe.close(); promise.cancel(true); } else { pipe.close(); promise.setFailure(future.cause()); } } }); return writeFuture; } else { return promise; } }
From source file:com.twocater.diamond.core.test.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*from w w w . ja v a2 s . co m*/ boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); keepAlive = false; if (!keepAlive) { ctx.write(response).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { channelFuture.channel().close(); System.out.println("asdfsadasdfsdfsadfsadfsdfsdfdfasdfasdfasdfasdfasf"); } }); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:com.uber.tchannel.channels.Peer.java
License:Open Source License
public Connection connect(Bootstrap bootstrap, Connection.Direction preferredDirection) { Connection conn = getConnection(ConnectionState.IDENTIFIED, preferredDirection); if (conn != null && (conn.satisfy(preferredDirection) || preferredDirection == Connection.Direction.IN)) { return conn; }/*from w ww .j a v a 2 s . co m*/ final ChannelFuture f = bootstrap.connect(remoteAddress); Channel channel = f.channel(); final Connection connection = add(channel, Connection.Direction.OUT); // handle connection errors f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { connection.setIndentified(new TChannelConnectionFailure(future.cause())); } } }); return connection; }