Example usage for io.netty.handler.codec.http HttpResponseStatus REQUEST_ENTITY_TOO_LARGE

List of usage examples for io.netty.handler.codec.http HttpResponseStatus REQUEST_ENTITY_TOO_LARGE

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus REQUEST_ENTITY_TOO_LARGE.

Prototype

HttpResponseStatus REQUEST_ENTITY_TOO_LARGE

To view the source code for io.netty.handler.codec.http HttpResponseStatus REQUEST_ENTITY_TOO_LARGE.

Click Source Link

Document

413 Request Entity Too Large

Usage

From source file:com.linecorp.armeria.server.http.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);//  w ww  . j ava2 s  .  c  o  m
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController);

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.writtenBytes() > maxContentLength - dataLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                req.write(HttpData.of(data));
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.server.http.Http2RequestDecoder.java

License:Apache License

@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)
        throws Http2Exception {

    final DecodedHttpRequest req = requests.get(streamId);
    if (req == null) {
        throw connectionError(PROTOCOL_ERROR, "received a DATA Frame for an unknown stream: %d", streamId);
    }//from  w w w . j a va2s . com

    final int dataLength = data.readableBytes();

    if (req.isOpen()) {
        final long maxContentLength = req.maxRequestLength();
        if (maxContentLength > 0 && req.writtenBytes() > maxContentLength - dataLength) {
            if (isWritable(streamId)) {
                writeErrorResponse(ctx, streamId, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                req.close(ContentTooLargeException.get());
            } else {
                req.close(ContentTooLargeException.get());
                throw connectionError(INTERNAL_ERROR, "content length too large: %d + %d > %d (stream: %d)",
                        req.writtenBytes(), dataLength, maxContentLength, streamId);
            }
        } else {
            try {
                req.write(HttpData.of(data));
            } catch (Throwable t) {
                req.close(t);
                throw connectionError(INTERNAL_ERROR, t, "failed to consume a DATA frame");
            }

            if (endOfStream) {
                req.close();
            }
        }
    }

    // All bytes have been processed.
    return dataLength + padding;
}

From source file:com.linecorp.armeria.server.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);//ww w  . jav a2 s .  co m
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the method.
                if (!HttpMethod.isSupported(nettyReq.method().name())) {
                    fail(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
                    return;
                }

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                final boolean contentEmpty;
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }

                    contentEmpty = contentLength == 0;
                } else {
                    contentEmpty = true;
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController, cfg.defaultMaxRequestLength());

                // Close the request early when it is sure that there will be
                // neither content nor trailing headers.
                if (contentEmpty && !HttpUtil.isTransferEncodingChunked(nettyReq)) {
                    req.close();
                }

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                req.increaseTransferredBytes(dataLength);
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.transferredBytes() > maxContentLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                if (req.isOpen()) {
                    req.write(new ByteBufHttpData(data.retain(), false));
                }
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (URISyntaxException e) {
        fail(ctx, HttpResponseStatus.BAD_REQUEST);
        if (req != null) {
            req.close(e);
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linecorp.armeria.server.Http2RequestDecoder.java

License:Apache License

@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)
        throws Http2Exception {

    final DecodedHttpRequest req = requests.get(streamId);
    if (req == null) {
        throw connectionError(PROTOCOL_ERROR, "received a DATA Frame for an unknown stream: %d", streamId);
    }/*from   w w  w  .j  a  va2s. c om*/

    final int dataLength = data.readableBytes();
    if (dataLength == 0) {
        // Received an empty DATA frame
        if (endOfStream) {
            req.close();
        }
        return padding;
    }

    req.increaseTransferredBytes(dataLength);

    final long maxContentLength = req.maxRequestLength();
    if (maxContentLength > 0 && req.transferredBytes() > maxContentLength) {
        if (req.isOpen()) {
            req.close(ContentTooLargeException.get());
        }

        if (isWritable(streamId)) {
            writeErrorResponse(ctx, streamId, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
        } else {
            // Cannot write to the stream. Just close it.
            final Http2Stream stream = writer.connection().stream(streamId);
            stream.close();
        }
    } else if (req.isOpen()) {
        try {
            req.write(new ByteBufHttpData(data.retain(), endOfStream));
        } catch (Throwable t) {
            req.close(t);
            throw connectionError(INTERNAL_ERROR, t, "failed to consume a DATA frame");
        }

        if (endOfStream) {
            req.close();
        }
    }

    // All bytes have been processed.
    return dataLength + padding;
}

From source file:com.mastfrog.acteur.ActeurFactory.java

License:Open Source License

public Acteur maximumBodyLength(final int length) {
    return new Acteur() {

        @Override//from w w w  . j  a va2 s .com
        public State getState() {
            try {
                int val = deps.getInstance(HttpEvent.class).getContent().readableBytes();
                if (val > length) {
                    return new Acteur.RespondWith(new Err(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE,
                            "Request body must be < " + length + " characters"));
                }
                return new Acteur.ConsumedState();
            } catch (IOException ex) {
                return Exceptions.chuck(ex);
            }
        }
    };
}

From source file:org.apache.hyracks.http.test.HttpRequestTask.java

License:Apache License

@Override
public Void call() throws Exception {
    try {//ww w.  j  ava2s. co  m
        HttpResponse response = executeHttpRequest(request);
        if (response.getStatusLine().getStatusCode() == HttpResponseStatus.OK.code()) {
            HttpServerTest.SUCCESS_COUNT.incrementAndGet();
        } else if (response.getStatusLine().getStatusCode() == HttpResponseStatus.SERVICE_UNAVAILABLE.code()) {
            HttpServerTest.UNAVAILABLE_COUNT.incrementAndGet();
        } else if (response.getStatusLine().getStatusCode() == HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE
                .code()) {
            throw new Exception(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE.reasonPhrase());
        } else {
            HttpServerTest.OTHER_COUNT.incrementAndGet();
        }
        InputStream in = response.getEntity().getContent();
        if (HttpServerTest.PRINT_TO_CONSOLE) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
        IOUtils.closeQuietly(in);
    } catch (Throwable th) {
        th.printStackTrace();
        throw th;
    }
    return null;
}

From source file:org.eclipse.milo.opcua.stack.client.transport.http.OpcClientHttpCodec.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, HttpResponse httpResponse, List<Object> out) throws Exception {

    logger.trace("channelRead0: " + httpResponse);

    UaTransportRequest transportRequest = ctx.channel().attr(KEY_PENDING_REQUEST).getAndSet(null);

    if (httpResponse instanceof FullHttpResponse) {
        String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE);

        FullHttpResponse fullHttpResponse = (FullHttpResponse) httpResponse;
        ByteBuf content = fullHttpResponse.content();

        UaResponseMessage responseMessage;

        switch (transportProfile) {
        case HTTPS_UABINARY: {
            if (!UABINARY_CONTENT_TYPE.equalsIgnoreCase(contentType)) {
                throw new UaException(StatusCodes.Bad_DecodingError, "unexpected content-type: " + contentType);
            }//  w  w  w  . j a  v a 2  s .c  om

            OpcUaBinaryStreamDecoder decoder = new OpcUaBinaryStreamDecoder(content);
            responseMessage = (UaResponseMessage) decoder.readMessage(null);
            break;
        }

        case HTTPS_UAXML: {
            // TODO extract document from SOAP message body
            throw new UaException(StatusCodes.Bad_InternalError,
                    "no decoder for transport: " + transportProfile);
        }

        default:
            throw new UaException(StatusCodes.Bad_InternalError,
                    "no decoder for transport: " + transportProfile);
        }

        transportRequest.getFuture().complete(responseMessage);
    } else {
        HttpResponseStatus status = httpResponse.status();

        if (status.equals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE)) {
            transportRequest.getFuture()
                    .completeExceptionally(new UaException(StatusCodes.Bad_ResponseTooLarge));
        } else {
            transportRequest.getFuture().completeExceptionally(new UaException(StatusCodes.Bad_UnexpectedError,
                    String.format("%s: %s", status.code(), status.reasonPhrase())));
        }
    }
}

