private void writeResponse(Channel channel, HttpRequest request, String message, String client) {
    String contentType = "text/plain";
    if (client != null && (client.equals("web") || client.equals("bluej"))) {
      // convert to HTML
      message = message.replaceAll("\n", "<br>\n");
      contentType = "text/html";
    }
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(message, CharsetUtil.UTF_8);

    // 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(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(CONTENT_TYPE, contentType + "; 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());
    }

    // 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);
    }
  }
  /**
   * Flush the response contents to the output channel
   *
   * @param channel Channel to be used
   */
  private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);

    // 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(HttpVersion.HTTP_1_1, HttpResponseStatus.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());
    }

    try {
      // 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);
      }
    } catch (Exception e) {
      logger.error("{}", e);
    }
  }
Esempio n. 3
0
  public void sendError() {
    if (request == null
        || status == null
        || shortDescription == null
        || detailedDescription == null
        || version == null
        || status == null) throw new IllegalStateException();

    StringBuffer sb = new StringBuffer();
    sb.append("Error ").append(status.code()).append(": ").append(shortDescription);
    sb.append("\n\n");
    sb.append(detailedDescription);
    sb.append("\n\n");
    sb.append("Request:\n").append(request.getUri());
    sb.append("\n\n");
    sb.append("Request Submitted:\n").append(FdsnwsDate.toString(new Date()));
    sb.append("\n\n");
    sb.append("Service version:\n").append(version);
    String html = sb.toString();

    FullHttpResponse response =
        new DefaultFullHttpResponse(
            request.getProtocolVersion(),
            status,
            Unpooled.copiedBuffer(html, Charset.forName("UTF-8")));
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, html.length());
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (HttpHeaders.isKeepAlive(request)) {
      response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.writeAndFlush(response);
  }
 @Override
 protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
   Integer streamId =
       msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
   if (streamId == null) {
     logger.error("HttpResponseHandler unexpected message received: " + msg);
     return;
   }
   onResponseReceived(ctx, streamIdUrlMap.get(streamId));
   Map.Entry<ChannelFuture, ChannelPromise> entry = streamIdPromiseMap.get(streamId);
   if (entry == null) {
     logger.error("Message received for unknown stream id " + streamId);
   } else {
     // Do stuff with the message (for now just print it)
     ByteBuf content = msg.content();
     ContentType contentType = ContentType.parse(msg.headers().get(HttpHeaderNames.CONTENT_TYPE));
     if (content.isReadable()) {
       int contentLength = content.readableBytes();
       byte[] arr = new byte[contentLength];
       content.readBytes(arr);
       handleContent(arr, ctx, contentType);
     }
     entry.getValue().setSuccess();
   }
 }
 @Override
 public FullHttpResponse handleRequest(ChannelHandlerContext ctx, HttpRequest request)
     throws Exception {
   URL url = Resources.getResource("org/glowroot/ui/app-dist/index.html");
   String indexHtml = Resources.toString(url, Charsets.UTF_8);
   String layout;
   if (httpSessionManager.hasReadAccess(request)) {
     layout = layoutJsonService.getLayout();
   } else {
     layout = layoutJsonService.getNeedsAuthenticationLayout();
   }
   String authenticatedUser = httpSessionManager.getAuthenticatedUser(request);
   String layoutScript =
       "var layout="
           + layout
           + ";var authenticatedUser = '******'";
   indexHtml =
       indexHtml.replaceFirst(
           "<base href=\"/\">",
           "<base href=\"" + BASE_HREF + "\"><script>" + layoutScript + "</script>");
   // this is to work around an issue with IE10-11 (IE9 is OK)
   // (even without reverse proxy/non-root base href)
   // IE doesn't use the base href when loading the favicon
   indexHtml =
       indexHtml.replaceFirst(
           "<link rel=\"shortcut icon\" href=\"favicon\\.([0-9a-f]+)\\.ico\">",
           "<script>document.write('<link rel=\"shortcut icon\" href=\"'"
               + " + document.getElementsByTagName(\"base\")[0].href"
               + " + 'favicon.$1.ico\">');</script>");
   if (GOOGLE_ANALYTICS_TRACKING_ID != null) {
     // this is for demo.glowroot.org
     indexHtml =
         indexHtml.replaceFirst(
             "<div class=\"navbar-brand\">(\\s*)Glowroot(\\s*)</div>",
             "<a href=\"https://glowroot.org\" class=\"navbar-brand\">$1Glowroot$2</a>");
     indexHtml =
         indexHtml.replaceFirst(
             "</body>",
             "<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]"
                 + "||function(){(i[r].q=i[r].q||[]).push(arguments)},"
                 + "i[r].l=1*new Date();a=s.createElement(o),"
                 + "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;"
                 + "m.parentNode.insertBefore(a,m)})(window,document,'script',"
                 + "'//www.google-analytics.com/analytics.js','ga');ga('create', '"
                 + GOOGLE_ANALYTICS_TRACKING_ID
                 + "', 'auto');</script>\n</body>");
   }
   ByteBuf content = Unpooled.copiedBuffer(indexHtml, Charsets.ISO_8859_1);
   FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
   HttpServices.preventCaching(response);
   response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
   response.headers().set(HttpHeaderNames.CONTENT_LENGTH, indexHtml.length());
   // X-UA-Compatible must be set via header (as opposed to via meta tag)
   // see https://github.com/h5bp/html5-boilerplate/blob/master/doc/html.md#x-ua-compatible
   response.headers().set("X-UA-Compatible", "IE=edge");
   return response;
 }
