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

Http server: Allow to disable not-found on missing body #11059

Merged
merged 14 commits into from
Aug 13, 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
2 changes: 1 addition & 1 deletion .github/workflows/corretto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
df -h
- uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
distribution: 'corretto'
java-version: ${{ matrix.java }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -552,8 +552,7 @@ public void visitAroundMethod(TypedElement beanType,
final Optional<MethodElement> overridden = methodElement.getOwningType()
.getEnclosedElement(ElementQuery.ALL_METHODS
.onlyInstance()
.named(name -> name.equals(methodElement.getName()))
.filter(el -> el.overrides(methodElement)));
.filter(el -> el.getName().equals(methodElement.getName()) && el.overrides(methodElement)));

if (overridden.isPresent()) {
MethodElement overriddenBy = overridden.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,19 @@ public interface ElementQuery<T extends Element> {

/**
* Allows filtering elements by name.
* This method will only process native elements passing the name predicate.
* NOTE: Use this method only if the other elements shouldn't be touched (missing compilation information etc.). This method will skip all elements reusable cache.
*
* @param predicate The predicate to use. Should return true to include the element.
* @return This query
*/
@NonNull ElementQuery<T> named(@NonNull Predicate<String> predicate);

/**
* Allows filtering elements by name.
* This method will only process native elements passing the name predicate.
* NOTE: Use this method only if the other elements shouldn't be touched (missing compilation information etc.). This method will skip all elements reusable cache.
*
* @param name The name to filter by
* @return This query
* @since 3.5.2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,19 +179,23 @@ public <T extends io.micronaut.inject.ast.Element> List<T> getEnclosedElements(C
if (result.isOnlyDeclared() || classElement.getSuperType().isEmpty() && classElement.getInterfaces().isEmpty()) {
elements = getElements(nativeClassType, result, filter);
} else {
// Let's try to load the unfiltered result and apply the filter
QueryResultKey queryWithoutPredicatesResultKey = new QueryResultKey(result.withoutPredicates(), classElement.getNativeType());
List<T> valuesWithoutPredicates = (List<T>) resultsCache.get(queryWithoutPredicatesResultKey);
if (valuesWithoutPredicates != null) {
return valuesWithoutPredicates.stream().filter(filter).toList();
}

elements = getAllElements(nativeClassType, (t1, t2) -> reduceElements(t1, t2, result), result);
if (!queryWithoutPredicatesResultKey.equals(queryResultKey)) {
ElementQuery.Result<T> resultWithoutPredicates = result.withoutPredicates();
QueryResultKey queryWithoutPredicatesResultKey = new QueryResultKey(resultWithoutPredicates, classElement.getNativeType());
if (queryWithoutPredicatesResultKey.equals(queryResultKey)) {
// No predicates query
elements = getAllElements(nativeClassType, (t1, t2) -> reduceElements(t1, t2, result), result);
} else {
// Let's try to load the result without predicates and cache it, then apply predicates
List<T> valuesWithoutPredicates = (List<T>) resultsCache.get(queryWithoutPredicatesResultKey);
if (valuesWithoutPredicates != null) {
return valuesWithoutPredicates.stream().filter(filter).toList();
}
elements = getAllElements(nativeClassType, (t1, t2) -> reduceElements(t1, t2, resultWithoutPredicates), resultWithoutPredicates);
// This collection is before predicates are applied, we can store it and reuse
resultsCache.put(queryWithoutPredicatesResultKey, new ArrayList<>(elements));
// The second filtered result
elements.removeIf(element -> !filter.test(element));
}
elements.removeIf(element -> !filter.test(element));
}
resultsCache.put(queryResultKey, elements);
adjustMapCapacity(resultsCache, MAX_RESULTS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,12 +259,13 @@ void visitProperty(
.onlyAccessible()
.onlyDeclared()
.onlyInstance()
.named((n) -> n.startsWith(prefix) && n.equals(prefix + NameUtils.capitalize(name)))
.filter((methodElement -> {
ParameterElement[] parameters = methodElement.getParameters();
return parameters.length == 1 &&
methodElement.getGenericReturnType().getName().equals(classElement.getName()) &&
type.getType().isAssignable(parameters[0].getType());
String methodName = methodElement.getName();
return methodName.startsWith(prefix) && methodName.equals(prefix + NameUtils.capitalize(name))
&& parameters.length == 1
&& methodElement.getGenericReturnType().getName().equals(classElement.getName())
&& type.getType().isAssignable(parameters[0].getType());
}));
MethodElement withMethod = classElement.getEnclosedElement(elementQuery).orElse(null);
if (withMethod != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,7 @@ private void processBuilderDefinition(ClassElement element, VisitorContext conte
if (builderMethod != null) {
MethodElement methodElement = element
.getEnclosedElement(ElementQuery.ALL_METHODS.onlyStatic()
.named(builderMethod)
.filter(m -> !m.getGenericReturnType().isVoid())
.filter(m -> m.getName().equals(builderMethod) && !m.getGenericReturnType().isVoid())
.onlyAccessible(element))
.orElse(null);
if (methodElement != null) {
Expand Down Expand Up @@ -341,9 +340,9 @@ private void handleBuilder(
ElementQuery<MethodElement> builderMethodQuery = ElementQuery.ALL_METHODS
.onlyAccessible(classToBuild)
.onlyInstance()
.named(n -> Arrays.stream(writePrefixes).anyMatch(n::startsWith))
.filter(m ->
builderType.isAssignable(m.getGenericReturnType()) && m.getParameters().length <= 1
Arrays.stream(writePrefixes).anyMatch(m.getName()::startsWith) &&
builderType.isAssignable(m.getGenericReturnType()) && m.getParameters().length <= 1
);
builderType.getEnclosedElements(builderMethodQuery)
.forEach(builderWriter::visitBeanMethod);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ private void buildProducedBeanDefinition(ClassElement producedType,
if (StringUtils.isNotEmpty(destroyMethodName)) {
final Optional<MethodElement> destroyMethod = producedType.getEnclosedElement(ElementQuery.ALL_METHODS.onlyAccessible(classElement)
.onlyInstance()
.named(destroyMethodName)
.named(destroyMethodName) // Named filtering should avoid processing all method and fail on possible missing classes and compilation errors
.filter((e) -> !e.hasParameters()));
if (destroyMethod.isPresent()) {
MethodElement destroyMethodElement = destroyMethod.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@
*/
package io.micronaut.inject.writer;

import static io.micronaut.core.util.StringUtils.EMPTY_STRING_ARRAY;
import static io.micronaut.inject.visitor.BeanElementVisitor.VISITORS;

import io.micronaut.aop.writer.AopProxyWriter;
import io.micronaut.context.AbstractBeanDefinitionBeanConstructor;
import io.micronaut.context.AbstractExecutableMethod;
Expand Down Expand Up @@ -129,6 +126,14 @@
import io.micronaut.inject.visitor.BeanElementVisitorContext;
import io.micronaut.inject.visitor.VisitorContext;
import jakarta.inject.Singleton;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.signature.SignatureVisitor;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
Expand Down Expand Up @@ -156,13 +161,9 @@
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.signature.SignatureVisitor;

import static io.micronaut.core.util.StringUtils.EMPTY_STRING_ARRAY;
import static io.micronaut.inject.visitor.BeanElementVisitor.VISITORS;

/**
* <p>Responsible for building {@link BeanDefinition} instances at compile time. Uses ASM build the class definition.</p>
Expand Down Expand Up @@ -2195,8 +2196,7 @@ public void visitAnnotationMemberPropertyInjectionPoint(TypedElement annotationM
ElementQuery.ALL_METHODS
.onlyAccessible(beanTypeElement)
.onlyInstance()
.named(name -> annotationMemberProperty.equals(NameUtils.getPropertyNameForGetter(name, readPrefixes)))
.filter((e) -> !e.hasParameters())
.filter(m -> annotationMemberProperty.equals(NameUtils.getPropertyNameForGetter(m.getName(), readPrefixes)) && !m.hasParameters())
).orElse(null);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
Expand Down Expand Up @@ -516,6 +515,28 @@ public static <T> T convertPublisher(ConversionService conversionService, Object
.orElseThrow(() -> unconvertibleError(object, publisherType));
}

/**
* Attempts to convert the publisher to the given type.
*
* @param conversionService The conversion service
* @param object The object to convert
* @param <T> The generic type
* @return The Resulting in publisher
* @since 4.6.0
*/
@NonNull
public static <T> Publisher<T> convertToPublisher(@NonNull ConversionService conversionService, @NonNull Object object) {
Objects.requireNonNull(object, "Argument [object] cannot be null");
if (object instanceof Publisher<?> publisher) {
return (Publisher<T>) publisher;
}
if (object instanceof CompletableFuture cf) {
return Publishers.fromCompletableFuture(() -> cf);
}
return conversionService.convert(object, Publisher.class)
.orElseThrow(() -> unconvertibleError(object, Publisher.class));
}

/**
* Does the given reactive type emit a single result.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import io.micronaut.core.annotation.ReflectionConfig;
import io.micronaut.core.annotation.ReflectiveAccess;
import io.micronaut.core.annotation.TypeHint;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.inject.annotation.MutableAnnotationMetadata;
import io.micronaut.inject.ast.ClassElement;
Expand Down
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ micronaut-rxjava3 = "3.4.0"
micronaut-reactor = "3.4.1"
native-gradle-plugin = "0.10.2"
neo4j-java-driver = "5.17.0"
selenium = "4.23.0"
selenium = "4.23.1"
slf4j = "2.0.16"
smallrye = "6.4.0"
spock = "2.3-groovy-4.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ protected DefaultHttpClientBinderRegistry(ConversionService conversionService,
byAnnotation.put(Header.class, (context, uriContext, value, request) -> {
AnnotationMetadata annotationMetadata = context.getAnnotationMetadata();
String headerName = annotationMetadata
.stringValue(Header.class)
.filter(StringUtils::isNotEmpty)
.orElse(NameUtils.hyphenate(context.getArgument().getName()));
.stringValue(Header.class)
.filter(StringUtils::isNotEmpty)
.orElseGet(() -> annotationMetadata.stringValue(Header.class, "name").orElse(NameUtils.hyphenate(context.getArgument().getName())));

conversionService.convert(value, String.class)
.ifPresent(header -> request.getHeaders().set(headerName, header));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ public <T> Optional<T> getBody(Argument<T> type) {
}

private <T> Optional convertBytes(@Nullable MediaType contentType, byte[] bytes, Argument<T> type) {
if (bytes.length == 0) {
return Optional.empty();
}
final boolean isOptional = type.getType() == Optional.class;
final Argument finalArgument = isOptional ? type.getFirstTypeVariable().orElse(type) : type;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* 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.client.tck.tests;

import io.micronaut.context.annotation.Requires;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.tck.ServerUnderTest;
import io.micronaut.http.tck.ServerUnderTestProviderUtils;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.junit.jupiter.api.Assertions.assertEquals;

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

@Test
void testHeaders() throws IOException {
try (ServerUnderTest server = ServerUnderTestProviderUtils.getServerUnderTestProvider().getServer(SPEC_NAME)) {
Client client = server.getApplicationContext().getBean(Client.class);

assertEquals("{\"status\":\"ok\"}", client.getOkAsJson());
// custom header name with mixed case
assertEquals("{\"status\":\"okok\"}", client.getFooAsJson("fOO", "ok"));
// A different use-case with using @Header(name="..")
assertEquals("{\"status\":\"okok\"}", client.getFooAsJson2("fOO", "ok"));
}
}

@Controller("/foo")
@Requires(property = "spec.name", value = SPEC_NAME)
static class ProduceController implements API {
@Get(value = "/ok", produces = MediaType.APPLICATION_JSON)
public String getOkAsJson() {
return "{\"status\":\"ok\"}";
}

@Get(value = "/bar", produces = MediaType.APPLICATION_JSON)
public String getFooAsJson(@Header("Foo") String header1, @Header("fOo") String header2) {
return "{\"status\":\"" + header1 + header2 + "\"}";
}

@Get(value = "/bar2", produces = MediaType.APPLICATION_JSON)
public String getFooAsJson2(@Header(name = "Foo") String header1, @Header(name = "fOo") String header2) {
return "{\"status\":\"" + header1 + header2 + "\"}";
}
}

@Requires(property = "spec.name", value = SPEC_NAME)
@io.micronaut.http.client.annotation.Client("/foo")
interface Client extends API {
}

interface API {

@Get(value = "/ok", produces = MediaType.APPLICATION_JSON)
String getOkAsJson();

@Get(value = "/bar", produces = MediaType.APPLICATION_JSON)
String getFooAsJson(@Header("Foo") String header1, @Header("fOo") String header2);

@Get(value = "/bar2", produces = MediaType.APPLICATION_JSON)
String getFooAsJson2(@Header(name = "Foo") String header1, @Header(name = "fOo") String header2);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
* @return The flowable
*/
protected Publisher<?> instrumentPublisher(ChannelHandlerContext ctx, Object result) {
Publisher<?> actual = Publishers.convertPublisher(conversionService, result, Publisher.class);
Publisher<?> actual = Publishers.convertToPublisher(conversionService, result);
return Flux.from(actual).subscribeOn(Schedulers.fromExecutorService(ctx.channel().eventLoop()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ private Flux<HttpContent> mapToHttpContent(NettyHttpRequest<?> request,
ChannelHandlerContext context) {
MediaType mediaType = response.getContentType().orElse(null);
NettyByteBufferFactory byteBufferFactory = new NettyByteBufferFactory(context.alloc());
Flux<Object> bodyPublisher = Flux.from(Publishers.convertPublisher(conversionService, body, Publisher.class));
Flux<Object> bodyPublisher = Flux.from(Publishers.convertToPublisher(conversionService, body));
Flux<HttpContent> httpContentPublisher;
boolean isJson = false;
if (routeInfo != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public final Publisher<? extends MutableHttpResponse<?>> doFilter(HttpRequest<?>
Object body = optionalBody.get();
MediaTypeCodec codec = codecFactory.resolveJsonViewCodec(viewClass.get());
if (Publishers.isConvertibleToPublisher(body)) {
Publisher<?> pub = Publishers.convertPublisher(conversionService, body, Publisher.class);
Publisher<?> pub = Publishers.convertToPublisher(conversionService, body);
response.body(Flux.from(pub)
.map(o -> codec.encode((Argument) routeInfo.getResponseBodyType(), o))
.subscribeOn(Schedulers.fromExecutorService(executorService)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ public ConvertibleValues<Object> getUriVariables() {

@Override
protected Publisher<?> instrumentPublisher(ChannelHandlerContext ctx, Object result) {
Publisher<?> actual = Publishers.convertPublisher(conversionService, result, Publisher.class);
Publisher<?> actual = Publishers.convertToPublisher(conversionService, result);
Publisher<?> traced = (Publisher<Object>) subscriber -> ServerRequestContext.with(originatingRequest,
() -> actual.subscribe(new Subscriber<Object>() {
@Override
Expand Down
Loading
Loading