Beispiel #1
0
    @Override
    public void messageReceived(ChannelHandlerContext ctx, HttpObject httpObject) {
      if (log.isDebugEnabled()) {
        log.debug("Received HTTP message {}", httpObject);
      }
      if (httpObject instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) httpObject;
        SocketChannel channel = (SocketChannel) ctx.channel();
        curRequest = new NettyHttpRequest(req, channel);

        curResponse =
            new NettyHttpResponse(
                new DefaultHttpResponse(req.getProtocolVersion(), HttpResponseStatus.OK),
                channel,
                curRequest.isKeepAlive(),
                NettyHttpServer.this);
        stub.onRequest(curRequest, curResponse);

      } else if (httpObject instanceof HttpContent) {
        if ((curRequest == null) || (curResponse == null)) {
          log.error("Received an HTTP chunk without a request first");
          return;
        }
        NettyHttpChunk chunk = new NettyHttpChunk((HttpContent) httpObject);
        if (chunk.hasData() && !curRequest.hasContentLength() && !curRequest.isChunked()) {
          returnError(ctx, HttpResponseStatus.BAD_REQUEST);
        } else {
          stub.onData(curRequest, curResponse, chunk);
        }

      } else {
        throw new AssertionError();
      }
    }
  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);
    }
  }
 public static HttpResponse createRejection(HttpRequest request, String reason) {
   HttpVersion version = request != null ? request.getProtocolVersion() : HttpVersion.HTTP_1_1;
   HttpResponse response = new DefaultHttpResponse(version, HttpResponseStatus.BAD_REQUEST);
   response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=\"utf-8\"");
   ChannelBuffer reasonBuffer = ChannelBuffers.wrappedBuffer(toBytes(reason));
   response.setHeader(
       HttpHeaders.Names.CONTENT_LENGTH, Integer.toString(reasonBuffer.readableBytes()));
   response.setContent(reasonBuffer);
   return response;
 }
  private static boolean isRequestTo(HttpRequest request, String uri) {
    URI decodedUri;
    try {
      decodedUri = new URI(request.getUri());
    } catch (URISyntaxException e) {
      return false;
    }

    return HttpVersion.HTTP_1_1.equals(request.getProtocolVersion())
        && USER_AGENT.equals(request.getHeader(HttpHeaders.Names.USER_AGENT))
        && HttpMethod.POST.equals(request.getMethod())
        && uri.equals(decodedUri.getPath());
  }
  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(CONNECTION, HttpHeaders.Values.CLOSE, true)
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
                && !request.headers().contains(CONNECTION, HttpHeaders.Values.KEEP_ALIVE, true);

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

    Set<Cookie> cookies;
    String value = request.headers().get(COOKIE);
    if (value == null) {
      cookies = Collections.emptySet();
    } else {
      cookies = CookieDecoder.decode(value);
    }
    if (!cookies.isEmpty()) {
      // Reset the cookies if necessary.
      for (Cookie cookie : cookies) {
        response.headers().add(SET_COOKIE, ServerCookieEncoder.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);
    }
  }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
      HttpRequest request = this.request = (HttpRequest) msg;
      URI uri = new URI(request.getUri());
      if (!uri.getPath().startsWith("/form")) {
        // Write Menu
        writeMenu(ctx);
        return;
      }
      responseContent.setLength(0);
      responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
      responseContent.append("===================================\r\n");

      responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

      responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
      responseContent.append("\r\n\r\n");

      // new getMethod
      for (Entry<String, String> entry : request.headers()) {
        responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
      }
      responseContent.append("\r\n\r\n");

      // new getMethod
      Set<Cookie> cookies;
      String value = request.headers().get(COOKIE);
      if (value == null) {
        cookies = Collections.emptySet();
      } else {
        cookies = CookieDecoder.decode(value);
      }
      for (Cookie cookie : cookies) {
        responseContent.append("COOKIE: " + cookie + "\r\n");
      }
      responseContent.append("\r\n\r\n");

      QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
      Map<String, List<String>> uriAttributes = decoderQuery.parameters();
      for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
        for (String attrVal : attr.getValue()) {
          responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
        }
      }
      responseContent.append("\r\n\r\n");

      // if GET Method: should not try to create a HttpPostRequestDecoder
      if (request.getMethod().equals(HttpMethod.GET)) {
        // GET Method: should not try to create a HttpPostRequestDecoder
        // So stop here
        responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
        writeResponse(ctx.channel());
        return;
      }
      try {
        decoder = new HttpPostRequestDecoder(factory, request);
      } catch (ErrorDataDecoderException e1) {
        e1.printStackTrace();
        responseContent.append(e1.getMessage());
        writeResponse(ctx.channel());
        ctx.channel().close();
        return;
      }

      readingChunks = HttpHeaders.isTransferEncodingChunked(request);
      responseContent.append("Is Chunked: " + readingChunks + "\r\n");
      responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
      if (readingChunks) {
        // Chunk version
        responseContent.append("Chunks: ");
        readingChunks = true;
      }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
      if (msg instanceof HttpContent) {
        // New chunk is received
        HttpContent chunk = (HttpContent) msg;
        try {
          decoder.offer(chunk);
        } catch (ErrorDataDecoderException e1) {
          e1.printStackTrace();
          responseContent.append(e1.getMessage());
          writeResponse(ctx.channel());
          ctx.channel().close();
          return;
        }
        responseContent.append('o');
        // example of reading chunk by chunk (minimize memory usage due to
        // Factory)
        readHttpDataChunkByChunk();
        // example of reading only if at the end
        if (chunk instanceof LastHttpContent) {
          writeResponse(ctx.channel());
          readingChunks = false;

          reset();
        }
      }
    }
  }