Esempio n. 6
0
 protected void setContent(FullHttpResponse response, int messageId) {
   response
       .headers()
       .set(
           HttpHeaders.Names.CONTENT_TYPE,
           "text/plain; charset=UTF-8; " + "MessageId".toLowerCase() + "=" + messageId);
   response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
   if (isKeepAlive) {
     response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
   }
 }
Esempio n. 7
0
  private static void writeHttpResponse(
      ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res, Boolean close) {
    if (!omitDateHeader && !res.headers().contains(DefaultHttpHeaders.Names.DATE))
      DefaultHttpHeaders.addDateHeader(res, DefaultHttpHeaders.Names.DATE, new Date());

    // Send the response and close the connection if necessary.
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200 || close == null || close) {
      res.headers().set(CONNECTION, HttpHeaders.Values.CLOSE);
      ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
    } else {
      res.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
      write(ctx, res);
    }
  }
Esempio n. 8
0
  @Override
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
      throws Exception {
    logger.info("StringEncoder response to client.");
    String serverMsg = (String) msg;

    FullHttpResponse response =
        new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(serverMsg.getBytes()));
    response.headers().set(CONTENT_TYPE, "text/plain");
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(CONNECTION, Values.KEEP_ALIVE);
    ctx.write(response);
    ctx.flush();
  }
Esempio n. 9
0
 public static void sendError(
     ChannelHandlerContext ctx, int statusCode, Map<String, String> rspHeaders) {
   HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
   logger.warn("send status {}", ctx.channel(), statusCode);
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HTTP_1_1, status, Unpooled.copiedBuffer(status + "\r\n", CharsetUtil.UTF_8));
   rspHeaders.forEach(
       (k, v) -> {
         response.headers().set(k, v);
       });
   response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
 }
  @Override
  protected HttpResponse createResponseObject() {
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    FullHttpResponse response =
        new DefaultFullHttpResponse(
            HTTP_1_1, OK, Unpooled.copiedBuffer(MESSAGE, CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    if (keepAlive) {
      response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
      response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    return response;
  }
  private void sendServerError(final ChannelHandlerContext ctx, final ServerException cause)
      throws Exception {

    if (ctx.channel().isActive()) {

      final ByteBuf content = Unpooled.buffer();

      content.writeBytes(
          (cause.getStatus().code()
                  + " "
                  + cause.getStatus().reasonPhrase()
                  + " - "
                  + cause.getMessage())
              .getBytes());

      final FullHttpResponse response =
          new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, cause.getStatus());

      response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());

      response.content().writeBytes(content);

      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
  }
 private static void sendListing(ChannelHandlerContext ctx, File dir) {
   FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
   response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
   StringBuilder buf = new StringBuilder();
   String dirPath = dir.getPath();
   buf.append("<!DOCTYPE html>\r\n");
   buf.append("<html><head><title>");
   buf.append(dirPath);
   buf.append(" 目录:");
   buf.append("</title></head><body>\r\n");
   buf.append("<h3>");
   buf.append(dirPath).append(" 目录:");
   buf.append("</h3>\r\n");
   buf.append("<ul>");
   buf.append("<li>链接:<a href=\"../\">..</a></li>\r\n");
   for (File f : dir.listFiles()) {
     if (f.isHidden() || !f.canRead()) {
       continue;
     }
     String name = f.getName();
     if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
       continue;
     }
     buf.append("<li>链接:<a href=\"");
     buf.append(name);
     buf.append("\">");
     buf.append(name);
     buf.append("</a></li>\r\n");
   }
   buf.append("</ul></body></html>\r\n");
   ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
   response.content().writeBytes(buffer);
   buffer.release();
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
 }
  /**
   * Sets the Date header for the HTTP response
   *
   * @param response HTTP response
   */
  private static void setDateHeader(FullHttpResponse response) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));
  }
  private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
    response.headers().set(LOCATION, newUri);

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  }
Esempio n. 15
0
  @Override
  public FullHttpResponse getResponse() throws InterruptedException {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);

    response.headers().set(LOCATION, urlRedirect).set(CONTENT_TYPE, "text/html; charset=UTF-8");
    return response;
  }
 @Test
 public void iframeHtml() throws Exception {
   final SockJsConfig config = config();
   final String path = config.prefix() + "/iframe.html";
   final FullHttpResponse response = Iframe.response(config, createHttpRequest(path));
   assertThat(response.getStatus().code(), is(HttpResponseStatus.OK.code()));
   assertThat(
       response.headers().get(HttpHeaders.Names.CONTENT_TYPE),
       equalTo("text/html; charset=UTF-8"));
   assertThat(
       response.headers().get(HttpHeaders.Names.CACHE_CONTROL),
       equalTo("max-age=31536000, public"));
   assertThat(response.headers().get(HttpHeaders.Names.EXPIRES), is(notNullValue()));
   assertThat(response.headers().get(HttpHeaders.Names.SET_COOKIE), is(nullValue()));
   assertThat(response.headers().get(HttpHeaders.Names.ETAG), is(notNullValue()));
 }
