Search in sources :

Example 1 with UnpooledByteBufAllocator

use of io.netty.buffer.UnpooledByteBufAllocator in project vertx-web by vert-x3.

the class HttpContext method sendRequest.

private void sendRequest() {
    Future<HttpClientResponse> responseFuture = Future.<HttpClientResponse>future().setHandler(ar -> {
        Context context = Vertx.currentContext();
        if (ar.succeeded()) {
            HttpClientResponse resp = ar.result();
            Future<HttpResponse<Object>> fut = Future.future();
            fut.setHandler(r -> {
                // We are running on a context (the HTTP client mandates it)
                context.runOnContext(v -> currentResponseHandler.handle(r));
            });
            resp.exceptionHandler(err -> {
                if (!fut.isComplete()) {
                    fut.fail(err);
                }
            });
            resp.pause();
            ((BodyCodec<Object>) request.codec).create(ar2 -> {
                resp.resume();
                if (ar2.succeeded()) {
                    BodyStream<Object> stream = ar2.result();
                    stream.exceptionHandler(err -> {
                        if (!fut.isComplete()) {
                            fut.fail(err);
                        }
                    });
                    resp.endHandler(v -> {
                        if (!fut.isComplete()) {
                            stream.end();
                            if (stream.result().succeeded()) {
                                fut.complete(new HttpResponseImpl<>(resp, null, stream.result().result()));
                            } else {
                                fut.fail(stream.result().cause());
                            }
                        }
                    });
                    Pump responsePump = Pump.pump(resp, stream);
                    responsePump.start();
                } else {
                    currentResponseHandler.handle(Future.failedFuture(ar2.cause()));
                }
            });
        } else {
            currentResponseHandler.handle(Future.failedFuture(ar.cause()));
        }
    });
    HttpClientRequest req;
    String requestURI;
    if (request.queryParams() != null && request.queryParams().size() > 0) {
        QueryStringEncoder enc = new QueryStringEncoder(request.uri);
        request.queryParams().forEach(param -> enc.addParam(param.getKey(), param.getValue()));
        requestURI = enc.toString();
    } else {
        requestURI = request.uri;
    }
    int port = request.port;
    String host = request.host;
    if (request.ssl != request.options.isSsl()) {
        req = request.client.client.request(request.method, new RequestOptions().setSsl(request.ssl).setHost(host).setPort(port).setURI(requestURI));
    } else {
        if (request.protocol != null && !request.protocol.equals("http") && !request.protocol.equals("https")) {
            // we have to create an abs url again to parse it in HttpClient
            try {
                URI uri = new URI(request.protocol, null, host, port, requestURI, null, null);
                req = request.client.client.requestAbs(request.method, uri.toString());
            } catch (URISyntaxException ex) {
                currentResponseHandler.handle(Future.failedFuture(ex));
                return;
            }
        } else {
            req = request.client.client.request(request.method, port, host, requestURI);
        }
    }
    if (request.virtualHost != null) {
        String virtalHost = request.virtualHost;
        if (port != 80) {
            virtalHost += ":" + port;
        }
        req.setHost(virtalHost);
    }
    req.setFollowRedirects(request.followRedirects);
    if (request.headers != null) {
        req.headers().addAll(request.headers);
    }
    req.handler(responseFuture::tryComplete);
    if (request.timeout > 0) {
        req.setTimeout(request.timeout);
    }
    if (body != null) {
        if (contentType != null) {
            String prev = req.headers().get(HttpHeaders.CONTENT_TYPE);
            if (prev == null) {
                req.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
            } else {
                contentType = prev;
            }
        }
        if (body instanceof ReadStream<?>) {
            ReadStream<Buffer> stream = (ReadStream<Buffer>) body;
            if (request.headers == null || !request.headers.contains(HttpHeaders.CONTENT_LENGTH)) {
                req.setChunked(true);
            }
            Pump pump = Pump.pump(stream, req);
            req.exceptionHandler(err -> {
                pump.stop();
                stream.endHandler(null);
                stream.resume();
                responseFuture.tryFail(err);
            });
            stream.exceptionHandler(err -> {
                req.reset();
                responseFuture.tryFail(err);
            });
            stream.endHandler(v -> {
                req.exceptionHandler(responseFuture::tryFail);
                req.end();
                pump.stop();
            });
            pump.start();
        } else {
            Buffer buffer;
            if (body instanceof Buffer) {
                buffer = (Buffer) body;
            } else if (body instanceof MultiMap) {
                try {
                    MultiMap attributes = (MultiMap) body;
                    boolean multipart = "multipart/form-data".equals(contentType);
                    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.POST, "/");
                    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, multipart);
                    for (Map.Entry<String, String> attribute : attributes) {
                        encoder.addBodyAttribute(attribute.getKey(), attribute.getValue());
                    }
                    encoder.finalizeRequest();
                    for (String headerName : request.headers().names()) {
                        req.putHeader(headerName, request.headers().get(headerName));
                    }
                    if (encoder.isChunked()) {
                        buffer = Buffer.buffer();
                        while (true) {
                            HttpContent chunk = encoder.readChunk(new UnpooledByteBufAllocator(false));
                            ByteBuf content = chunk.content();
                            if (content.readableBytes() == 0) {
                                break;
                            }
                            buffer.appendBuffer(Buffer.buffer(content));
                        }
                    } else {
                        ByteBuf content = request.content();
                        buffer = Buffer.buffer(content);
                    }
                } catch (Exception e) {
                    throw new VertxException(e);
                }
            } else if (body instanceof JsonObject) {
                buffer = Buffer.buffer(((JsonObject) body).encode());
            } else {
                buffer = Buffer.buffer(Json.encode(body));
            }
            req.exceptionHandler(responseFuture::tryFail);
            req.end(buffer);
        }
    } else {
        req.exceptionHandler(responseFuture::tryFail);
        req.end();
    }
}
Also used : RequestOptions(io.vertx.core.http.RequestOptions) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) JsonObject(io.vertx.core.json.JsonObject) URISyntaxException(java.net.URISyntaxException) ByteBuf(io.netty.buffer.ByteBuf) URI(java.net.URI) MultiMap(io.vertx.core.MultiMap) UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) VertxException(io.vertx.core.VertxException) HttpClientResponse(io.vertx.core.http.HttpClientResponse) ReadStream(io.vertx.core.streams.ReadStream) Context(io.vertx.core.Context) BodyCodec(io.vertx.ext.web.codec.BodyCodec) Buffer(io.vertx.core.buffer.Buffer) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponse(io.vertx.ext.web.client.HttpResponse) Pump(io.vertx.core.streams.Pump) VertxException(io.vertx.core.VertxException) URISyntaxException(java.net.URISyntaxException) HttpClientRequest(io.vertx.core.http.HttpClientRequest) JsonObject(io.vertx.core.json.JsonObject) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 2 with UnpooledByteBufAllocator

