Java Code Examples for io.netty.handler.codec.http.HttpHeaders#isKeepAlive()

The following examples show how to use io.netty.handler.codec.http.HttpHeaders#isKeepAlive() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpHelloWorldServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@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));
        }
        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());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example 2
Source File: HelloServerHandler.java    From crow-benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
// Decide whether to close the connection or not.
boolean keepAlive = HttpHeaders.isKeepAlive(request);
// Build the response object.
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
HttpHeaders headers = response.headers();
headers.set(CONTENT_TYPE_ENTITY, contentType);
headers.set(SERVER_ENTITY, SERVER_NAME);
headers.set(DATE_ENTITY, date);
headers.set(CONTENT_LENGTH_ENTITY, contentLength);

// Close the non-keep-alive connection after the write operation is
// done.
if (!keepAlive) {
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
    ctx.write(response, ctx.voidPromise());
}
   }
 
Example 3
Source File: ApiRequestParser.java    From netty.book.kor with MIT License 6 votes vote down vote up
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(
                    apiResult.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");

    if (keepAlive) {
        // 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.KEEP_ALIVE);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
Example 4
Source File: WebSocketServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private static void sendHttpResponse(
        ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 5
Source File: WebSocketServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private static void sendHttpResponse(
        ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 6
Source File: NettyHttpFileHandler.java    From khs-stockticker with Apache License 2.0 6 votes vote down vote up
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
   if (res.getStatus().code() != 200) {
      ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
      res.content().clear();
      res.content().writeBytes(f);
      f.release();
   }

   HttpHeaders.setContentLength(res, res.content().readableBytes());
   ChannelFuture f1;
   f1 = ctx.channel().writeAndFlush(res);

   if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
 
Example 7
Source File: AbstractHandler.java    From jframe with Apache License 2.0 6 votes vote down vote up
protected void readHttpRequest(HttpRequest msg) throws Exception {
    HttpRequest req = (HttpRequest) msg;
    AbstractHandler.this.req = req;

    if (!req.getMethod().equals(HttpMethod.POST) || !isValidHeaders(req.headers())) {
        finish(ctx);
        return;
    }

    keepAlive = HttpHeaders.isKeepAlive(req);
    String encoding = req.headers().get(HttpHeaders.Names.ACCEPT_ENCODING);
    if (encoding != null && encoding.indexOf("gzip") != -1) {
        gzip = true;
    }
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.getUri());
    _params = queryStringDecoder.parameters();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Receive request -> {}", req.getUri());
    }
}
 
Example 8
Source File: WebSocketServerHandler.java    From withme3.0 with MIT License 6 votes vote down vote up
/**
 * 给客户端回复消息
 *
 * @param ctx
 * @param req
 * @param res
 */
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse res) {

    //返回应答给客户端
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
    }

    // 如果是非Keep-Alive,关闭连接
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 9
Source File: ServiceConnector.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 10
Source File: WebsocketSinkServerHandler.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
	// Generate an error page if response getStatus code is not OK (200).
	if (res.getStatus().code() != 200) {
		ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
		res.content().writeBytes(buf);
		buf.release();
		HttpHeaders.setContentLength(res, res.content().readableBytes());
	}

	// Send the response and close the connection if necessary.
	ChannelFuture f = ctx.channel().writeAndFlush(res);
	if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
		f.addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example 11
Source File: SimpleWampWebsocketListener.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private static void sendHttpResponse(
    ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }
    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 12
Source File: UploadHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   long startTime = System.nanoTime();

   HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
   try {
      String place = null;
      int num = 0;
      while(decoder.hasNext()) {
         num++;

         InterfaceHttpData httpData = decoder.next();
         if(httpData.getHttpDataType() == HttpDataType.Attribute && httpData.getName().equalsIgnoreCase("place")) {
            place = ((Attribute) httpData).getValue();
         } else if(httpData.getHttpDataType() == HttpDataType.FileUpload) {
            String camProtAddr = URLDecoder.decode(httpData.getName(), "UTF-8");
            Device d = findCamera(camProtAddr);
            if(d == null) {
               UPLOAD_UNKNOWN.inc();
               logger.warn("ignoring preview upload for non-existent camera {}", camProtAddr);
               continue;
            }
            write(place, d, (FileUpload) httpData);
         }
      }
      HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
      ChannelFuture future = ctx.writeAndFlush(response);
      if(!HttpHeaders.isKeepAlive(req)) {
         future.addListener(ChannelFutureListener.CLOSE);
      }

      UPLOAD_NUM.update(num);
      UPLOAD_SUCCESS.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } catch (Exception ex) {
      UPLOAD_FAIL.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } finally {
      decoder.cleanFiles();
   }
}
 
