Java Code Examples for io.netty.handler.codec.http.HttpUtil#is100ContinueExpected()

The following examples show how to use io.netty.handler.codec.http.HttpUtil#is100ContinueExpected() . 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: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<?> receiveObject() {
	// Handle the 'Expect: 100-continue' header if necessary.
	// TODO: Respond with 413 Request Entity Too Large
	//   and discard the traffic or close the connection.
	//       No need to notify the upstream handlers - just log.
	//       If decoding a response, just throw an error.
	if (HttpUtil.is100ContinueExpected(nettyRequest)) {
		return FutureMono.deferFuture(() -> {
					if(!hasSentHeaders()) {
						return channel().writeAndFlush(CONTINUE);
					}
					return channel().newSucceededFuture();
				})

		                 .thenMany(super.receiveObject());
	}
	else {
		return super.receiveObject();
	}
}
 
Example 2
Source File: HttpBlobHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
private void put(HttpRequest request, HttpContent content, String index, String digest) throws IOException {
    if (digestBlob == null) {
        digestBlob = blobService.newBlob(index, digest);
    }
    boolean continueExpected = HttpUtil.is100ContinueExpected(currentMessage);
    if (content == null) {
        if (continueExpected) {
            ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        return;
    }


    boolean isLast = content instanceof LastHttpContent;
    ByteBuf byteBuf = content.content();
    try {
        writeToFile(request, byteBuf, isLast, continueExpected);
    } finally {
        byteBuf.release();
    }
}
 
Example 3
Source File: HttpBlobHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
private boolean possibleRedirect(HttpRequest request, String index, String digest) {
    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET) ||
        method.equals(HttpMethod.HEAD) ||
        (method.equals(HttpMethod.PUT) &&
         HttpUtil.is100ContinueExpected(request))) {
        String redirectAddress;
        try {
            redirectAddress = blobService.getRedirectAddress(index, digest);
        } catch (MissingHTTPEndpointException ex) {
            simpleResponse(request, HttpResponseStatus.BAD_GATEWAY);
            return true;
        }

        if (redirectAddress != null) {
            LOGGER.trace("redirectAddress: {}", redirectAddress);
            sendRedirect(request, activeScheme + redirectAddress);
            return true;
        }
    }
    return false;
}
 
Example 4
Source File: HelloWorldHandler.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) {
  if (!(msg instanceof HttpRequest)) return;
  HttpRequest req = (HttpRequest) msg;

  if (HttpUtil.is100ContinueExpected(req)) {
    ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
  }
  boolean keepAlive = HttpUtil.isKeepAlive(req);
  FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
    Unpooled.wrappedBuffer(HELLO_WORLD));
  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, HttpHeaderValues.KEEP_ALIVE);
    ctx.write(response);
  }
}
 
Example 5
Source File: NettyHttpServletHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequest request = (HttpRequest) msg;
    if (HttpUtil.is100ContinueExpected(request)) {
        ctx.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
    }

    // find the nettyHttpContextHandler by lookup the request url
    NettyHttpContextHandler nettyHttpContextHandler = pipelineFactory.getNettyHttpHandler(request.uri());
    if (nettyHttpContextHandler != null) {
        handleHttpServletRequest(ctx, request, nettyHttpContextHandler);
    } else {
        throw new RuntimeException(
                new Fault(new Message("NO_NETTY_SERVLET_HANDLER_FOUND", LOG, request.uri())));
    }
}
 
Example 6
Source File: HelloWorldHttp1Handler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
    }
}
 
Example 7
Source File: Http1Handler.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(Http2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - established via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
    }
}
 
Example 8
Source File: HttpServerHandler.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext handlerContext, final Object message) {
  if (message instanceof HttpRequest) {
    final HttpRequest request = (HttpRequest)message;
    if (HttpUtil.is100ContinueExpected(request))
      handlerContext.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));

    final boolean keepAlive = HttpUtil.isKeepAlive(request);
    final 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) {
      response.headers().set(CONNECTION, Values.KEEP_ALIVE);
      handlerContext.write(response);
    }
    else {
      handlerContext.write(response).addListener(ChannelFutureListener.CLOSE);
    }
  }
}
 
Example 9
Source File: HttpServerHandler.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext handlerContext, final Object message) {
  if (message instanceof HttpRequest) {
    final HttpRequest request = (HttpRequest)message;
    if (HttpUtil.is100ContinueExpected(request))
      handlerContext.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));

    final boolean keepAlive = HttpUtil.isKeepAlive(request);
    final 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) {
      response.headers().set(CONNECTION, Values.KEEP_ALIVE);
      handlerContext.write(response);
    }
    else {
      handlerContext.write(response).addListener(ChannelFutureListener.CLOSE);
    }
  }
}
 
Example 10
Source File: HelloWorldHttp1Handler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
    }
}
 
Example 11
Source File: AgentHandler.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext context, final FullHttpRequest request) throws Exception {
  if (HttpUtil.is100ContinueExpected(request)) {
    send100Continue(context);
  }

  provider.httpRequestChannelConsumer().consume(agentChannelContext(context), toConsumable(request));
}
 
Example 12
Source File: HttpStreamsClientHandler.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void subscribeSubscriberToStream(StreamedHttpMessage msg, Subscriber<HttpContent> subscriber) {
    if (HttpUtil.is100ContinueExpected(msg)) {
        awaiting100Continue = subscriber;
        awaiting100ContinueMessage = msg;
    } else {
        super.subscribeSubscriberToStream(msg, subscriber);
    }
}
 
