Search in sources :

Example 46 with FullHttpRequest

use of io.netty.handler.codec.http.FullHttpRequest in project elasticsearch by elastic.

the class Netty4HttpRequestHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    final FullHttpRequest request;
    final HttpPipelinedRequest pipelinedRequest;
    if (this.httpPipeliningEnabled && msg instanceof HttpPipelinedRequest) {
        pipelinedRequest = (HttpPipelinedRequest) msg;
        request = (FullHttpRequest) pipelinedRequest.last();
    } else {
        pipelinedRequest = null;
        request = (FullHttpRequest) msg;
    }
    final FullHttpRequest copy = new DefaultFullHttpRequest(request.protocolVersion(), request.method(), request.uri(), Unpooled.copiedBuffer(request.content()), request.headers(), request.trailingHeaders());
    final Netty4HttpRequest httpRequest = new Netty4HttpRequest(serverTransport.xContentRegistry, copy, ctx.channel());
    final Netty4HttpChannel channel = new Netty4HttpChannel(serverTransport, httpRequest, pipelinedRequest, detailedErrorsEnabled, threadContext);
    if (request.decoderResult().isSuccess()) {
        serverTransport.dispatchRequest(httpRequest, channel);
    } else {
        assert request.decoderResult().isFailure();
        serverTransport.dispatchBadRequest(httpRequest, channel, request.decoderResult().cause());
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpPipelinedRequest(org.elasticsearch.http.netty4.pipelining.HttpPipelinedRequest)

Example 47 with FullHttpRequest

use of io.netty.handler.codec.http.FullHttpRequest in project elasticsearch by elastic.

the class Netty4HttpChannelTests method testReleaseOnSendToClosedChannel.

public void testReleaseOnSendToClosedChannel() {
    final Settings settings = Settings.builder().build();
    final NamedXContentRegistry registry = xContentRegistry();
    try (Netty4HttpServerTransport httpServerTransport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, registry, new NullDispatcher())) {
        final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        final EmbeddedChannel embeddedChannel = new EmbeddedChannel();
        final Netty4HttpRequest request = new Netty4HttpRequest(registry, httpRequest, embeddedChannel);
        final HttpPipelinedRequest pipelinedRequest = randomBoolean() ? new HttpPipelinedRequest(request.request(), 1) : null;
        final Netty4HttpChannel channel = new Netty4HttpChannel(httpServerTransport, request, pipelinedRequest, randomBoolean(), threadPool.getThreadContext());
        final TestResponse response = new TestResponse(bigArrays);
        assertThat(response.content(), instanceOf(Releasable.class));
        embeddedChannel.close();
        channel.sendResponse(response);
    // ESTestCase#after will invoke ensureAllArraysAreReleased which will fail if the response content was not released
    }
}
Also used : NullDispatcher(org.elasticsearch.http.NullDispatcher) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpPipelinedRequest(org.elasticsearch.http.netty4.pipelining.HttpPipelinedRequest) Releasable(org.elasticsearch.common.lease.Releasable) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Settings(org.elasticsearch.common.settings.Settings) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings)

Example 48 with FullHttpRequest

use of io.netty.handler.codec.http.FullHttpRequest in project elasticsearch by elastic.

the class Netty4HttpChannelTests method testHeadersSet.

public void testHeadersSet() {
    Settings settings = Settings.builder().build();
    try (Netty4HttpServerTransport httpServerTransport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), new NullDispatcher())) {
        httpServerTransport.start();
        final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        httpRequest.headers().add(HttpHeaderNames.ORIGIN, "remote");
        final WriteCapturingChannel writeCapturingChannel = new WriteCapturingChannel();
        Netty4HttpRequest request = new Netty4HttpRequest(xContentRegistry(), httpRequest, writeCapturingChannel);
        // send a response
        Netty4HttpChannel channel = new Netty4HttpChannel(httpServerTransport, request, null, randomBoolean(), threadPool.getThreadContext());
        TestResponse resp = new TestResponse();
        final String customHeader = "custom-header";
        final String customHeaderValue = "xyz";
        resp.addHeader(customHeader, customHeaderValue);
        channel.sendResponse(resp);
        // inspect what was written
        List<Object> writtenObjects = writeCapturingChannel.getWrittenObjects();
        assertThat(writtenObjects.size(), is(1));
        HttpResponse response = (HttpResponse) writtenObjects.get(0);
        assertThat(response.headers().get("non-existent-header"), nullValue());
        assertThat(response.headers().get(customHeader), equalTo(customHeaderValue));
        assertThat(response.headers().get(HttpHeaderNames.CONTENT_LENGTH), equalTo(Integer.toString(resp.content().length())));
        assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE), equalTo(resp.contentType()));
    }
}
Also used : NullDispatcher(org.elasticsearch.http.NullDispatcher) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Settings(org.elasticsearch.common.settings.Settings) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings)

Example 49 with FullHttpRequest

use of io.netty.handler.codec.http.FullHttpRequest in project elasticsearch by elastic.

the class Netty4HttpServerTransportTests method runExpectHeaderTest.

