List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:com.caricah.iotracah.server.netty.channelgroup.IotChannelGroupFuture.java
License:Apache License
IotChannelGroupFuture(ChannelGroup group, Map<Channel, ChannelFuture> futures, EventExecutor executor) { super(executor); this.group = group; this.futures = Collections.unmodifiableMap(futures); for (ChannelFuture f : this.futures.values()) { f.addListener(childListener); }// w w w . ja v a2s. c om // Done on arrival? if (this.futures.isEmpty()) { setSuccess0(); } }
From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// ww w .ja v a 2 s. c o m return; } if (request.method() == POST) { new VersionProtocolMessageHandler().handleMessage(ctx, request); return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (new URLServiceFilter(uri, ctx, request).doFilte()) { return; } if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || (!file.exists() && (file = downloadSoftWare(file)) == null)) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (!HttpStaticVersionMonitorFileServer.OPEN_ACCESS) { sendWarningInfo(ctx); return; } if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().getAndConvert(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); HttpHeaderUtil.setContentLength(response, fileLength); response.headers().set("file_flag", "yes"); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaderUtil.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaderValues.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.writeAndFlush(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 (!HttpHeaderUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.cdg.study.netty.time.TimeServerHandler.java
License:Open Source License
@Override public void channelActive(final ChannelHandlerContext ctx) { // (1) final ByteBuf time = ctx.alloc().buffer(4); // (2) time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)); final ChannelFuture f = ctx.writeAndFlush(time); // (3) f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { assert f == future; ctx.close();// www .j av a2s . co m } }); // (4) }
From source file:com.chen.opensourceframework.netty.copy.DiscardServerHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ChannelFuture f = ctx.writeAndFlush(new UnixTime()); f.addListener(ChannelFutureListener.CLOSE); }
From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { final Channel uaChannel = uaChannelCtx.channel(); final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); if (remoteChannel != null && remoteChannel.isActive()) { HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote); remoteChannel.writeAndFlush(request); } else {/*from w w w . j a va2 s . c om*/ Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this)); ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(), new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0)); remoteChannel = remoteConnectFuture.channel(); remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel); remoteConnectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote)); for (HttpContent hc : httpContentBuffer) { future.channel().writeAndFlush(hc); if (hc instanceof LastHttpContent) { future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } httpContentBuffer.clear(); } else { HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR); httpContentBuffer.clear(); future.channel().close(); } } }); } ReferenceCountUtil.release(msg); } else { Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); HttpContent hc = ((HttpContent) msg); if (remoteChannel != null && remoteChannel.isActive()) { remoteChannel.writeAndFlush(hc); if (hc instanceof LastHttpContent) { remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } else { httpContentBuffer.add(hc); } } }
From source file:com.chiorichan.http.HttpResponseWrapper.java
License:Mozilla Public License
public void finishMultipart() throws IOException { if (stage == HttpResponseStage.CLOSED) throw new IllegalStateException( "You can't access closeMultipart unless you start MULTIPART with sendMultipart."); stage = HttpResponseStage.CLOSED;/*w w w .j ava 2 s.co m*/ // Write the end marker ChannelFuture lastContentFuture = request.getChannel().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. // if ( !isKeepAlive( request ) ) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.chiorichan.http.HttpResponseWrapper.java
License:Mozilla Public License
public void sendMultipart(byte[] bytesToWrite) throws IOException { if (request.method() == HttpMethod.HEAD) throw new IllegalStateException("You can't start MULTIPART mode on a HEAD Request."); if (stage != HttpResponseStage.MULTIPART) { stage = HttpResponseStage.MULTIPART; HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders h = response.headers(); try {//from w w w . j a v a 2 s . com request.getSession().save(); } catch (SessionException e) { e.printStackTrace(); } for (HttpCookie c : request.getCookies()) if (c.needsUpdating()) h.add("Set-Cookie", c.toHeaderValue()); if (h.get("Server") == null) h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion()); h.add("Access-Control-Allow-Origin", request.getLocation().getConfig().getString("site.web-allowed-origin", "*")); h.add("Connection", "close"); h.add("Cache-Control", "no-cache"); h.add("Cache-Control", "private"); h.add("Pragma", "no-cache"); h.set("Content-Type", "multipart/x-mixed-replace; boundary=--cwsframe"); // if ( isKeepAlive( request ) ) { // response.headers().set( CONNECTION, HttpHeaders.Values.KEEP_ALIVE ); } request.getChannel().write(response); } else { StringBuilder sb = new StringBuilder(); sb.append("--cwsframe\r\n"); sb.append("Content-Type: " + httpContentType + "\r\n"); sb.append("Content-Length: " + bytesToWrite.length + "\r\n\r\n"); ByteArrayOutputStream ba = new ByteArrayOutputStream(); ba.write(sb.toString().getBytes(encoding)); ba.write(bytesToWrite); ba.flush(); ChannelFuture sendFuture = request.getChannel().write( new ChunkedStream(new ByteArrayInputStream(ba.toByteArray())), request.getChannel().newProgressivePromise()); ba.close(); sendFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { NetworkManager.getLogger().info("Transfer complete."); } @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) NetworkManager.getLogger().info("Transfer progress: " + progress); else NetworkManager.getLogger().info("Transfer progress: " + progress + " / " + total); } }); } }
From source file:com.chiorichan.net.query.QueryServerHandler.java
License:Mozilla Public License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { context = ctx;/* w w w . j av a 2 s . c o m*/ persistence = new NetworkPersistence(this); console = InteractiveConsole.createInstance(this, persistence); console.displayWelcomeMessage(); QueryEvent queryEvent = new QueryEvent(ctx, QueryType.CONNECTED, null); try { Loader.getEventBus().callEventWithException(queryEvent); } catch (EventException ex) { throw new IOException( "Exception encountered during query event call, most likely the fault of a plugin.", ex); } if (queryEvent.isCancelled()) { ChannelFuture future = ctx.write(parseColor((queryEvent.getReason().isEmpty()) ? "We're sorry, you've been disconnected from the server by a Cancelled Event." : queryEvent.getReason())); future.addListener(ChannelFutureListener.CLOSE); ctx.flush(); return; } console.resetPrompt(); }
From source file:com.chiorichan.net.query.QueryServerHandler.java
License:Mozilla Public License
public void disconnect(String msg) { ChannelFuture future = context.write(parseColor(msg)); future.addListener(ChannelFutureListener.CLOSE); }
From source file:com.chiorichan.net.query.QueryServerTerminal.java
License:Mozilla Public License
public boolean disconnect(String msg) { NetworkManager.getLogger().info(EnumColor.YELLOW + "The connection to Query Client `" + getIpAddr() + "` is being disconnected with message `" + msg + "`."); ChannelFuture future = context.writeAndFlush("\r" + parseColor(msg) + "\r\n"); future.addListener(ChannelFutureListener.CLOSE); return true;// ww w . j a v a2 s . co m }