Example 13
Source File: HttpServerHandler.java    From cantor with Apache License 2.0 5 votes vote down vote up
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (FullHttpRequest.class.isAssignableFrom(msg.getClass())) {
            FullHttpRequest req = FullHttpRequest.class.cast(msg);
            DecoderResult result = req.decoderResult();

            if (result.isFailure()) {
                if (log.isWarnEnabled())
                    log.warn("http decoder failure", result.cause());
                ReferenceCountUtil.release(msg);
                ctx.writeAndFlush(HttpResponses.badRequest());
                ctx.channel().close();
                return;
            }

            if (HttpUtil.is100ContinueExpected(req))
                ctx.writeAndFlush(new DefaultFullHttpResponse(req.protocolVersion(), CONTINUE));

            FullHttpRequest safeReq = new DefaultFullHttpRequest(req.protocolVersion(),
                                                                 req.method(),
                                                                 req.uri(),
//                                                                 Buffers.safeByteBuf(req.content(), ctx.alloc()),
                                                                 req.content(),
                                                                 req.headers(),
                                                                 req.trailingHeaders());
            channelRead(ctx, safeReq);
        } else
            ctx.fireChannelRead(msg);
    }
 
Example 14
Source File: NettyHttpServerHandler.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            nettySource.consume(new NettyHttpRecord(Optional.ofNullable(""),
                    content.toString(CharsetUtil.UTF_8).getBytes()));
        }

        if (msg instanceof LastHttpContent) {
            LastHttpContent trailer = (LastHttpContent) msg;

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}
 
Example 15
Source File: HTTPServer.java    From tchannel-java with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(
        ChannelHandlerContext channelHandlerContext,
        FullHttpRequest fullHttpRequest
) throws Exception {

    logger.warn("Received {}", fullHttpRequest);

    if (HttpUtil.is100ContinueExpected(fullHttpRequest)) {
        channelHandlerContext.writeAndFlush(
                new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1,
                        HttpResponseStatus.CONTINUE));
    }

    HttpResponse response = new DefaultHttpResponse(
            fullHttpRequest.protocolVersion(),
            HttpResponseStatus.OK);
    HttpHeaders headers = response.headers();
    headers.set(CONTENT_TYPE, "text/html; charset=UTF-8");

    ByteBuf responseContent = Unpooled.copiedBuffer("OK", CharsetUtil.UTF_8);

    boolean keepAlive = HttpUtil.isKeepAlive(fullHttpRequest);
    if (keepAlive) {
        headers.set(CONTENT_LENGTH, responseContent.readableBytes());
        headers.set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // write response
    channelHandlerContext.write(response);
    channelHandlerContext.write(responseContent);
    ChannelFuture future = channelHandlerContext.writeAndFlush(
            LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 16
Source File: CustomHttpServerHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(request)) {
            writeResponse(ctx);
        }

        responseData.setLength(0);
        responseData.append(RequestUtils.formatParams(request));
    }

    responseData.append(RequestUtils.evaluateDecoderResult(request));

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        responseData.append(RequestUtils.formatBody(httpContent));
        responseData.append(RequestUtils.evaluateDecoderResult(request));

        if (msg instanceof LastHttpContent) {
            LastHttpContent trailer = (LastHttpContent) msg;
            responseData.append(RequestUtils.prepareLastResponse(request, trailer));
            writeResponse(ctx, trailer, responseData);
        }
    }
}
 
Example 17
Source File: ClientRequestReceiver.java    From zuul with Apache License 2.0 5 votes vote down vote up
private void handleExpect100Continue(ChannelHandlerContext ctx, HttpRequest req) {
    if (HttpUtil.is100ContinueExpected(req)) {
        final ChannelFuture f = ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        f.addListener((s) -> {
            if (! s.isSuccess()) {
                throw new ZuulException(s.cause(), "Failed while writing 100-continue response", true);
            }
        });
        // Remove the Expect: 100-Continue header from request as we don't want to proxy it downstream.
        req.headers().remove(HttpHeaderNames.EXPECT);
        zuulRequest.getHeaders().remove(HttpHeaderNames.EXPECT.toString());
    }
}
 
Example 18
Source File: Http1RequestHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (HttpUtil.is100ContinueExpected(request)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    super.channelRead0(ctx, request);
}
 
Example 19
Source File: SimpleProxyHandler.java    From xio with Apache License 2.0 4 votes vote down vote up
@Override
public RequestUpdateHandler handle(HttpRequest payload, ChannelHandlerContext ctx) {
  ReferenceCountUtil.retain(payload);
  buildAndAttach(ctx);
  if (HttpUtil.is100ContinueExpected(payload)) {
    ctx.writeAndFlush(
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
  }

  Optional<String> path =
      route
          .groups(payload.uri())
          .entrySet()
          .stream()
          .filter(e -> e.getKey().equals("path"))
          .map(e -> e.getValue())
          .findFirst();

  if (!config.pathPassthru) {
    payload.setUri(path.map(config.urlPath::concat).orElse(config.urlPath));
  }

  payload.headers().set("Host", config.hostHeader);

  XioRequest request =
      HttpTracingState.hasSpan(ctx)
          ? new XioRequest(payload, HttpTracingState.getSpan(ctx).context())
          : new XioRequest(payload, null);

  log.info("Requesting {}", payload);
  ctx.channel().attr(key).get().write(request);

  return new RequestUpdateHandler() {
    @Override
    public void update(HttpContent content) {
      ReferenceCountUtil.retain(content);
      client.write(content);
    }

    @Override
    public void update(LastHttpContent last) {
      ReferenceCountUtil.retain(last);
      client.write(last);
    }
  };
}