Example 13
Source File: HttpSnoopServerHandler.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, currentObj.getDecoderResult().isSuccess()? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // 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.KEEP_ALIVE);
    }

    // Encode the cookie.
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie: cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
Example 14
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Responds to the client with the specified "short-circuit" response. The response will be sent through the
 * {@link HttpFilters#proxyToClientResponse(HttpObject)} filter method before writing it to the client. The client
 * will not be disconnected, unless the response includes a "Connection: close" header, or the filter returns
 * a null HttpResponse (in which case no response will be written to the client and the connection will be
 * disconnected immediately). If the response is not a Bad Gateway or Gateway Timeout response, the response's headers
 * will be modified to reflect proxying, including adding a Via header, Date header, etc.
 *
 * @param httpResponse the response to return to the client
 * @return true if the connection will be kept open, or false if it will be disconnected.
 */
private boolean respondWithShortCircuitResponse(HttpResponse httpResponse) {
    // we are sending a response to the client, so we are done handling this request
    this.currentRequest = null;

    HttpResponse filteredResponse = (HttpResponse) currentFilters.proxyToClientResponse(httpResponse);
    if (filteredResponse == null) {
        disconnect();
        return false;
    }

    // allow short-circuit messages to close the connection. normally the Connection header would be stripped when modifying
    // the message for proxying, so save the keep-alive status before the modifications are made.
    boolean isKeepAlive = HttpHeaders.isKeepAlive(httpResponse);

    // if the response is not a Bad Gateway or Gateway Timeout, modify the headers "as if" the short-circuit response were proxied
    int statusCode = httpResponse.getStatus().code();
    if (statusCode != HttpResponseStatus.BAD_GATEWAY.code() && statusCode != HttpResponseStatus.GATEWAY_TIMEOUT.code()) {
        modifyResponseHeadersToReflectProxying(httpResponse);
    }

    // restore the keep alive status, if it was overwritten when modifying headers for proxying
    HttpHeaders.setKeepAlive(httpResponse, isKeepAlive);

    write(httpResponse);

    if (ProxyUtils.isLastChunk(httpResponse)) {
        writeEmptyBuffer();
    }

    if (!HttpHeaders.isKeepAlive(httpResponse)) {
        disconnect();
        return false;
    }

    return true;
}
 
Example 15
Source File: EchoServerHttpRequestHandler.java    From examples-javafx-repos1 with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
	
	if( wsURI.equalsIgnoreCase(request.getUri()) ) {
		
		ctx.fireChannelRead(request.retain());
	
	} else {
		
		if( HttpHeaders.is100ContinueExpected(request) ) {
			send100Continue(ctx);
		}
		
		try (
			RandomAccessFile rFile = new RandomAccessFile(indexHTML, "r")
		) {
			HttpResponse response = new DefaultHttpResponse( request.getProtocolVersion(), HttpResponseStatus.OK );
			response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
			boolean keepAlive = HttpHeaders.isKeepAlive(request);
			if( keepAlive ) {
				response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, rFile.length());
				response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
			}
			
			ctx.write(response);
			
			if( ctx.pipeline().get(SslHandler.class) == null ) {
				ctx.write(new DefaultFileRegion(rFile.getChannel(), 0, rFile.length()));
			} else {
				ctx.write(new ChunkedNioFile(rFile.getChannel()));
			}
			
			ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
			
			if( !keepAlive ) {
				future.addListener(ChannelFutureListener.CLOSE);
			}
		}
	}
}
 
