Skip to content

Commit

Permalink
Rest Client Reactive - MicroProfile 2.0 features
Browse files Browse the repository at this point in the history
  • Loading branch information
michalszynkiewicz authored and cescoffier committed Apr 6, 2021
1 parent 316942e commit 571fa92
Show file tree
Hide file tree
Showing 27 changed files with 662 additions and 342 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
import io.quarkus.jaxrs.client.reactive.deployment.beanparam.QueryParamItem;
import io.quarkus.jaxrs.client.reactive.runtime.ClientResponseBuilderFactory;
import io.quarkus.jaxrs.client.reactive.runtime.JaxrsClientReactiveRecorder;
import io.quarkus.resteasy.reactive.client.runtime.ToObjectArray;
import io.quarkus.resteasy.reactive.common.deployment.ApplicationResultBuildItem;
import io.quarkus.resteasy.reactive.common.deployment.QuarkusFactoryCreator;
import io.quarkus.resteasy.reactive.common.deployment.ResourceScanningResultBuildItem;
Expand Down Expand Up @@ -451,7 +452,8 @@ public void close() {

// query params have to be set on a method-level web target (they vary between invocations)
methodCreator.assign(methodTarget, addQueryParam(methodCreator, methodTarget, param.name,
methodCreator.getMethodParam(paramIdx)));
methodCreator.getMethodParam(paramIdx),
jandexMethod.parameters().get(paramIdx), index));
} else if (param.parameterType == ParameterType.BEAN) {
// bean params require both, web-target and Invocation.Builder, modifications
// The web target changes have to be done on the method level.
Expand All @@ -470,7 +472,7 @@ public void close() {
handleBeanParamMethod.assign(invocationBuilderRef, handleBeanParamMethod.getMethodParam(0));
addBeanParamData(methodCreator, handleBeanParamMethod,
invocationBuilderRef, beanParam.getItems(),
methodCreator.getMethodParam(paramIdx), methodTarget);
methodCreator.getMethodParam(paramIdx), methodTarget, index);

handleBeanParamMethod.returnValue(invocationBuilderRef);
invocationBuilderEnrichers.put(handleBeanParamDescriptor, methodCreator.getMethodParam(paramIdx));
Expand Down Expand Up @@ -809,8 +811,8 @@ private void addBeanParamData(BytecodeCreator methodCreator,
AssignableResultHandle invocationBuilder,
List<Item> beanParamItems,
ResultHandle param,
AssignableResultHandle target // can only be used in the current method, not in `invocationBuilderEnricher`
) {
AssignableResultHandle target, // can only be used in the current method, not in `invocationBuilderEnricher`
IndexView index) {
BytecodeCreator creator = methodCreator.ifNotNull(param).trueBranch();
BytecodeCreator invoEnricher = invocationBuilderEnricher.ifNotNull(invocationBuilderEnricher.getMethodParam(1))
.trueBranch();
Expand All @@ -820,12 +822,15 @@ private void addBeanParamData(BytecodeCreator methodCreator,
BeanParamItem beanParamItem = (BeanParamItem) item;
ResultHandle beanParamElementHandle = beanParamItem.extract(creator, param);
addBeanParamData(creator, invoEnricher, invocationBuilder, beanParamItem.items(),
beanParamElementHandle, target);
beanParamElementHandle, target, index);
break;
case QUERY_PARAM:
QueryParamItem queryParam = (QueryParamItem) item;
creator.assign(target,
addQueryParam(creator, target, queryParam.name(), queryParam.extract(creator, param)));
addQueryParam(creator, target, queryParam.name(),
queryParam.extract(creator, param),
queryParam.getValueType(),
index));
break;
case COOKIE:
CookieParamItem cookieParam = (CookieParamItem) item;
Expand All @@ -848,13 +853,29 @@ private void addBeanParamData(BytecodeCreator methodCreator,
// takes a result handle to target as one of the parameters, returns a result handle to a modified target
private ResultHandle addQueryParam(BytecodeCreator methodCreator,
ResultHandle target,
String paramName, ResultHandle queryParamHandle) {
ResultHandle array = methodCreator.newArray(Object.class, 1);
methodCreator.writeArrayValue(array, 0, queryParamHandle);
String paramName,
ResultHandle queryParamHandle,
Type type,
IndexView index) {
ResultHandle paramArray;
if (type.kind() == Type.Kind.ARRAY) {
paramArray = methodCreator.checkCast(queryParamHandle, Object[].class);
} else if (index
.getClassByName(type.name()).interfaceNames().stream()
.anyMatch(DotName.createSimple(Collection.class.getName())::equals)) {
paramArray = methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(ToObjectArray.class, "collection", Object[].class, Collection.class),
queryParamHandle);
} else {
paramArray = methodCreator.invokeStaticMethod(
MethodDescriptor.ofMethod(ToObjectArray.class, "value", Object[].class, Object.class),
queryParamHandle);
}

ResultHandle alteredTarget = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(WebTarget.class, "queryParam", WebTarget.class,
String.class, Object[].class),
target, methodCreator.load(paramName), array);
target, methodCreator.load(paramName), paramArray);
return alteredTarget;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ public static List<Item> parse(ClassInfo beanParamClass, IndexView index) {
if (target.kind() == AnnotationTarget.Kind.FIELD) {
FieldInfo fieldInfo = target.asField();
resultList.add(new QueryParamItem(annotation.value().asString(),
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())));
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()),
fieldInfo.type()));
} else if (target.kind() == AnnotationTarget.Kind.METHOD) {
MethodInfo getterMethod = getGetterMethod(beanParamClass, target.asMethod());
resultList.add(new QueryParamItem(annotation.value().asString(),
new GetterExtractor(getterMethod)));
new GetterExtractor(getterMethod), getterMethod.returnType()));
}
}
}
Expand Down Expand Up @@ -116,4 +117,7 @@ private static MethodInfo getGetterMethod(ClassInfo beanParamClass, MethodInfo m
}
return getter;
}

