Skip to content
Draft
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 @@ -18,6 +18,7 @@
import io.micronaut.context.annotation.Executable;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.inject.ast.ClassElement;
import io.micronaut.inject.ast.KotlinParameterElement;
import io.micronaut.inject.ast.MethodElement;
import io.micronaut.inject.ast.ParameterElement;
Expand Down Expand Up @@ -48,7 +49,8 @@ public TypeElementQuery query() {
@Override
public void visitMethod(MethodElement element, VisitorContext context) {
for (ParameterElement parameter : element.getParameters()) {
if (parameter.getType().isPrimitive() && parameter.isNullable()
ClassElement type = parameter.getType();
if (type.isPrimitive() && !type.isArray() && parameter.isNullable()
&& !(parameter instanceof KotlinParameterElement kotlinParameterElement && kotlinParameterElement.hasDefault())) {
context.warn("@Nullable on primitive types will allow the method to be executed at runtime with null values, causing an exception", parameter);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@

import io.micronaut.core.annotation.Internal;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.convert.ConversionContext;
import io.micronaut.core.convert.ConversionError;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.core.convert.value.ConvertibleValues;
import io.micronaut.core.execution.ExecutionFlow;
import io.micronaut.core.io.buffer.ByteBuffer;
import io.micronaut.core.io.buffer.ReferenceCounted;
import io.micronaut.core.propagation.PropagatedContext;
import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MediaType;
Expand Down Expand Up @@ -61,12 +61,13 @@

@Internal
final class NettyBodyAnnotationBinder<T> extends DefaultBodyAnnotationBinder<T> {

final NettyHttpServerConfiguration httpServerConfiguration;
final MessageBodyHandlerRegistry bodyHandlerRegistry;

NettyBodyAnnotationBinder(ConversionService conversionService,
NettyHttpServerConfiguration httpServerConfiguration,
MessageBodyHandlerRegistry bodyHandlerRegistry) {
MessageBodyHandlerRegistry bodyHandlerRegistry) {
super(conversionService);
this.httpServerConfiguration = httpServerConfiguration;
this.bodyHandlerRegistry = bodyHandlerRegistry;
Expand All @@ -91,10 +92,10 @@ protected BindingResult<ConvertibleValues<?>> bindFullBodyConvertibleValues(Http
if (existing != null) {
return existing;
} else {
//noinspection unchecked
BindingResult<ConvertibleValues<?>> result = (BindingResult<ConvertibleValues<?>>) bindFullBody((ArgumentConversionContext<T>) ConversionContext.of(ConvertibleValues.class), nhr);
nhr.convertibleBody = result;
return result;
Argument<T> objectArgument = (Argument) Argument.of(ConvertibleValues.class);
BindingResult<T> result = bindFullBodyNullable(objectArgument, nhr);
nhr.convertibleBody = (BindingResult<ConvertibleValues<?>>) result;
return (BindingResult<ConvertibleValues<?>>) result;
}
}

Expand All @@ -103,7 +104,7 @@ public BindingResult<T> bindFullBody(ArgumentConversionContext<T> context, HttpR
if (!(source instanceof NettyHttpRequest<?> nhr)) {
return super.bindFullBody(context, source);
}
if (nhr.byteBody().expectedLength().orElse(-1) == 0) {
if (context.getArgument().isNullable() && nhr.byteBody().expectedLength().orElse(-1) == 0) {
return BindingResult.empty();
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ public NettyServerRequestBinderRegistry(ConversionService conversionService,
internalRequestBinderRegistry.addArgumentBinder(new MultipartBodyArgumentBinder(
httpServerConfiguration
));
internalRequestBinderRegistry.addArgumentBinder(new NettyInputStreamBodyBinder());
NettyStreamingFileUpload.Factory fileUploadFactory = new NettyStreamingFileUpload.Factory(
httpServerConfiguration.get().getMultipart(),
executorService.get()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
/*
* Copyright 2017-2023 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.server.tck.tests.bodyreadwrite;

import io.micronaut.context.annotation.Requires;
import io.micronaut.core.annotation.Introspected;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Consumes;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.annotation.Produces;
import io.micronaut.http.tck.AssertionUtils;
import io.micronaut.http.tck.BodyAssertion;
import io.micronaut.http.tck.HttpResponseAssertion;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static io.micronaut.http.tck.TestScenario.asserts;

@SuppressWarnings({
"java:S5960", // We're allowed assertions, as these are used in tests only
"checkstyle:MissingJavadocType",
"checkstyle:DesignForExtension"
})
public class EmptyJsonBodyTest {
public static final String SPEC_NAME = "EmptyJsonBodyTest";

private Map<String, Object> getConfiguration() {
return Map.of(
"micronaut.server.not-found-on-missing-body", "false"
);
}

@Test
void stringBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/string", "FooBar").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body("FooBar")
.build()));
}

@Test
void bytesBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/bytes", "FooBar").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body("FooBar")
.build()));
}

@Test
void ioBody() throws IOException {
asserts(SPEC_NAME,

Check failure on line 80 in http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/bodyreadwrite/EmptyJsonBodyTest.java

View workflow job for this annotation

GitHub Actions / Java CI / Test Report (21)

EmptyJsonBodyTest.ioBody()

org.opentest4j.AssertionFailedError: Unexpected exception thrown: io.micronaut.http.client.exceptions.ReadTimeoutException: Read Timeout
Raw output
org.opentest4j.AssertionFailedError: Unexpected exception thrown: io.micronaut.http.client.exceptions.ReadTimeoutException: Read Timeout
	at app//org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152)
	at app//org.junit.jupiter.api.AssertDoesNotThrow.createAssertionFailedError(AssertDoesNotThrow.java:84)
	at app//org.junit.jupiter.api.AssertDoesNotThrow.assertDoesNotThrow(AssertDoesNotThrow.java:75)
	at app//org.junit.jupiter.api.AssertDoesNotThrow.assertDoesNotThrow(AssertDoesNotThrow.java:58)
	at app//org.junit.jupiter.api.Assertions.assertDoesNotThrow(Assertions.java:3259)
	at app//io.micronaut.http.tck.AssertionUtils.assertDoesNotThrow(AssertionUtils.java:117)
	at app//io.micronaut.http.server.tck.tests.bodyreadwrite.EmptyJsonBodyTest.lambda$ioBody$2(EmptyJsonBodyTest.java:83)
	at app//io.micronaut.http.tck.TestScenario.run(TestScenario.java:118)
	at app//io.micronaut.http.tck.TestScenario$Builder.run(TestScenario.java:201)
	at app//io.micronaut.http.tck.TestScenario.asserts(TestScenario.java:67)
	at app//io.micronaut.http.server.tck.tests.bodyreadwrite.EmptyJsonBodyTest.ioBody(EmptyJsonBodyTest.java:80)
	at [email protected]/java.lang.reflect.Method.invoke(Method.java:580)
	at [email protected]/java.util.ArrayList.forEach(ArrayList.java:1596)
	at [email protected]/java.util.ArrayList.forEach(ArrayList.java:1596)
	Suppressed: java.lang.RuntimeException: Detected a resource leak. Please check logs
		at io.micronaut.http.tck.netty.TestLeakDetector.stopTrackingAndReportLeaks(TestLeakDetector.java:100)
		at io.micronaut.http.tck.netty.LeakDetectionExtension.afterEach(LeakDetectionExtension.java:51)
		... 2 more
Caused by: io.micronaut.http.client.exceptions.ReadTimeoutException: Read Timeout
	at app//io.micronaut.http.client.exceptions.ReadTimeoutException.<clinit>(ReadTimeoutException.java:26)
	at app//io.micronaut.http.client.netty.DefaultHttpClient.handleResponseError(DefaultHttpClient.java:2073)
	at app//io.micronaut.http.client.netty.DefaultHttpClient.lambda$exchange$8(DefaultHttpClient.java:919)
	at app//io.micronaut.core.execution.ImperativeExecutionFlowImpl.onErrorResume(ImperativeExecutionFlowImpl.java:112)
	at app//io.micronaut.core.execution.DelayedExecutionFlowImpl$OnErrorResume.apply(DelayedExecutionFlowImpl.java:393)
	at app//io.micronaut.core.execution.DelayedExecutionFlowImpl.work(DelayedExecutionFlowImpl.java:58)
	at app//io.micronaut.core.execution.DelayedExecutionFlowImpl.completeLazy(DelayedExecutionFlowImpl.java:80)
	at app//io.micronaut.core.execution.DelayedExecutionFlowImpl.completeExceptionally(DelayedExecutionFlowImpl.java:104)
	at app//io.micronaut.http.body.stream.BaseSharedBuffer.error(BaseSharedBuffer.java:428)
	at app//io.micronaut.http.client.netty.Http1ResponseHandler$UnbufferedContent.exceptionCaught(Http1ResponseHandler.java:286)
	at app//io.micronaut.http.client.netty.Http1ResponseHandler.exceptionCaught(Http1ResponseHandler.java:90)
	at app//io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:289)
	at app//io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:271)
	at app//io.netty.channel.DefaultChannelPipeline$HeadContext.exceptionCaught(DefaultChannelPipeline.java:1396)
	at app//io.netty.channel.DefaultChannelPipeline.fireExceptionCaught(DefaultChannelPipeline.java:890)
	at app//io.netty.handler.codec.http2.Http2MultiplexHandler$2.visit(Http2MultiplexHandler.java:321)
	at app//io.netty.handler.codec.http2.Http2FrameCodec$1.visit(Http2FrameCodec.java:201)
	at app//io.netty.handler.codec.http2.DefaultHttp2Connection$ActiveStreams.forEachActiveStream(DefaultHttp2Connection.java:1014)
	at app//io.netty.handler.codec.http2.DefaultHttp2Connection.forEachActiveStream(DefaultHttp2Connection.java:207)
	at app//io.netty.handler.codec.http2.Http2FrameCodec.forEachActiveStream(Http2FrameCodec.java:197)
	at app//io.netty.handler.codec.http2.Http2ChannelDuplexHandler.forEachActiveStream(Http2ChannelDuplexHandler.java:81)
	at app//io.netty.handler.codec.http2.Http2MultiplexHandler.fireExceptionCaughtForActiveStream(Http2MultiplexHandler.java:316)
	at app//io.netty.handler.codec.http2.Http2MultiplexHandler.exceptionCaught(Http2MultiplexHandler.java:305)
	at app//io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:289)
	at app//io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:271)
	at app//io.netty.channel.ChannelInboundHandlerAdapter.exceptionCaught(ChannelInboundHandlerAdapter.java:143)
	at app//io.netty.handler.codec.http2.Http2ConnectionHandler.exceptionCaught(Http2ConnectionHandler.java:580)
	at app//io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:289)
	at app//io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:271)
	at app//io.netty.handler.ssl.SslHandler.exceptionCaught(SslHandler.java:1238)
	at app//io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:289)
	at app//io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:271)
	at app//io.netty.channel.DefaultChannelPipeline$HeadContext.exceptionCaught(DefaultChannelPipeline.java:1396)
	at app//io.netty.channel.DefaultChannelPipeline.fireExceptionCaught(DefaultChannelPipeline.java:890)
	at app//io.micronaut.http.client.netty.ConnectionManager$PoolHolder$Http2ConnectionHolder.fireReadTimeout(ConnectionManager.java:1606)
	at app//io.micronaut.http.client.netty.ConnectionManager$PoolHolder$ConnectionHolder$1.readTimedOut(ConnectionManager.java:1334)
	at app//io.netty.handler.timeout.ReadTimeoutHandler.channelIdle(ReadTimeoutHandler.java:90)
	at app//io.netty.handler.timeout.IdleStateHandler$ReaderIdleTimeoutTask.run(IdleStateHandler.java:522)
	at app//io.netty.handler.timeout.IdleStateHandler$AbstractIdleTask.run(IdleStateHandler.java:494)
	at app//io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98)
	at app//io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:160)
	at app//io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java:148)
	at app//io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:141)
	at app//io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:507)
	at app//io.netty.channel.SingleThreadIoEventLoop.run(SingleThreadIoEventLoop.java:183)
	at app//io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:1073)
	at app//io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at app//io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
	at [email protected]/java.lang.Thread.run(Thread.java:1583)
getConfiguration(),
HttpRequest.POST("/myController/io", "FooBar").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body("FooBar")
.build()));
}

@Test
void beanEmptyBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/bean", "").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.NO_CONTENT)
.body(BodyAssertion.IS_MISSING)
.build()));
}

@Test
void stringEmptyBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/string", "").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body(BodyAssertion.IS_MISSING)
.build()));
}

@Test
void bytesEmptyBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/bytes", "").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body(BodyAssertion.IS_MISSING)
.build()));
}

@Test
void ioEmptyBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/io", "").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body(BodyAssertion.IS_MISSING)
.build()));
}

@Test
void stringNullableBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/stringNullable", "").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body("<null>")
.build()));
}

@Test
void bytesNullableBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/bytesNullable", "").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body("<null>")
.build()));
}

@Test
void ioNullableEmptyBody() throws IOException {
asserts(SPEC_NAME,
getConfiguration(),
HttpRequest.POST("/myController/ioNullable", "").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body("<null>")
.build()));
}

@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Controller("/myController")
@Requires(property = "spec.name", value = SPEC_NAME)
static class MyController {

@Post("/bean")
MyBean bean(@Body @Nullable MyBean bean) {
return bean;
}

@Post("/string")
String string(@Body String foobar) {
return foobar;
}

@Post("/stringNullable")
String stringNullable(@Body @Nullable String foobar) {
if (foobar == null) {
return nullBodyValue();
}
return foobar;
}

@Post("/bytes")
byte[] bytes(@Body byte[] foobar) {
return foobar;
}

@Post("/bytesNullable")
byte[] bytesNullable(@Nullable @Body byte[] foobar) {
if (foobar == null) {
return nullBodyValue().getBytes(StandardCharsets.UTF_8);
}
return foobar;
}

@Post("/io")
InputStream inputStream(@Body InputStream is) {
return is;
}

@Post("/ioNullable")
InputStream inputNullableStream(@Body @Nullable InputStream is) {
if (is == null) {
return new ByteArrayInputStream(nullBodyValue().getBytes(StandardCharsets.UTF_8));
}
return is;
}

private String nullBodyValue() {
return "<null>";
}

}

@Introspected
record MyBean() {
}

}
Loading
Loading