use of io.netty.buffer.UnpooledByteBufAllocator in project netty by netty.

the class HttpPostRequestDecoderTest method testNoZeroOut.

// See https://github.com/netty/netty/issues/1848
@Test
public void testNoZeroOut() throws Exception {
    final String boundary = "E832jQp_Rq2ErFmAduHSR8YlMSm0FCY";
    final DefaultHttpDataFactory aMemFactory = new DefaultHttpDataFactory(false);
    DefaultHttpRequest aRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost");
    aRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    aRequest.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    HttpPostRequestDecoder aDecoder = new HttpPostRequestDecoder(aMemFactory, aRequest);
    final String aData = "some data would be here. the data should be long enough that it " + "will be longer than the original buffer length of 256 bytes in " + "the HttpPostRequestDecoder in order to trigger the issue. Some more " + "data just to be on the safe side.";
    final String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"root\"\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + aData + "\r\n" + "--" + boundary + "--\r\n";
    byte[] aBytes = body.getBytes();
    int split = 125;
    ByteBufAllocator aAlloc = new UnpooledByteBufAllocator(true);
    ByteBuf aSmallBuf = aAlloc.heapBuffer(split, split);
    ByteBuf aLargeBuf = aAlloc.heapBuffer(aBytes.length - split, aBytes.length - split);
    aSmallBuf.writeBytes(aBytes, 0, split);
    aLargeBuf.writeBytes(aBytes, split, aBytes.length - split);
    aDecoder.offer(new DefaultHttpContent(aSmallBuf));
    aDecoder.offer(new DefaultHttpContent(aLargeBuf));
    aDecoder.offer(LastHttpContent.EMPTY_LAST_CONTENT);
    assertTrue(aDecoder.hasNext(), "Should have a piece of data");
    InterfaceHttpData aDecodedData = aDecoder.next();
    assertEquals(InterfaceHttpData.HttpDataType.Attribute, aDecodedData.getHttpDataType());
    Attribute aAttr = (Attribute) aDecodedData;
    assertEquals(aData, aAttr.getValue());
    aDecodedData.release();
    aDecoder.destroy();
    aSmallBuf.release();
    aLargeBuf.release();
}
Also used : UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)2 UnpooledByteBufAllocator (io.netty.buffer.UnpooledByteBufAllocator)2 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)1 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)1 HttpContent (io.netty.handler.codec.http.HttpContent)1 QueryStringEncoder (io.netty.handler.codec.http.QueryStringEncoder)1 HttpPostRequestEncoder (io.netty.handler.codec.http.multipart.HttpPostRequestEncoder)1 Context (io.vertx.core.Context)1 MultiMap (io.vertx.core.MultiMap)1 VertxException (io.vertx.core.VertxException)1 Buffer (io.vertx.core.buffer.Buffer)1 HttpClientRequest (io.vertx.core.http.HttpClientRequest)1 HttpClientResponse (io.vertx.core.http.HttpClientResponse)1 RequestOptions (io.vertx.core.http.RequestOptions)1 JsonObject (io.vertx.core.json.JsonObject)1 Pump (io.vertx.core.streams.Pump)1 ReadStream (io.vertx.core.streams.ReadStream)1 HttpResponse (io.vertx.ext.web.client.HttpResponse)1