From source file:org.elasticsearch.http.nio.HttpReadWriteHandlerTests.java

License:Apache License

public void testDecodeHttpRequestContentLengthToLongGeneratesOutboundMessage() throws IOException {
    String uri = "localhost:9090/" + randomAlphaOfLength(8);
    io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.POST, uri, false);
    HttpUtil.setContentLength(httpRequest, 1025);
    HttpUtil.setKeepAlive(httpRequest, false);

    ByteBuf buf = requestEncoder.encode(httpRequest);
    try {// w w  w  .j av a 2s. c  om
        handler.consumeReads(toChannelBuffer(buf));
    } finally {
        buf.release();
    }
    verify(transport, times(0)).incomingRequestError(any(), any(), any());
    verify(transport, times(0)).incomingRequest(any(), any());

    List<FlushOperation> flushOperations = handler.pollFlushOperations();
    assertFalse(flushOperations.isEmpty());

    FlushOperation flushOperation = flushOperations.get(0);
    FullHttpResponse response = responseDecoder
            .decode(Unpooled.wrappedBuffer(flushOperation.getBuffersToWrite()));
    try {
        assertEquals(HttpVersion.HTTP_1_1, response.protocolVersion());
        assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());

        flushOperation.getListener().accept(null, null);
        // Since we have keep-alive set to false, we should close the channel after the response has been
        // flushed
        verify(nioHttpChannel).close();
    } finally {
        response.release();
    }
}

From source file:org.elasticsearch.http.nio.NioHttpServerTransportTests.java

License:Apache License

/**
 * Test that {@link NioHttpServerTransport} responds to a
 * 100-continue expectation with too large a content-length
 * with a 413 status.//from   ww  w  .ja va2s  .  c  o  m
 * @throws InterruptedException if the client communication with the server is interrupted
 */
public void testExpectContinueHeaderContentLengthTooLong() throws InterruptedException {
    final String key = HttpTransportSettings.SETTING_HTTP_MAX_CONTENT_LENGTH.getKey();
    final int maxContentLength = randomIntBetween(1, 104857600);
    final Settings settings = Settings.builder().put(key, maxContentLength + "b").build();
    final int contentLength = randomIntBetween(maxContentLength + 1, Integer.MAX_VALUE);
    runExpectHeaderTest(settings, HttpHeaderValues.CONTINUE.toString(), contentLength,
            HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
}

From source file:org.nosceon.titanite.Exceptions.java

License:Apache License

static Response requestEntityTooLarge() {
    return new Response(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE).text("Request Entity Too Large");
}