Search in sources :

Example 11 with MultipartForm

use of io.vertx.ext.web.multipart.MultipartForm in project vertx-web by vert-x3.

the class HttpRequestImpl method sendForm.

@Override
public void sendForm(MultiMap body, String charset, Handler<AsyncResult<HttpResponse<T>>> handler) {
    MultipartForm parts = MultipartForm.create();
    for (Map.Entry<String, String> attribute : body) {
        parts.attribute(attribute.getKey(), attribute.getValue());
    }
    parts.setCharset(charset);
    send("application/x-www-form-urlencoded", parts, handler);
}
Also used : MultipartForm(io.vertx.ext.web.multipart.MultipartForm) MultiMap(io.vertx.core.MultiMap) Map(java.util.Map)

Example 12 with MultipartForm

use of io.vertx.ext.web.multipart.MultipartForm in project vertx-web by vert-x3.

the class HttpContext method handleCreateRequest.

private void handleCreateRequest() {
    requestPromise = Promise.promise();
    if (body != null || "application/json".equals(contentType)) {
        if (body instanceof MultipartForm) {
            MultipartFormUpload multipartForm;
            try {
                boolean multipart = "multipart/form-data".equals(contentType);
                HttpPostRequestEncoder.EncoderMode encoderMode = this.request.multipartMixed ? HttpPostRequestEncoder.EncoderMode.RFC1738 : HttpPostRequestEncoder.EncoderMode.HTML5;
                multipartForm = new MultipartFormUpload(context, (MultipartForm) this.body, multipart, encoderMode);
                this.body = multipartForm;
            } catch (Exception e) {
                fail(e);
                return;
            }
            for (String headerName : this.request.headers().names()) {
                requestOptions.putHeader(headerName, this.request.headers().get(headerName));
            }
            multipartForm.headers().forEach(header -> {
                requestOptions.putHeader(header.getKey(), header.getValue());
            });
        }
        if (body instanceof ReadStream<?>) {
            ReadStream<Buffer> stream = (ReadStream<Buffer>) body;
            // Shouldn't this be called in an earlier phase ?
            Pipe<Buffer> pipe = stream.pipe();
            requestPromise.future().onComplete(ar -> {
                if (ar.succeeded()) {
                    HttpClientRequest req = ar.result();
                    if (this.request.headers == null || !this.request.headers.contains(HttpHeaders.CONTENT_LENGTH)) {
                        req.setChunked(true);
                    }
                    pipe.endOnFailure(false);
                    pipe.to(req, ar2 -> {
                        clientRequest = null;
                        if (ar2.failed()) {
                            req.reset(0L, ar2.cause());
                        }
                    });
                    if (body instanceof MultipartFormUpload) {
                        ((MultipartFormUpload) body).run();
                    }
                } else {
                    // Test this
                    clientRequest = null;
                    pipe.close();
                }
            });
        } else {
            Buffer buffer;
            if (body instanceof Buffer) {
                buffer = (Buffer) body;
            } else if (body instanceof JsonObject) {
                buffer = Buffer.buffer(((JsonObject) body).encode());
            } else {
                buffer = Buffer.buffer(Json.encode(body));
            }
            requestOptions.putHeader(HttpHeaders.CONTENT_LENGTH, "" + buffer.length());
            requestPromise.future().onSuccess(request -> {
                clientRequest = null;
                request.end(buffer);
            });
        }
    } else {
        requestPromise.future().onSuccess(request -> {
            clientRequest = null;
            request.end();
        });
    }
    client.request(requestOptions).onComplete(ar1 -> {
        if (ar1.succeeded()) {
            sendRequest(ar1.result());
        } else {
            fail(ar1.cause());
            requestPromise.fail(ar1.cause());
        }
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) JsonObject(io.vertx.core.json.JsonObject) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) URISyntaxException(java.net.URISyntaxException) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ReadStream(io.vertx.core.streams.ReadStream)

Example 13 with MultipartForm

use of io.vertx.ext.web.multipart.MultipartForm in project vertx-web by vert-x3.

the class WebClientTest method testFileUploads.

@Test
public void testFileUploads() throws Exception {
    server.requestHandler(req -> {
        fail("Should not be called");
    });
    startServer();
    HttpRequest<Buffer> builder = webClient.post("somepath");
    MultipartForm form = MultipartForm.create().textFileUpload("file", "nonexistentFilename", "nonexistentPathname", "text/plain");
    builder.sendMultipartForm(form, onFailure(err -> {
        assertEquals(err.getClass(), HttpPostRequestEncoder.ErrorDataEncoderException.class);
        complete();
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) AsyncFile(io.vertx.core.file.AsyncFile) CoreMatchers(org.hamcrest.CoreMatchers) ResponsePredicate(io.vertx.ext.web.client.predicate.ResponsePredicate) java.util(java.util) ErrorConverter(io.vertx.ext.web.client.predicate.ErrorConverter) URLDecoder(java.net.URLDecoder) io.vertx.core(io.vertx.core) DecodeException(io.vertx.core.json.DecodeException) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) BodyCodec(io.vertx.ext.web.codec.BodyCodec) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResponsePredicateResult(io.vertx.ext.web.client.predicate.ResponsePredicateResult) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) ReadStream(io.vertx.core.streams.ReadStream) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) ConnectException(java.net.ConnectException) SocketAddress(io.vertx.core.net.SocketAddress) ProxyOptions(io.vertx.core.net.ProxyOptions) UsernamePasswordCredentials(io.vertx.ext.auth.authentication.UsernamePasswordCredentials) OpenOptions(io.vertx.core.file.OpenOptions) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) Test(org.junit.Test) io.vertx.core.http(io.vertx.core.http) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) HtdigestCredentials(io.vertx.ext.auth.htdigest.HtdigestCredentials) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) TokenCredentials(io.vertx.ext.auth.authentication.TokenCredentials) Repeat(io.vertx.test.core.Repeat) URLEncoder(java.net.URLEncoder) Buffer(io.vertx.core.buffer.Buffer) ProxyType(io.vertx.core.net.ProxyType) NetServer(io.vertx.core.net.NetServer) WineAndCheese(io.vertx.ext.web.client.jackson.WineAndCheese) Cert(io.vertx.test.tls.Cert) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) Test(org.junit.Test)