private BeanParamParser() {
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
package io.quarkus.jaxrs.client.reactive.deployment.beanparam;

import org.jboss.jandex.Type;

public class QueryParamItem extends Item {

private final String name;
private final Type valueType;

public QueryParamItem(String name, ValueExtractor extractor) {
public QueryParamItem(String name, ValueExtractor extractor, Type valueType) {
super(ItemType.QUERY_PARAM, extractor);
this.name = name;
this.valueType = valueType;
}

public String name() {
return name;
}

public Type getValueType() {
return valueType;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.quarkus.jaxrs.client.reactive.runtime;

import java.util.Collection;

/**
* used by query param handling mechanism, in generated code
*/
@SuppressWarnings("unused")
public class ToObjectArray {

public static Object[] collection(Collection<?> collection) {
return collection.toArray();
}

public static Object[] value(Object value) {
return new Object[] { value };
}

private ToObjectArray() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MultivaluedMap;

import io.quarkus.jaxrs.client.reactive.deployment.JaxrsClientReactiveEnricher;
import io.quarkus.rest.client.reactive.MicroProfileRestClientRequestFilter;
import io.quarkus.rest.client.reactive.runtime.NoOpHeaderFiller;
import org.eclipse.microprofile.rest.client.RestClientDefinitionException;
import org.eclipse.microprofile.rest.client.ext.ClientHeadersFactory;
import org.eclipse.microprofile.rest.client.ext.DefaultClientHeadersFactoryImpl;
Expand All @@ -42,6 +45,7 @@
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.gizmo.AssignableResultHandle;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.CatchBlockCreator;
import io.quarkus.gizmo.ClassCreator;
Expand All @@ -52,10 +56,8 @@
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.gizmo.TryBlock;
import io.quarkus.jaxrs.client.reactive.deployment.JaxrsClientReactiveEnricher;
import io.quarkus.rest.client.reactive.BeanGrabber;
import io.quarkus.rest.client.reactive.HeaderFiller;
import io.quarkus.rest.client.reactive.runtime.NoOpHeaderFiller;
import io.quarkus.rest.client.reactive.runtime.RestClientReactiveRequestFilter;
import io.quarkus.runtime.util.HashUtil;

/**
Expand All @@ -64,8 +66,8 @@
* Used mostly to handle the `@RegisterProvider` annotation that e.g. registers filters
* and to add support for `@ClientHeaderParam` annotations for specifying (possibly) computed headers via annotations
*/
class RestClientReactiveEnricher implements JaxrsClientReactiveEnricher {
private static final Logger log = Logger.getLogger(RestClientReactiveEnricher.class);
class MicroProfileRestClientEnricher implements JaxrsClientReactiveEnricher {
private static final Logger log = Logger.getLogger(MicroProfileRestClientEnricher.class);

public static final String DEFAULT_HEADERS_FACTORY = DefaultClientHeadersFactoryImpl.class.getName();

Expand Down Expand Up @@ -128,7 +130,7 @@ public void forClass(MethodCreator constructor, AssignableResultHandle webTarget
}

ResultHandle restClientFilter = constructor.newInstance(
MethodDescriptor.ofConstructor(RestClientReactiveRequestFilter.class, ClientHeadersFactory.class),
MethodDescriptor.ofConstructor(MicroProfileRestClientRequestFilter.class, ClientHeadersFactory.class),
clientHeadersFactory);

constructor.assign(webTargetBase, constructor.invokeInterfaceMethod(
Expand Down Expand Up @@ -433,13 +435,35 @@ private AnnotationInstance[] extractAnnotations(AnnotationInstance groupAnnotati

private void addProvider(MethodCreator ctor, AssignableResultHandle target, IndexView index,
AnnotationInstance registerProvider) {
ResultHandle provider = ctor.newInstance(MethodDescriptor.ofConstructor(registerProvider.value().asString()));
ResultHandle alteredTarget = ctor.invokeInterfaceMethod(
// if a registered provider is a cdi bean, it has to be reused
// take the name of the provider class from the annotation:
String providerClass = registerProvider.value().asString();

// get bean, or null, with BeanGrabber.getBeanIfDefined(providerClass)
ResultHandle providerBean = ctor.invokeStaticMethod(
MethodDescriptor.ofMethod(BeanGrabber.class, "getBeanIfDefined", Object.class, Class.class),
ctor.loadClass(providerClass));

// if bean != null, register the bean
BranchResult branchResult = ctor.ifNotNull(providerBean);
BytecodeCreator beanProviderAvailable = branchResult.trueBranch();

ResultHandle alteredTarget = beanProviderAvailable.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Configurable.class, "register", Configurable.class, Object.class,
int.class),
target, providerBean,
beanProviderAvailable.load(registerProvider.valueWithDefault(index, "priority").asInt()));
beanProviderAvailable.assign(target, alteredTarget);

// else, create a new instance of the provider class
BytecodeCreator beanProviderNotAvailable = branchResult.falseBranch();
ResultHandle provider = beanProviderNotAvailable.newInstance(MethodDescriptor.ofConstructor(providerClass));
alteredTarget = beanProviderNotAvailable.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Configurable.class, "register", Configurable.class, Object.class,
int.class),
target, provider,
ctor.load(registerProvider.valueWithDefault(index, "priority").asInt()));
ctor.assign(target, alteredTarget);
beanProviderNotAvailable.load(registerProvider.valueWithDefault(index, "priority").asInt()));
beanProviderNotAvailable.assign(target, alteredTarget);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package io.quarkus.rest.client.reactive.redirect;

import static org.assertj.core.api.Assertions.assertThat;

import java.net.URI;

import javax.ws.rs.core.Response;

import org.eclipse.microprofile.rest.client.RestClientBuilder;
import org.jboss.resteasy.reactive.client.api.QuarkusRestClientProperties;
import org.jboss.shrinkwrap.api.ShrinkWrap;
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.quarkus.test.common.http.TestHTTPResource;

public class RedirectTest {

@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(RedirectingResourceClient.class, RedirectingResource.class));

@TestHTTPResource
URI uri;

@Test
void shouldRedirect3Times_whenMax4() {
RedirectingResourceClient client = RestClientBuilder.newBuilder()
.baseUri(uri)
.followRedirects(true)
.property(QuarkusRestClientProperties.MAX_REDIRECTS, 4)
.build(RedirectingResourceClient.class);
Response call = client.call(3);
assertThat(call.getStatus()).isEqualTo(200);
}

@Test
void shouldNotRedirect3Times_whenMax2() {
RedirectingResourceClient client = RestClientBuilder.newBuilder()
.baseUri(uri)
.followRedirects(true)
.property(QuarkusRestClientProperties.MAX_REDIRECTS, 2)
.build(RedirectingResourceClient.class);
assertThat(client.call(3).getStatus()).isEqualTo(307);

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.quarkus.rest.client.reactive.redirect;

import java.net.URI;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/redirect")
public class RedirectingResource {

@GET
public Response redirectedResponse(@QueryParam("redirects") Integer number) {
if (number == null || 0 == number) {
return Response.ok().build();
} else {
return Response.temporaryRedirect(URI.create("/redirect?redirects=" + (number - 1))).build();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.quarkus.rest.client.reactive.redirect;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/redirect")
public interface RedirectingResourceClient {
@GET
Response call(@QueryParam("redirects") Integer numberOfRedirects);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package io.quarkus.rest.client.reactive;

import io.quarkus.arc.Arc;
import io.quarkus.arc.InstanceHandle;

@SuppressWarnings("unused")
public class BeanGrabber {
public static <T> T getBeanIfDefined(Class<T> beanClass) {
InstanceHandle<T> instance = Arc.container().instance(beanClass);
if (instance.isAvailable()) {
return instance.get();
}
return null;
}

private BeanGrabber() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package io.quarkus.rest.client.reactive;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;

public class DefaultMicroprofileRestClientExceptionMapper implements ResponseExceptionMapper {

public Throwable toThrowable(Response response) {
try {
response.bufferEntity();
} catch (Exception var3) {
}

return new WebApplicationException("Unknown error, status code " + response.getStatus(), response);
}

public boolean handles(int status, MultivaluedMap headers) {
return status >= 400;
}

public int getPriority() {
return Integer.MAX_VALUE;
}
}
Loading

0 comments on commit 571fa92

Please sign in to comment.