List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:com.netty.fileTest.http.download.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w ww .j a va 2 s.c o m return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { final Channel inboundChannel = ctx.channel(); // ??//w w w . j a v a 2s. co m Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new GrpcProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); for (int i = 0; i < remoteHosts.length; i++) { final ChannelFuture f = b.connect(remoteHosts[i], remotePorts[i]); outboundChannels[i] = f.channel(); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); // System.out.println(f.channel().remoteAddress() + ", " + f.channel().localAddress()); } else { // Close the connection if the connection attempt has failed. // System.out.println("channelActive close" + inboundChannel.remoteAddress() + ", " + inboundChannel.localAddress()); inboundChannel.close(); } } }); } }
From source file:com.netty.telnet.impl.TelnetServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { // Generate and write a response. String response;// w w w . j ava 2 s. c o m boolean close = false; if (StringUtil.isNullOrEmpty(request)) { response = "Please type something.\r\n"; } else if ("bye".equals(request.toLowerCase())) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = ctx.write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.newlandframework.avatarmq.broker.SendMessageLauncher.java
License:Apache License
public Object launcher(Channel channel, ResponseMessage response) { if (channel != null) { CallBackInvoker<Object> invoke = new CallBackInvoker<Object>(); invokeMap.put(response.getMsgId(), invoke); invoke.setRequestId(response.getMsgId()); ChannelFuture channelFuture = channel.writeAndFlush(response); channelFuture.addListener(new LauncherListener(invoke)); try {/*from w ww . j ava 2s . c o m*/ Object result = invoke.getMessageResult(timeout, TimeUnit.MILLISECONDS); return result; } catch (RuntimeException e) { throw e; } finally { invokeMap.remove(response.getMsgId()); } } else { return null; } }
From source file:com.newlandframework.avatarmq.netty.MessageConnectFactory.java
License:Apache License
public void connect() { Preconditions.checkNotNull(messageHandler, "Message's Handler is Null!"); try {//from w w w. ja v a 2 s .co m init(); ChannelFuture channelFuture = bootstrap.connect(this.remoteAddr).sync(); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { Channel channel = future.channel(); messageChannel = channel; } }); System.out.println("ip address:" + this.remoteAddr.toString()); connected = true; } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java
License:Apache License
public void sendAsynMessage(RequestMessage request, final NotifyCallback listener) { Channel channel = factory.getMessageChannel(); if (channel == null) { return;//from w w w .j a va 2 s. com } Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap(); CallBackInvoker<Object> invoker = new CallBackInvoker<Object>(); callBackMap.put(request.getMsgId(), invoker); invoker.setRequestId(request.getMsgId()); invoker.join(new CallBackListener<Object>() { public void onCallBack(Object t) { ResponseMessage response = (ResponseMessage) t; listener.onEvent((ProducerAckMessage) response.getMsgParams()); } }); ChannelFuture channelFuture = channel.writeAndFlush(request); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { invoker.setReason(future.cause()); } } }); }
From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java
License:Apache License
public Object sendAsynMessage(RequestMessage request) { Channel channel = factory.getMessageChannel(); if (channel == null) { return null; }/* w ww. j ava2s . co m*/ Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap(); CallBackInvoker<Object> invoker = new CallBackInvoker<Object>(); callBackMap.put(request.getMsgId(), invoker); invoker.setRequestId(request.getMsgId()); ChannelFuture channelFuture = channel.writeAndFlush(request); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { invoker.setReason(future.cause()); } } }); try { Object result = invoker.getMessageResult(factory.getTimeOut(), TimeUnit.MILLISECONDS); callBackMap.remove(request.getMsgId()); return result; } catch (RuntimeException e) { e.printStackTrace(); return null; } }
From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java
License:Apache License
public void sendSyncMessage(RequestMessage request) { Channel channel = factory.getMessageChannel(); if (channel == null) { return;// w w w . j a va2 s .com } Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap(); CallBackInvoker<Object> invoker = new CallBackInvoker<Object>(); callBackMap.put(request.getMsgId(), invoker); invoker.setRequestId(request.getMsgId()); ChannelFuture channelFuture; try { channelFuture = channel.writeAndFlush(request).sync(); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { invoker.setReason(future.cause()); } } }); } catch (InterruptedException ex) { Logger.getLogger(MessageProcessor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.newlandframework.rpc.netty.MessageSendInitializeTask.java
License:Apache License
public Boolean call() { Bootstrap b = new Bootstrap(); b.group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true); b.handler(new MessageSendChannelInitializer().buildRpcSerializeProtocol(protocol)); ChannelFuture channelFuture = b.connect(serverAddress); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { MessageSendHandler handler = channelFuture.channel().pipeline().get(MessageSendHandler.class); RpcServerLoader.getInstance().setMessageSendHandler(handler); }/*from www . ja v a 2 s. co m*/ } }); return Boolean.TRUE; }
From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { logger.info("writeResponse ..."); // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);//from ww w.j ava 2s .c o m // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION)); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().set(CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { // cookies = CookieDecoder.decode(value); cookies = ServerCookieDecoder.STRICT.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { // response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); response.headers().add(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }