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);
    }
  }
 @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();
   }
 }
 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);
 }
Esempio n. 4
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;
  }
  /**
   * 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);
    }
  }
  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);
    }
  }
Esempio n. 7
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);
  }
  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);
  }
 @Test
 public void iframeUppercase() throws Exception {
   final SockJsConfig config = config();
   final String path = config.prefix() + "/IFRAME";
   final FullHttpResponse response = Iframe.response(config, createHttpRequest(path));
   assertThat(response.getStatus().code(), is(HttpResponseStatus.NOT_FOUND.code()));
 }
Esempio n. 10
0
 @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. 11
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. 12
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())));
  }
Esempio n. 13
0
 public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
   logger.warn("send status {}", ctx.channel(), status);
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HTTP_1_1, status, Unpooled.copiedBuffer(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);
 }
 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);
 }
Esempio n. 15
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. 16
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);
   }
 }
 @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. 18
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());
  }
Esempio n. 19
0
  @Override
  public void channelRead0(final ChannelHandlerContext c, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (response == null) {
      if (msg instanceof FullHttpResponse) {
        response = (FullHttpResponse) msg;
      } else {
        response = new WSResponse((DefaultHttpResponse) msg, ctx.alloc().buffer());
      }
      if (completeHandshake(ctx)) {
        return;
      }
    }
    if (msg instanceof LastHttpContent) {
      return;
    }

    if (!(msg instanceof WebSocketFrame)) {
      throw new Exception(
          "Unexpected FullHttpResponse (getStatus="
              + response.getStatus()
              + ", "
              + "content="
              + response.content().toString(CharsetUtil.UTF_8)
              + ')');
    }

    final WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
      for (WebSocketEventListener l : listensers) {
        l.onMessage(c, new WebSocketMessage(((TextWebSocketFrame) frame).text()));
      }
    } else if (frame instanceof PingWebSocketFrame) {
      if (autoPong) {
        ctx.writeAndFlush(new PongWebSocketFrame(frame.content().copy()));
      }
      for (WebSocketEventListener l : listensers) {
        l.onPing(c, (PingWebSocketFrame) frame.copy());
      }
    } else if (frame instanceof PongWebSocketFrame) {
      Logger.getLogger(getClass())
          .warn(
              String.format(
                  "WebSocketClient received a PongWebSocketFrame, that shouldn't happen! Data : %s",
                  frame.content().toString(CharsetUtil.UTF_8)));
    } else if (frame instanceof CloseWebSocketFrame) {
      ch.close();
      for (WebSocketEventListener l : listensers) {
        l.onClose(c, (CloseWebSocketFrame) frame.copy());
      }
    }
  }
Esempio n. 20
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);
   }
 }
Esempio n. 21
0
 @Converter
 public static String toString(FullHttpResponse response, Exchange exchange) {
   String contentType = response.headers().get(Exchange.CONTENT_TYPE);
   String charset = NettyHttpHelper.getCharsetFromContentType(contentType);
   if (charset == null && exchange != null) {
     charset = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
   }
   if (charset != null) {
     return response.content().toString(Charset.forName(charset));
   } else {
     return response.content().toString(Charset.defaultCharset());
   }
 }
Esempio n. 22
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. 23
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);
    }
  }
  private void writeMenu(ChannelHandlerContext ctx) {
    // print several HTML forms
    // Convert the response content to a ChannelBuffer.
    StringBuffer responseContent = new StringBuffer();
    responseContent.setLength(0);
    // TODO: Need to name the classfile for Java, or we need to parse it out server-side
    String page =
        String.format(
            "<html><head><title> KnoxCraft Turtles 3D: Code Upload Form</title></head>\n"
                + "<body>\n"
                + "<h1>KnoxCraft Turtles 3D: Code Upload Form</h1>\n"
                + "<form method=%s action=%s enctype=\"multipart/form-data\">\n"
                + "Player Name: <input type=text name=%s><br>\n"
                + "<input type=hidden name=client value=web>\n"
                + "Language: <select name=%s>\n"
                + "<option value=%s selected> Java </option><br>\n"
                + "<option value=%s> Python </option>\n"
                + "</select>\n"
                + "Source Code (paste here): <br><textarea rows=15 cols=60 name=%s></textarea><br>\n"
                + "JSON Turtle Commands (paste here): <br><textarea rows=15 cols=60 name=%s></textarea><br>\n"
                + "Source Code (file upload): <input type=%s name=%s><br>\n"
                + "JSON Turtle Commands (file upload): <input type=%s name=%s><br>\n"
                + "<input type=submit value=%s><br>\n"
                + "</form>\n"
                + "</body></html>\n",
            quoteString("POST"),
            quoteString("/kctupload"),
            quoteString("playerName"),
            quoteString("language"),
            quoteString("Java"),
            quoteString("Python"),
            quoteString("sourcetext"),
            quoteString("jsontext"),
            quoteString("file"),
            quoteString("sourcefile"),
            quoteString("file"),
            quoteString("jsonfile"),
            quoteString("Upload KnoxCraft 3D Turtle Code!"));
    responseContent.append(page);

    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    // Build the response object.
    FullHttpResponse response =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    // Write the response.
    ctx.channel().writeAndFlush(response);
  }
Esempio n. 25
0
 /**
  * Send an error and close
  *
  * @param ctx
  * @param status
  */
 private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
   responseContent.setLength(0);
   responseContent.append(error(status.toString()));
   FullHttpResponse response =
       new DefaultFullHttpResponse(
           HttpVersion.HTTP_1_1,
           status,
           Unpooled.copiedBuffer(responseContent.toString(), WaarpStringUtils.UTF8));
   response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
   response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
   responseContent.setLength(0);
   clearSession();
   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(WaarpSslUtility.SSLCLOSE);
 }
  @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 sendResponse(
      ChannelHandlerContext channel,
      FullHttpRequest request,
      String messageBody,
      HttpResponseStatus status) {

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);

    if (messageBody != null && !messageBody.isEmpty()) {
      response.content().writeBytes(Unpooled.copiedBuffer(messageBody, Constants.DEFAULT_CHARSET));
    }

    HttpResponder.respond(channel, request, response);
    Tracker.getInstance().trackResponse(request, 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.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);
    }
  }
  /**
   * 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()));
  }
Esempio n. 30
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));
   }
 }