Example 16
Source File: HttpSnoopServerHandler.java    From netty.book.kor with MIT License 5 votes vote down vote up
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, currentObj.decoderResult().isSuccess()? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // 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.KEEP_ALIVE);
    }

    // Encode the cookie.
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie: cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
Example 17
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the remote connection should be closed based on the request
 * and response pair. If the request is HTTP 1.0 with no keep-alive header,
 * for example, the connection should be closed.
 * 
 * This in part determines if we should close the connection. Here's the
 * relevant section of RFC 2616:
 * 
 * "HTTP/1.1 defines the "close" connection option for the sender to signal
 * that the connection will be closed after completion of the response. For
 * example,
 * 
 * Connection: close
 * 
 * in either the request or the response header fields indicates that the
 * connection SHOULD NOT be considered `persistent' (section 8.1) after the
 * current request/response is complete."
 * 
 * @param req
 *            The request.
 * @param res
 *            The response.
 * @param msg
 *            The message.
 * @return Returns true if the connection should close.
 */
private boolean shouldCloseServerConnection(HttpRequest req,
        HttpResponse res, HttpObject msg) {
    if (ProxyUtils.isChunked(res)) {
        // If the response is chunked, we want to return false unless it's
        // the last chunk. If it is the last chunk, then we want to pass
        // through to the same close semantics we'd otherwise use.
        if (msg != null) {
            if (!ProxyUtils.isLastChunk(msg)) {
                String uri = null;
                if (req != null) {
                    uri = req.getUri();
                }
                LOG.debug("Not closing server connection on middle chunk for {}", uri);
                return false;
            } else {
                LOG.debug("Handling last chunk. Using normal server connection closing rules.");
            }
        }
    }

    // ignore the request's keep-alive; we can keep this server connection open as long as the server allows it.

    if (!HttpHeaders.isKeepAlive(res)) {
        LOG.debug("Closing server connection since response is not keep alive: {}", res);
        // In this case, we want to honor the Connection: close header
        // from the remote server and close that connection. We don't
        // necessarily want to close the connection to the client, however
        // as it's possible it has other connections open.
        return true;
    }

    LOG.debug("Not closing server connection for response: {}", res);
    return false;
}
 
Example 18
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Determine whether or not the client connection should be closed.
 * 
 * @param req
 * @param res
 * @param httpObject
 * @return
 */
private boolean shouldCloseClientConnection(HttpRequest req,
        HttpResponse res, HttpObject httpObject) {
    if (ProxyUtils.isChunked(res)) {
        // If the response is chunked, we want to return false unless it's
        // the last chunk. If it is the last chunk, then we want to pass
        // through to the same close semantics we'd otherwise use.
        if (httpObject != null) {
            if (!ProxyUtils.isLastChunk(httpObject)) {
                String uri = null;
                if (req != null) {
                    uri = req.getUri();
                }
                LOG.debug("Not closing client connection on middle chunk for {}", uri);
                return false;
            } else {
                LOG.debug("Handling last chunk. Using normal client connection closing rules.");
            }
        }
    }

    if (!HttpHeaders.isKeepAlive(req)) {
        LOG.debug("Closing client connection since request is not keep alive: {}", req);
        // Here we simply want to close the connection because the
        // client itself has requested it be closed in the request.
        return true;
    }

    // ignore the response's keep-alive; we can keep this client connection open as long as the client allows it.

    LOG.debug("Not closing client connection for request: {}", req);
    return false;
}
 
Example 19
Source File: HttpClasspathServerHandler.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        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;
    }

    // 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;
        // we use the start time of the JVM as last modified date
        long lastModifiedSeconds = ManagementFactory.getRuntimeMXBean().getStartTime();
        if (ifModifiedSinceDateSeconds == lastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    ClassLoader classLoader = HttpClasspathServerHandler.class.getClassLoader();
    InputStream stream = classLoader.getResourceAsStream(path);

    if(stream == null) {
      sendError(ctx, NOT_FOUND);
      return;
    }

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, stream.available());
    setContentTypeHeader(response, path);
    setDateAndCacheHeaders(response);
    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 = ctx.write(new ChunkedStream(stream), ctx.newProgressivePromise());
        // Write the end marker.
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // 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);
    }
}
 
Example 20
Source File: SampleHandler.java    From xio with Apache License 2.0 4 votes vote down vote up
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
  // Decide whether to close the connection or not.
  boolean keepAlive = HttpHeaders.isKeepAlive(request);
  // Build the response object.
  FullHttpResponse response =
      new DefaultFullHttpResponse(
          HTTP_1_1,
          currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST,
          Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

  response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

  if (keepAlive) {
    // 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.KEEP_ALIVE);
  }

  // Encode the cookie.
  String cookieString = request.headers().get(COOKIE);
  if (cookieString != null) {
    Set<Cookie> cookies = CookieDecoder.decode(cookieString);
    if (!cookies.isEmpty()) {
      // Reset the cookies if necessary.
      for (Cookie cookie : cookies) {
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
      }
    }
  } else {
    // Browser sent no cookie.  Add some.
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
  }

  // Write the response.
  ctx.write(response);

  return keepAlive;
}