Example 14 with MultipartForm

use of io.vertx.ext.web.multipart.MultipartForm in project vertx-web by vert-x3.

the class WebClientTest method testFileUploadWhenFileDoesNotExist.

@Test
public void testFileUploadWhenFileDoesNotExist() {
    HttpRequest<Buffer> builder = webClient.post("somepath");
    MultipartForm form = MultipartForm.create().textFileUpload("file", "nonexistentFilename", "nonexistentPathname", "text/plain");
    builder.sendMultipartForm(form, onFailure(err -> {
        assertEquals(err.getClass(), HttpPostRequestEncoder.ErrorDataEncoderException.class);
        assertEquals(err.getCause().getClass(), FileNotFoundException.class);
        complete();
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) AsyncFile(io.vertx.core.file.AsyncFile) CoreMatchers(org.hamcrest.CoreMatchers) ResponsePredicate(io.vertx.ext.web.client.predicate.ResponsePredicate) java.util(java.util) ErrorConverter(io.vertx.ext.web.client.predicate.ErrorConverter) URLDecoder(java.net.URLDecoder) io.vertx.core(io.vertx.core) DecodeException(io.vertx.core.json.DecodeException) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) BodyCodec(io.vertx.ext.web.codec.BodyCodec) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResponsePredicateResult(io.vertx.ext.web.client.predicate.ResponsePredicateResult) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) ReadStream(io.vertx.core.streams.ReadStream) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) ConnectException(java.net.ConnectException) SocketAddress(io.vertx.core.net.SocketAddress) ProxyOptions(io.vertx.core.net.ProxyOptions) UsernamePasswordCredentials(io.vertx.ext.auth.authentication.UsernamePasswordCredentials) OpenOptions(io.vertx.core.file.OpenOptions) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) Test(org.junit.Test) io.vertx.core.http(io.vertx.core.http) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) HtdigestCredentials(io.vertx.ext.auth.htdigest.HtdigestCredentials) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) TokenCredentials(io.vertx.ext.auth.authentication.TokenCredentials) Repeat(io.vertx.test.core.Repeat) URLEncoder(java.net.URLEncoder) Buffer(io.vertx.core.buffer.Buffer) ProxyType(io.vertx.core.net.ProxyType) NetServer(io.vertx.core.net.NetServer) WineAndCheese(io.vertx.ext.web.client.jackson.WineAndCheese) Cert(io.vertx.test.tls.Cert) FileNotFoundException(java.io.FileNotFoundException) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) Test(org.junit.Test)

Example 15 with MultipartForm

use of io.vertx.ext.web.multipart.MultipartForm in project vertx-web by vert-x3.

the class RouterBuilderIntegrationTest method testComplexMultipart.