Esempio n. 17
0
 protected void setCookie(FullHttpResponse response) {
   //		Set<Cookie> cookies = CookieDecoder.decode(MessageFormat.format(COOKIE, sessionId));
   Set<Cookie> cookies = CookieDecoder.decode(sessionId);
   HttpHeaders headers = response.headers();
   for (Cookie cookie : cookies) {
     headers.add(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.encode(cookie));
   }
 }
Esempio n. 18
0
 @Override
 public FullHttpResponse handle(
     HttpRequest httpRequest, Map<String, List<String>> params, ByteBuf byteBuf) {
   FullHttpResponse httpResponse =
       new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, defaultStatus);
   httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
   return httpResponse;
 }
Esempio n. 19
0
  private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);

    // Decide whether to close the connection or not.
    boolean close =
        request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true)
            || request.protocolVersion().equals(HttpVersion.HTTP_1_0)
                && !request
                    .headers()
                    .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true);

    // Build the response object.
    FullHttpResponse response =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(HttpHeaderNames.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().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().getAndConvert(HttpHeaderNames.COOKIE);
    if (value == null) {
      cookies = Collections.emptySet();
    } else {
      cookies = ServerCookieDecoder.STRICT.decode(value);
    }
    if (!cookies.isEmpty()) {
      // Reset the cookies if necessary.
      for (Cookie cookie : cookies) {
        response
            .headers()
            .add(HttpHeaderNames.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);
    }
  }
Esempio n. 20
0
  @Override
  public void writeToResponse(SessionContext context) {
    FullHttpResponse response = context.getResponse();
    if (detector.hasHeader(response, name)) {
      response.headers().remove(name);
    }

    HttpHeaders.addHeader(response, name, new String(resource.readFor(context.getRequest())));
  }
 private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HTTP_1_1,
           status,
           Unpooled.copiedBuffer("失败: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
   response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
 }
  private static void respond(
      ServiceInvocationContext ctx,
      Promise<Object> promise,
      HttpResponseStatus status,
      long lastModifiedMillis,
      String contentType,
      ByteBuf content) {

    final FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
    if (lastModifiedMillis != 0) {
      res.headers().set(HttpHeaderNames.LAST_MODIFIED, new Date(lastModifiedMillis));
    }

    if (contentType != null) {
      res.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
    }

    ctx.resolvePromise(promise, res);
  }
Esempio n. 23
0
  @Override
  public void failover(FullHttpRequest request, FullHttpResponse response) {
    Response dumpedResponse = failoverResponse(request);
    response.setProtocolVersion(HttpVersion.valueOf(dumpedResponse.getVersion()));
    response.setStatus(HttpResponseStatus.valueOf(dumpedResponse.getStatusCode()));
    for (Map.Entry<String, String> entry : dumpedResponse.getHeaders().entrySet()) {
      response.headers().add(entry.getKey(), entry.getValue());
    }

    response.content().writeBytes(dumpedResponse.getContent().getBytes());
  }
 @Test
 public void ifNoneMatchHeader() throws Exception {
   final SockJsConfig config = config();
   final String path = config.prefix() + "/iframe.html";
   final HttpRequest httpRequest = createHttpRequest(path);
   httpRequest.headers().set(HttpHeaders.Names.IF_NONE_MATCH, "*");
   final FullHttpResponse response = Iframe.response(config, httpRequest);
   assertThat(
       response.headers().get(HttpHeaders.Names.SET_COOKIE), equalTo("JSESSIONID=dummy; path=/"));
   assertThat(response.getStatus().code(), is(HttpResponseStatus.NOT_MODIFIED.code()));
 }
Esempio n. 25
0
  private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response =
        new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderConstants.CONTENT_TYPE, "text/plain; charset=UTF-8");

    // Close the connection as soon as the error message is sent.
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
  }
