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 radcortez committed Mar 29, 2021
1 parent 4eb41ab commit ff6fbd5
Show file tree
Hide file tree
Showing 21 changed files with 465 additions and 327 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
import io.quarkus.resteasy.reactive.client.deployment.beanparam.QueryParamItem;
import io.quarkus.resteasy.reactive.client.runtime.ClientResponseBuilderFactory;
import io.quarkus.resteasy.reactive.client.runtime.ResteasyReactiveClientRecorder;
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 @@ -447,7 +448,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 @@ -466,7 +468,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 @@ -761,8 +763,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 @@ -772,12 +774,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 @@ -800,13 +805,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.resteasy.reactive.client.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.resteasy.reactive.client.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 @@ -42,6 +42,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,6 +53,7 @@
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.gizmo.TryBlock;
import io.quarkus.rest.client.reactive.BeanGrabber;
import io.quarkus.rest.client.reactive.HeaderFiller;
import io.quarkus.rest.client.reactive.MicroProfileRestClientRequestFilter;
import io.quarkus.rest.client.reactive.NoOpHeaderFiller;
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() {
}
}
Loading

0 comments on commit ff6fbd5

Please sign in to comment.