@Timeout(2000)
@Test
public void testComplexMultipart(Vertx vertx, VertxTestContext testContext) {
    Checkpoint checkpoint = testContext.checkpoint(2);
    loadBuilderAndStartServer(vertx, VALIDATION_SPEC, testContext, routerBuilder -> {
        routerBuilder.setOptions(HANDLERS_TESTS_OPTIONS);
        routerBuilder.operation("complexMultipartRequest").handler(routingContext -> {
            RequestParameters params = routingContext.get("parsedParameters");
            if (params.body() == null) {
                routingContext.response().setStatusCode(200).end();
            } else {
                routingContext.response().putHeader("content-type", "application/json").setStatusCode(200).end(params.body().getJsonObject().toBuffer());
            }
        });
    }).onComplete(h -> {
        JsonObject pet = new JsonObject();
        pet.put("id", 14612);
        pet.put("name", "Willy");
        MultipartForm form = MultipartForm.create().textFileUpload("param1", "random.txt", "src/test/resources/random.txt", "text/plain").attribute("param2", pet.encode()).textFileUpload("param3", "random.csv", "src/test/resources/random.txt", "text/csv").attribute("param4", "1.2").attribute("param4", "5.2").attribute("param4", "6.2").attribute("param5", "2").binaryFileUpload("param1NotRealBinary", "random-file", "src/test/resources/random-file", "text/plain").binaryFileUpload("param1Binary", "random-file", "src/test/resources/random-file", "application/octet-stream");
        JsonObject expected = new JsonObject().put("param2", pet).put("param4", new JsonArray().add(1.2).add(5.2).add(6.2)).put("param5", 2);
        testRequest(client, HttpMethod.POST, "/multipart/complex").expect(statusCode(200)).expect(jsonBodyResponse(expected)).sendMultipartForm(form, testContext, checkpoint);
        testRequest(client, HttpMethod.POST, "/multipart/complex").expect(statusCode(200)).send(testContext, checkpoint);
    });
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) Arrays(java.util.Arrays) RequestParameters(io.vertx.ext.web.validation.RequestParameters) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) MultiMap(io.vertx.core.MultiMap) Router(io.vertx.ext.web.Router) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) BodyProcessorException(io.vertx.ext.web.validation.BodyProcessorException) Timeout(io.vertx.junit5.Timeout) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) ParameterLocation(io.vertx.ext.web.validation.impl.ParameterLocation) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) JsonObject(io.vertx.core.json.JsonObject) RequestParameter(io.vertx.ext.web.validation.RequestParameter) Route(io.vertx.ext.web.Route) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) StaticHandler(io.vertx.ext.web.handler.StaticHandler) Vertx(io.vertx.core.Vertx) TestRequest(io.vertx.ext.web.validation.testutils.TestRequest) HttpHeaders(io.vertx.core.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Stream(java.util.stream.Stream) ValidationTestUtils(io.vertx.ext.web.validation.testutils.ValidationTestUtils) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) ParameterProcessorException(io.vertx.ext.web.validation.ParameterProcessorException) Condition(org.assertj.core.api.Condition) Checkpoint(io.vertx.junit5.Checkpoint) Pattern(java.util.regex.Pattern) Handler(io.vertx.core.Handler) JsonArray(io.vertx.core.json.JsonArray) Checkpoint(io.vertx.junit5.Checkpoint) JsonObject(io.vertx.core.json.JsonObject) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) RequestParameters(io.vertx.ext.web.validation.RequestParameters) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Aggregations

MultipartForm (io.vertx.ext.web.multipart.MultipartForm)15 JsonObject (io.vertx.core.json.JsonObject)10 Buffer (io.vertx.core.buffer.Buffer)9 JsonArray (io.vertx.core.json.JsonArray)7 Test (org.junit.Test)7 MultiMap (io.vertx.core.MultiMap)5 ArrayList (java.util.ArrayList)5 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)3 QueryStringEncoder (io.netty.handler.codec.http.QueryStringEncoder)3 HttpPostRequestEncoder (io.netty.handler.codec.http.multipart.HttpPostRequestEncoder)3 Future (io.vertx.core.Future)3 Handler (io.vertx.core.Handler)3 Vertx (io.vertx.core.Vertx)3 HttpHeaders (io.vertx.core.http.HttpHeaders)3 HttpMethod (io.vertx.core.http.HttpMethod)3 ReadStream (io.vertx.core.streams.ReadStream)3 Route (io.vertx.ext.web.Route)3 Router (io.vertx.ext.web.Router)3 RoutingContext (io.vertx.ext.web.RoutingContext)3 RequestParameters (io.vertx.ext.web.api.RequestParameters)3