Esempio n. 26
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    if (is100ContinueExpected(req)) {
      ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES);

    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.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
      response.headers().set(CONNECTION, Values.KEEP_ALIVE);
      ctx.writeAndFlush(response);
    }
  }
  public void sendError(
      ChannelHandlerContext ctx, HttpResponseStatus status, FullHttpRequest request) {
    FullHttpResponse response =
        new DefaultFullHttpResponse(
            HTTP_1_1,
            status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  }
 @SuppressWarnings("argument.type.incompatible")
 private void sendFullResponse(
     ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response)
     throws Exception {
   boolean keepAlive = HttpUtil.isKeepAlive(request);
   if (httpSessionManager.getSessionId(request) != null
       && httpSessionManager.getAuthenticatedUser(request) == null
       && !response.headers().contains("Set-Cookie")) {
     httpSessionManager.deleteSessionCookie(response);
   }
   response.headers().add("Glowroot-Layout-Version", layoutService.getLayoutVersion());
   if (response.headers().contains("Glowroot-Port-Changed")) {
     // current connection is the only open channel on the old port, keepAlive=false will add
     // the listener below to close the channel after the response completes
     //
     // remove the hacky header, no need to send it back to client
     response.headers().remove("Glowroot-Port-Changed");
     response.headers().add("Connection", "close");
     keepAlive = false;
   }
   response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
   if (keepAlive && !request.protocolVersion().isKeepAliveDefault()) {
     response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
   }
   ChannelFuture f = ctx.write(response);
   if (!keepAlive) {
     f.addListener(ChannelFutureListener.CLOSE);
   }
 }
Esempio n. 29
0
  /** Write the response */
  private void writeResponse(ChannelHandlerContext ctx) {
    // Convert the response content to a ByteBuf.
    ByteBuf buf = Unpooled.copiedBuffer(responseContent.toString(), WaarpStringUtils.UTF8);
    responseContent.setLength(0);

    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request);
    boolean close =
        HttpHeaderValues.CLOSE.contentEqualsIgnoreCase(
                request.headers().get(HttpHeaderNames.CONNECTION))
            || (!keepAlive)
            || forceClose;

    // Build the response object.
    FullHttpResponse response =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
    if (keepAlive) {
      response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    if (!close) {
      // There's no need to add 'Content-Length' header
      // if this is the last response.
      response.headers().set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
    }

    handleCookies(response);

    // Write the response.
    ChannelFuture future = ctx.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
      future.addListener(WaarpSslUtility.SSLCLOSE);
    }
    if (shutdown) {
      ChannelUtils.startShutdown();
    }
  }
Esempio n. 30
0
 private void writeResponse(HttpObject msg, ChannelHandlerContext ctx) {
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HTTP_1_1,
           msg.decoderResult().isSuccess() ? OK : BAD_REQUEST,
           Unpooled.copiedBuffer(_buf.toString(), CharsetUtil.UTF_8));
   if (HttpHeaderUtil.isKeepAlive(_request)) {
     response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
     ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
   } else {
     ctx.write(response).addListener(ChannelFutureListener.CLOSE);
   }
 }