private void runExpectHeaderTest(final Settings settings, final String expectation, final int contentLength, final HttpResponseStatus expectedStatus) throws InterruptedException {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) {
            channel.sendResponse(new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done")));
        }

        @Override
        public void dispatchBadRequest(RestRequest request, RestChannel channel, ThreadContext threadContext, Throwable cause) {
            throw new AssertionError();
        }
    };
    try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher)) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        try (Netty4HttpClient client = new Netty4HttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
            request.headers().set(HttpHeaderNames.EXPECT, expectation);
            HttpUtil.setContentLength(request, contentLength);
            final FullHttpResponse response = client.post(remoteAddress.address(), request);
            assertThat(response.status(), equalTo(expectedStatus));
            if (expectedStatus.equals(HttpResponseStatus.CONTINUE)) {
                final FullHttpRequest continuationRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.EMPTY_BUFFER);
                final FullHttpResponse continuationResponse = client.post(remoteAddress.address(), continuationRequest);
                assertThat(continuationResponse.status(), is(HttpResponseStatus.OK));
                assertThat(new String(ByteBufUtil.getBytes(continuationResponse.content()), StandardCharsets.UTF_8), is("done"));
            }
        }
    }
}
Also used : BytesArray(org.elasticsearch.common.bytes.BytesArray) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) TransportAddress(org.elasticsearch.common.transport.TransportAddress) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) RestChannel(org.elasticsearch.rest.RestChannel) Matchers.containsString(org.hamcrest.Matchers.containsString) Strings.collectionToDelimitedString(org.elasticsearch.common.Strings.collectionToDelimitedString) NullDispatcher(org.elasticsearch.http.NullDispatcher) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) RestRequest(org.elasticsearch.rest.RestRequest) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 50 with FullHttpRequest

use of io.netty.handler.codec.http.FullHttpRequest in project netty by netty.

the class HttpPostRequestEncoder method finalizeRequest.

/**
     * Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br>
     * Once finalized, no data must be added.<br>
     * If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote
     * server.
     *
     * @return the request object (chunked or not according to size of body)
     * @throws ErrorDataEncoderException
     *             if the encoding is in error or if the finalize were already done
     */
public HttpRequest finalizeRequest() throws ErrorDataEncoderException {
    // Finalize the multipartHttpDatas
    if (!headerFinalized) {
        if (isMultipart) {
            InternalAttribute internal = new InternalAttribute(charset);
            if (duringMixedMode) {
                internal.addValue("\r\n--" + multipartMixedBoundary + "--");
            }
            internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n");
            multipartHttpDatas.add(internal);
            multipartMixedBoundary = null;
            currentFileUpload = null;
            duringMixedMode = false;
            globalBodySize += internal.size();
        }
        headerFinalized = true;
    } else {
        throw new ErrorDataEncoderException("Header already encoded");
    }
    HttpHeaders headers = request.headers();
    List<String> contentTypes = headers.getAll(HttpHeaderNames.CONTENT_TYPE);
    List<String> transferEncoding = headers.getAll(HttpHeaderNames.TRANSFER_ENCODING);
    if (contentTypes != null) {
        headers.remove(HttpHeaderNames.CONTENT_TYPE);
        for (String contentType : contentTypes) {
            // "multipart/form-data; boundary=--89421926422648"
            String lowercased = contentType.toLowerCase();
            if (lowercased.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()) || lowercased.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())) {
            // ignore
            } else {
                headers.add(HttpHeaderNames.CONTENT_TYPE, contentType);
            }
        }
    }
    if (isMultipart) {
        String value = HttpHeaderValues.MULTIPART_FORM_DATA + "; " + HttpHeaderValues.BOUNDARY + '=' + multipartDataBoundary;
        headers.add(HttpHeaderNames.CONTENT_TYPE, value);
    } else {
        // Not multipart
        headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    }
    // Now consider size for chunk or not
    long realSize = globalBodySize;
    if (isMultipart) {
        iterator = multipartHttpDatas.listIterator();
    } else {
        // last '&' removed
        realSize -= 1;
        iterator = multipartHttpDatas.listIterator();
    }
    headers.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(realSize));
    if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) {
        isChunked = true;
        if (transferEncoding != null) {
            headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
            for (CharSequence v : transferEncoding) {
                if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(v)) {
                // ignore
                } else {
                    headers.add(HttpHeaderNames.TRANSFER_ENCODING, v);
                }
            }
        }
        HttpUtil.setTransferEncodingChunked(request, true);
        // wrap to hide the possible content
        return new WrappedHttpRequest(request);
    } else {
        // get the only one body and set it to the request
        HttpContent chunk = nextChunk();
        if (request instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) request;
            ByteBuf chunkContent = chunk.content();
            if (fullRequest.content() != chunkContent) {
                fullRequest.content().clear().writeBytes(chunkContent);
                chunkContent.release();
            }
            return fullRequest;
        } else {
            return new WrappedFullHttpRequest(request, chunk);
        }
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) EmptyHttpHeaders(io.netty.handler.codec.http.EmptyHttpHeaders) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent)

Aggregations

FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)97 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)65 Test (org.junit.Test)51 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)32 AsciiString (io.netty.util.AsciiString)25 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)22 ByteBuf (io.netty.buffer.ByteBuf)19 ChannelPromise (io.netty.channel.ChannelPromise)16 HttpResponse (io.netty.handler.codec.http.HttpResponse)13 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)12 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)11 FullHttpMessage (io.netty.handler.codec.http.FullHttpMessage)10 URI (java.net.URI)10 Http2CodecUtil.getEmbeddedHttp2Exception (io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception)9 Http2Runnable (io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable)9 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)8 ChannelFuture (io.netty.channel.ChannelFuture)7 Channel (io.netty.channel.Channel)6 NullDispatcher (org.elasticsearch.http.NullDispatcher)6 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)5