List of usage examples for io.netty.channel ChannelFutureListener CLOSE
ChannelFutureListener CLOSE
To view the source code for io.netty.channel ChannelFutureListener CLOSE.
Click Source Link
From source file:com.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { try {/*from www .j av a 2 s . c o m*/ if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { send100Continue(ctx); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); path = queryStringDecoder.path(); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); if (key.equalsIgnoreCase("db")) { dbName = p.getValue().get(0); } } } if (path != null && path.contains("query")) { Gson gson = new Gson(); JsonObject obj = new JsonObject(); JsonArray ary = new JsonArray(); ary.add(new JsonObject()); obj.add("results", ary); responseString.append(gson.toJson(obj)); } } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf byteBuf = httpContent.content(); if (byteBuf.isReadable()) { requestBuffer.append(byteBuf.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { // LastHttpContent lastHttpContent = (LastHttpContent) msg; // if (!lastHttpContent.trailingHeaders().isEmpty()) { // } if (dbName == null) { responseString.append("Invalid database null"); logger.severe("Invalid database null"); } else { String payload = requestBuffer.toString(); logger.fine("Request:" + payload); List<DataPoint> dps = dataPointsFromString(dbName, payload); for (DataPoint dp : dps) { try { engine.writeDataPoint(dp); logger.fine("Accepted:" + dp + "\t" + new Date(dp.getTimestamp())); } catch (IOException e) { logger.fine("Dropped:" + dp + "\t" + e.getMessage()); responseString.append("Dropped:" + dp); } } } if (writeResponse(request, ctx)) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
From source file:com.stremebase.examples.todomvc.HttpRouter.java
License:Apache License
private static ChannelFuture flushResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) { if (!HttpHeaders.isKeepAlive(req)) { return ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); } else {// ww w.j a v a 2s.com res.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); return ctx.writeAndFlush(res); } }
From source file:com.study.hc.net.netty.http.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else {//w w w.java2 s . co m response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } }
From source file:com.supermy.im.netty.handler.ImServerHandler.java
License:Apache License
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // ctxWriteAndFlush() ??? ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
From source file:com.tc.websocket.server.handler.RedirectionHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); HttpHeaders headers = req.headers(); IConfig cfg = Config.getInstance();// w w w . j a v a 2 s .c o m StringBuilder sb = new StringBuilder(); if (cfg.isEncrypted()) { sb.append(StringCache.HTTPS); } else { sb.append(StringCache.HTTP); } //finish up the url. sb.append(headers.get(HttpHeaderNames.HOST)).append(StringCache.COLON).append(cfg.getPort()) .append(req.uri()); //apply the redirect url response.headers().set(HttpHeaderNames.LOCATION, sb.toString()); // Close the connection as soon as the redirect is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.tc.websocket.server.handler.WebSocketValidationHandler.java
License:Apache License
/** * Send http response.//from ww w . ja v a 2s . c o m * * @param ctx the ctx * @param req the req * @param res the res */ private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.tesora.dve.parlb.MysqlClientHandler.java
License:Open Source License
/** * Closes the specified channel after all queued write requests are flushed. *///from w w w. j a v a 2 s. c o m static void closeOnFlush(Channel ch) { if (ch.isActive()) { ch.write(Unpooled.buffer()).addListener(ChannelFutureListener.CLOSE); } }
From source file:com.tongtech.tis.fsc.file.HttpStaticFileServerHandler.java
License:Apache License
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { URI requri = new URI(request.uri()); System.out.println("uri download: " + requri.getPath()); if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*w w w . j a va2 s . c om*/ return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); 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(HttpHeaderNames.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { logger.info("file is modified."); 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); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.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 (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.topsec.bdc.platform.api.server.http.HttpSnoopServerHandler.java
License:Apache License
/** * send back response and close the connection in server side. * //from w w w .j a v a 2s . c om * @param ctx * @param responseStatus * @param responseContent */ private void writeResponseAndClose(ChannelHandlerContext ctx, String message) { //response????? ByteBuf responseContentBuf = null; if (Assert.isEmptyString(message) == true) { responseContentBuf = Unpooled.copiedBuffer(_responseStatus.reasonPhrase(), CharsetUtil.UTF_8); } else { responseContentBuf = Unpooled.copiedBuffer(message, CharsetUtil.UTF_8); } // Decide whether to close the connection or not. // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, _responseStatus, responseContentBuf); //??? response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); //disallow keepAlive //boolean keepAlive = HttpHeaders.isKeepAlive(_request); //response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection //??? response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); // Encode the cookie. String cookieString = _request.headers().get(COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie)); } } } else { // Browser sent no cookie. Add some. //response.headers().add(SET_COOKIE, ServerCookieEncoder.LAX.encode("key1", "value1")); //response.headers().add(SET_COOKIE, ServerCookieEncoder.LAX.encode("key2", "value2")); } try { // Write the response. ctx.write(response); // close connection ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } catch (Throwable t) { t.printStackTrace(); ctx.close(); } }