Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix File handling as a JAX-RS body parameter #35659

Merged
merged 2 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,20 @@
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.CompletionCallback;
import jakarta.ws.rs.container.ConnectionCallback;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import org.jboss.resteasy.reactive.common.providers.serialisers.AbstractJsonMessageBodyReader;
import org.jboss.resteasy.reactive.server.jackson.JacksonBasicMessageBodyReader;
import org.jboss.resteasy.reactive.server.jaxrs.HttpHeadersImpl;
import org.jboss.resteasy.reactive.server.spi.ContentType;
import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
import org.jboss.resteasy.reactive.server.spi.ServerHttpResponse;
Expand Down Expand Up @@ -266,6 +269,11 @@ public ResteasyReactiveResourceInfo getResteasyReactiveResourceInfo() {
return null;
}

@Override
public HttpHeaders getRequestHeaders() {
return new HttpHeadersImpl(Collections.emptyList());
}

@Override
public void abortWith(Response response) {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.quarkus.resteasy.reactive.server.deployment;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.quarkus.builder.item.MultiBuildItem;

public final class BuiltInReaderOverrideBuildItem extends MultiBuildItem {

private final String readerClassName;
private final String overrideClassName;

public BuiltInReaderOverrideBuildItem(String readerClassName, String overrideClassName) {
this.readerClassName = readerClassName;
this.overrideClassName = overrideClassName;
}

public String getReaderClassName() {
return readerClassName;
}

public String getOverrideClassName() {
return overrideClassName;
}

public static Map<String, String> toMap(List<BuiltInReaderOverrideBuildItem> items) {
if (items.isEmpty()) {
return Collections.emptyMap();
}
Map<String, String> result = new HashMap<>();
for (BuiltInReaderOverrideBuildItem item : items) {
String previousOverride = result.put(item.getReaderClassName(), item.getOverrideClassName());
if (previousOverride != null) {
throw new IllegalStateException(
"Providing multiple BuiltInReaderOverrideBuildItem for the same readerClassName is not supported");
}
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -110,6 +111,7 @@
import org.jboss.resteasy.reactive.server.processor.scanning.ResponseHeaderMethodScanner;
import org.jboss.resteasy.reactive.server.processor.scanning.ResponseStatusMethodScanner;
import org.jboss.resteasy.reactive.server.processor.util.ResteasyReactiveServerDotNames;
import org.jboss.resteasy.reactive.server.providers.serialisers.ServerFileBodyHandler;
import org.jboss.resteasy.reactive.server.spi.RuntimeConfiguration;
import org.jboss.resteasy.reactive.server.spi.ServerRestHandler;
import org.jboss.resteasy.reactive.server.vertx.serializers.ServerMutinyAsyncFileMessageBodyWriter;
Expand Down Expand Up @@ -165,6 +167,8 @@
import io.quarkus.resteasy.reactive.common.deployment.ServerDefaultProducesHandlerBuildItem;
import io.quarkus.resteasy.reactive.common.runtime.ResteasyReactiveConfig;
import io.quarkus.resteasy.reactive.server.EndpointDisabled;
import io.quarkus.resteasy.reactive.server.runtime.QuarkusServerFileBodyHandler;
import io.quarkus.resteasy.reactive.server.runtime.QuarkusServerPathBodyHandler;
import io.quarkus.resteasy.reactive.server.runtime.ResteasyReactiveInitialiser;
import io.quarkus.resteasy.reactive.server.runtime.ResteasyReactiveRecorder;
import io.quarkus.resteasy.reactive.server.runtime.ResteasyReactiveRuntimeRecorder;
Expand Down Expand Up @@ -1021,6 +1025,16 @@ private static String determineHandledGenericTypeOfProviderInterface(Class<?> pr
}
}

@BuildStep
public void fileHandling(BuildProducer<BuiltInReaderOverrideBuildItem> overrideProducer,
BuildProducer<MessageBodyReaderBuildItem> readerProducer) {
overrideProducer.produce(new BuiltInReaderOverrideBuildItem(ServerFileBodyHandler.class.getName(),
QuarkusServerFileBodyHandler.class.getName()));
readerProducer.produce(
new MessageBodyReaderBuildItem(QuarkusServerPathBodyHandler.class.getName(), Path.class.getName(), List.of(
MediaType.WILDCARD), RuntimeType.SERVER, true, Priorities.USER));
}

@BuildStep
@Record(value = ExecutionTime.STATIC_INIT, useIdentityComparisonForParameters = false)
public void serverSerializers(ResteasyReactiveRecorder recorder,
Expand All @@ -1030,6 +1044,7 @@ public void serverSerializers(ResteasyReactiveRecorder recorder,
List<MessageBodyWriterBuildItem> additionalMessageBodyWriters,
List<MessageBodyReaderOverrideBuildItem> messageBodyReaderOverrideBuildItems,
List<MessageBodyWriterOverrideBuildItem> messageBodyWriterOverrideBuildItems,
List<BuiltInReaderOverrideBuildItem> builtInReaderOverrideBuildItems,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<ServerSerialisersBuildItem> serverSerializersProducer) {

Expand All @@ -1047,11 +1062,16 @@ public void serverSerializers(ResteasyReactiveRecorder recorder,
reflectiveClass.produce(ReflectiveClassBuildItem.builder(builtinWriter.writerClass.getName())
.build());
}
Map<String, String> builtInReaderOverrides = BuiltInReaderOverrideBuildItem.toMap(builtInReaderOverrideBuildItems);
for (Serialisers.BuiltinReader builtinReader : ServerSerialisers.BUILTIN_READERS) {
registerReader(recorder, serialisers, builtinReader.entityClass.getName(), builtinReader.readerClass.getName(),
String effectiveReaderClassName = builtinReader.readerClass.getName();
if (builtInReaderOverrides.containsKey(effectiveReaderClassName)) {
effectiveReaderClassName = builtInReaderOverrides.get(effectiveReaderClassName);
}
registerReader(recorder, serialisers, builtinReader.entityClass.getName(), effectiveReaderClassName,
beanContainerBuildItem.getValue(),
builtinReader.mediaType, builtinReader.constraint);
reflectiveClass.produce(ReflectiveClassBuildItem.builder(builtinReader.readerClass.getName())
reflectiveClass.produce(ReflectiveClassBuildItem.builder(effectiveReaderClassName)
.build());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import static org.awaitility.Awaitility.await;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.concurrent.Callable;
Expand Down Expand Up @@ -40,4 +42,8 @@ public Boolean call() {
}
});
}

protected String fileSizeAsStr(File file) throws IOException {
return "" + Files.readAllBytes(file.toPath()).length;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤢

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package io.quarkus.resteasy.reactive.server.test.multipart;

import static org.hamcrest.CoreMatchers.equalTo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.Supplier;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;

public class FileInputWithDeleteTest extends AbstractMultipartTest {

private static final java.nio.file.Path uploadDir = Paths.get("file-uploads");

@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class)
.addAsResource(new StringAsset(
"quarkus.http.body.uploads-directory="
+ uploadDir.toString() + "\n"),
"application.properties");
}

});

private final File HTML_FILE = new File("./src/test/resources/test.html");
private final File HTML_FILE2 = new File("./src/test/resources/test2.html");

@Test
public void test() throws IOException {
RestAssured.given()
.contentType("application/octet-stream")
.body(HTML_FILE)
.when()
.post("/test")
.then()
.statusCode(200)
.body(equalTo(fileSizeAsStr(HTML_FILE)));

awaitUploadDirectoryToEmpty(uploadDir);

RestAssured.given()
.contentType("application/octet-stream")
.body(HTML_FILE2)
.when()
.post("/test")
.then()
.statusCode(200)
.body(equalTo(fileSizeAsStr(HTML_FILE2)));

awaitUploadDirectoryToEmpty(uploadDir);
}

@Path("test")
public static class Resource {

@POST
@Consumes("application/octet-stream")
public long size(File file) throws IOException {
return Files.size(file.toPath());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package io.quarkus.resteasy.reactive.server.test.multipart;

import static org.hamcrest.CoreMatchers.equalTo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.Supplier;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;

public class FileInputWithoutDeleteTest extends AbstractMultipartTest {

private static final java.nio.file.Path uploadDir = Paths.get("file-uploads");

@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class)
.addAsResource(new StringAsset(
// keep the files around so we can assert the outcome
"quarkus.http.body.delete-uploaded-files-on-end=false\nquarkus.http.body.uploads-directory="
+ uploadDir.toString() + "\n"),
"application.properties");
}

});

private final File HTML_FILE = new File("./src/test/resources/test.html");
private final File HTML_FILE2 = new File("./src/test/resources/test2.html");

@BeforeEach
public void assertEmptyUploads() {
Assertions.assertTrue(isDirectoryEmpty(uploadDir));
}

@AfterEach
public void clearDirectory() {
clearDirectory(uploadDir);
}

@Test
public void test() throws IOException {
RestAssured.given()
.contentType("application/octet-stream")
.body(HTML_FILE)
.when()
.post("/test")
.then()
.statusCode(200)
.body(equalTo(fileSizeAsStr(HTML_FILE)));

// ensure that the 3 uploaded files where created on disk
Assertions.assertEquals(1, uploadDir.toFile().listFiles().length);

RestAssured.given()
.contentType("application/octet-stream")
.body(HTML_FILE2)
.when()
.post("/test")
.then()
.statusCode(200)
.body(equalTo(fileSizeAsStr(HTML_FILE2)));

// ensure that the 3 uploaded files where created on disk
Assertions.assertEquals(2, uploadDir.toFile().listFiles().length);
}

@Path("test")
public static class Resource {

@POST
@Consumes("application/octet-stream")
public long size(File file) throws IOException {
return Files.size(file.toPath());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
Expand Down Expand Up @@ -164,8 +163,4 @@ private String filePath(File file) {
return file.toPath().toAbsolutePath().toString();
}

private String fileSizeAsStr(File file) throws IOException {
return "" + Files.readAllBytes(file.toPath()).length;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Supplier;
Expand Down Expand Up @@ -245,8 +244,4 @@ private String filePath(File file) {
return file.toPath().toAbsolutePath().toString();
}

private String fileSizeAsStr(File file) throws IOException {
return "" + Files.readAllBytes(file.toPath()).length;
}

}
Loading
Loading