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:io.aos.netty5.spdy.server.SpdyServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*from w ww. jav a 2 s.c o m*/ boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:io.aos.netty5.telnet.TelnetServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, String request) { // Generate and write a response. String response;//from w w w. jav a 2s.co m boolean close = false; if (request.isEmpty()) { 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:io.blobkeeper.server.handler.BaseFileHandler.java
License:Apache License
protected void writeResponse(Channel channel, String result, HttpRequest request) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(result, CharsetUtil.UTF_8); // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) || request.getProtocolVersion().equals(HTTP_1_0) && !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, "application/json; 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()); }//from ww w. j a va 2s . c o m // 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); } }
From source file:io.crate.mqtt.protocol.MqttProcessor.java
private ChannelFuture sendErrorResponse(Channel channel, MqttConnectReturnCode returnCode) { return channel.writeAndFlush(MqttMessageFactory.newConnAck(returnCode, false)) .addListener(ChannelFutureListener.CLOSE); }
From source file:io.crate.protocols.http.HttpAuthUpstreamHandler.java
@VisibleForTesting static void sendUnauthorized(Channel channel, @Nullable String body) { LOGGER.warn(body == null ? "unauthorized http chunk" : body); HttpResponse response;/*from w w w . j av a2s . co m*/ if (body != null) { if (!body.endsWith("\n")) { body += "\n"; } response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED, copiedBuffer(body, StandardCharsets.UTF_8)); HttpUtil.setContentLength(response, body.length()); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); } // "Tell" the browser to open the credentials popup // It helps to avoid custom login page in AdminUI response.headers().set(HttpHeaderNames.WWW_AUTHENTICATE, WWW_AUTHENTICATE_REALM_MESSAGE); channel.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:io.crate.protocols.http.HttpBlobHandler.java
License:Apache License
private void sendResponse(HttpResponse response) { ChannelFuture cf = ctx.channel().writeAndFlush(response); if (currentMessage != null && !HttpUtil.isKeepAlive(currentMessage)) { cf.addListener(ChannelFutureListener.CLOSE); }/*from w w w .j a va 2s. c o m*/ }
From source file:io.crate.protocols.http.HttpBlobHandler.java
License:Apache License
private void partialContentResponse(String range, HttpRequest request, String index, final String digest) throws IOException { assert range != null : "Getting partial response but no byte-range is not present."; Matcher matcher = CONTENT_RANGE_PATTERN.matcher(range); if (!matcher.matches()) { LOGGER.warn("Invalid byte-range: {}; returning full content", range); fullContentResponse(request, index, digest); return;//from w ww . j a v a 2 s. c o m } BlobShard blobShard = localBlobShard(index, digest); final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest); long start; long end; try { try { start = Long.parseLong(matcher.group(1)); if (start > raf.length()) { LOGGER.warn("416 Requested Range not satisfiable"); simpleResponse(HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE); raf.close(); return; } end = raf.length() - 1; if (!matcher.group(2).equals("")) { end = Long.parseLong(matcher.group(2)); } } catch (NumberFormatException ex) { LOGGER.error("Couldn't parse Range Header", ex); start = 0; end = raf.length(); } DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, PARTIAL_CONTENT); maybeSetConnectionCloseHeader(response); HttpUtil.setContentLength(response, end - start + 1); response.headers().set(HttpHeaderNames.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + raf.length()); setDefaultGetHeaders(response); ctx.channel().write(response); ChannelFuture writeFuture = transferFile(digest, raf, start, end - start + 1); if (!HttpUtil.isKeepAlive(request)) { writeFuture.addListener(ChannelFutureListener.CLOSE); } } catch (Throwable t) { /* * Make sure RandomAccessFile is closed when exception is raised. * In case of success, the ChannelFutureListener in "transferFile" will take care * that the resources are released. */ raf.close(); throw t; } }
From source file:io.crate.protocols.http.HttpBlobHandler.java
License:Apache License
private void fullContentResponse(HttpRequest request, String index, final String digest) throws IOException { BlobShard blobShard = localBlobShard(index, digest); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest); try {// ww w .j a va 2 s . c o m HttpUtil.setContentLength(response, raf.length()); setDefaultGetHeaders(response); LOGGER.trace("HttpResponse: {}", response); Channel channel = ctx.channel(); channel.write(response); ChannelFuture writeFuture = transferFile(digest, raf, 0, raf.length()); if (!HttpUtil.isKeepAlive(request)) { writeFuture.addListener(ChannelFutureListener.CLOSE); } } catch (Throwable t) { /* * Make sure RandomAccessFile is closed when exception is raised. * In case of success, the ChannelFutureListener in "transferFile" will take care * that the resources are released. */ raf.close(); throw t; } }
From source file:io.enforcer.deathstar.ws.WebSocketServerHandler.java
License:Apache License
/** * Sends http response to clients/*from www . j a v a2 s.c om*/ * * @param ctx handler context * @param req http request * @param res http response */ 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(); HttpHeaderUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.hekate.network.netty.NettyServerClient.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (isHandshakeDone()) { if (msg instanceof Heartbeat) { if (trace) { log.trace("Received network heartbeat from client [from={}]", address()); }//from ww w .j av a 2 s .co m } else { NettyMessage netMsg = (NettyMessage) msg; netMsg.prepare(log); if (trace) { log.trace("Message buffer prepared [from={}, message={}]", address(), netMsg); } if (metrics != null) { metrics.onMessageReceived(); } try { serverHandler.onMessage(netMsg, this); } finally { netMsg.release(); } } } else { if (trace) { log.trace("Received network handshake request [from={}, message={}]", address(), msg); } HandshakeRequest handshake = (HandshakeRequest) msg; String protocol; NettyServerHandler handlerReg; if (handshake == null) { protocol = null; handlerReg = null; } else { this.protocol = protocol = handshake.protocol(); handlerReg = handlers.get(protocol); } if (handlerReg == null) { if (debug) { log.debug("Closing connection with unsupported protocol [from={}, protocol={}]", address(), protocol); } HandshakeReject reject = new HandshakeReject("Unsupported protocol [protocol=" + protocol + ']'); ctx.writeAndFlush(reject).addListener(ChannelFutureListener.CLOSE); } else { // Map connection to a thread. EventLoop eventLoop = mapToThread(handshake.threadAffinity(), handlerReg); // Check if we need to re-bind this channel to another thread. if (eventLoop.inEventLoop()) { // No need to rebind. init(ctx.channel(), handshake, handlerReg); } else { if (trace) { log.trace("Registering channel to a custom NIO thread [from={}, protocol={}]", address(), protocol); } // Unregister and then re-register IdleStateHandler in order to prevent RejectedExecutionException if same // instance is used on different threads. ctx.pipeline().remove(IdleStateHandler.class.getName()); Channel channel = ctx.channel(); channel.deregister().addListener(deregister -> { if (deregister.isSuccess()) { if (!eventLoop.isShutdown() && channel.isOpen()) { eventLoop.register(channel).addListener(register -> { if (register.isSuccess() && channel.isOpen()) { if (trace) { log.trace( "Registered channel to a custom NIO thread [from={}, protocol={}]", address(), protocol); } mayBeCreateIdleStateHandler().ifPresent(handler -> ctx.pipeline() .addFirst(IdleStateHandler.class.getName(), handler)); init(channel, handshake, handlerReg); } }); } } }); } } } }