From 8c63e8e74485d1d5952dd0c648e6279dfcea5b6f Mon Sep 17 00:00:00 2001 From: Kevin Davis Date: Fri, 23 Jul 2021 16:16:39 -0400 Subject: [PATCH] [GH-57] Introduce Annotation Processors This change introduces the concept of an `AnnotationProcessor`. These components are used when processing an `AnnotationDrivenContract` Contracts can now be modularized whereas they are now collections of annotation processors instead of full fledged parsing components. By doing so, `AnnotationProcessors` can be shared between our current reflection based contract parsers and the upcoming compile time annotation processors. --- .../AbstractAnnotationDrivenContract.java | 27 +++-- .../feign/contract/AnnotationProcessor.java | 16 +++ .../java/feign/contract/FeignContract.java | 110 +++++------------- .../ParameterAnnotationProcessor.java | 16 +++ .../contract/TargetMethodDefinition.java | 62 ++++++---- .../impl/BodyAnnotationProcessor.java | 33 ++++++ .../impl/HeaderAnnotationProcessor.java | 36 ++++++ .../impl/HeadersAnnotationProcessor.java | 47 ++++++++ .../impl/ParamAnnotationProcessor.java | 44 +++++++ .../impl/RequestAnnotationProcessor.java | 16 +++ .../impl/AbstractTargetMethodHandler.java | 2 +- .../impl/TypeDrivenMethodHandlerFactory.java | 7 +- .../impl/type/TypeDefinitionFactory.java | 4 +- .../main/java/feign/impl/type/TypeUtils.java | 77 ++++++++++++ .../feign/contract/FeignContractTest.java | 16 +-- .../impl/AbstractTargetMethodHandlerTest.java | 62 +++------- .../impl/BlockingTargetMethodHandlerTest.java | 9 +- .../TypeDrivenMethodHandlerFactoryTest.java | 9 +- 18 files changed, 405 insertions(+), 188 deletions(-) create mode 100644 core/src/main/java/feign/contract/impl/BodyAnnotationProcessor.java create mode 100644 core/src/main/java/feign/contract/impl/HeaderAnnotationProcessor.java create mode 100644 core/src/main/java/feign/contract/impl/HeadersAnnotationProcessor.java create mode 100644 core/src/main/java/feign/contract/impl/ParamAnnotationProcessor.java create mode 100644 core/src/main/java/feign/impl/type/TypeUtils.java diff --git a/core/src/main/java/feign/contract/AbstractAnnotationDrivenContract.java b/core/src/main/java/feign/contract/AbstractAnnotationDrivenContract.java index b963bad..8b104b6 100644 --- a/core/src/main/java/feign/contract/AbstractAnnotationDrivenContract.java +++ b/core/src/main/java/feign/contract/AbstractAnnotationDrivenContract.java @@ -23,12 +23,9 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; -import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collection; -import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,7 +39,6 @@ public abstract class AbstractAnnotationDrivenContract implements Contract { private static final Logger logger = LoggerFactory.getLogger(AbstractAnnotationDrivenContract.class); - protected final TypeDefinitionFactory typeDefinitionFactory = new TypeDefinitionFactory(); private final Map, AnnotationProcessor> annotationProcessors = new LinkedHashMap<>(); private final Map, ParameterAnnotationProcessor> @@ -121,16 +117,27 @@ public TargetDefinition apply(Class targetType, FeignConfiguration configurat return builder.build(); } - private void registerAnnotationProcessor(Annotation annotation, AnnotationProcessor processor) { - this.annotationProcessors.put(annotation.annotationType(), processor); - } - protected abstract Collection> getSupportedClassAnnotations(); protected abstract Collection> getSupportedMethodAnnotations(); protected abstract Collection> getSupportedParameterAnnotations(); + @SuppressWarnings("unchecked") + protected void registerAnnotationProcessor( + Class annotation, AnnotationProcessor processor) { + this.annotationProcessors + .computeIfAbsent(annotation, annotationType -> (AnnotationProcessor) processor); + } + + @SuppressWarnings("unchecked") + protected void registerParameterAnnotationProcessor( + Class annotation, ParameterAnnotationProcessor processor) { + this.parameterAnnotationProcessors + .computeIfAbsent(annotation, + annotationType -> (ParameterAnnotationProcessor) processor); + } + /** * Apply any Annotations located at the Type level. Any definitions applied at this level will be * used as defaults for all methods on the target, unless redefined at the method or parameter @@ -147,7 +154,6 @@ protected void processAnnotationsOnType(Class type, TargetMethodDefinition.Bu /** * Apply any Annotations located at the Method level. * - * @param type to the method belongs to. * @param method to inspect * @param builder to store the applied configuration. */ @@ -155,7 +161,8 @@ protected void processAnnotationsOnMethod(Class type, Method method, TargetMethodDefinition.Builder builder) { /* set the common method information */ builder.name(method.getName()); - builder.returnType(method.getGenericReturnType().getTypeName()); + builder.returnTypeDefinition( + TypeDefinitionFactory.getInstance().create(method.getGenericReturnType(), type)); this.processAnnotations(method.getAnnotations(), this.getSupportedMethodAnnotations(), builder); } diff --git a/core/src/main/java/feign/contract/AnnotationProcessor.java b/core/src/main/java/feign/contract/AnnotationProcessor.java index 35691db..9aeb954 100644 --- a/core/src/main/java/feign/contract/AnnotationProcessor.java +++ b/core/src/main/java/feign/contract/AnnotationProcessor.java @@ -1,3 +1,19 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.contract; import java.lang.annotation.Annotation; diff --git a/core/src/main/java/feign/contract/FeignContract.java b/core/src/main/java/feign/contract/FeignContract.java index e93e70c..c5d8f09 100644 --- a/core/src/main/java/feign/contract/FeignContract.java +++ b/core/src/main/java/feign/contract/FeignContract.java @@ -16,17 +16,13 @@ package feign.contract; -import feign.http.HttpHeader; -import feign.http.HttpMethod; -import feign.impl.type.TypeDefinition; -import feign.support.StringUtils; -import feign.template.ExpressionExpander; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; +import feign.contract.impl.BodyAnnotationProcessor; +import feign.contract.impl.HeadersAnnotationProcessor; +import feign.contract.impl.ParamAnnotationProcessor; +import feign.contract.impl.RequestAnnotationProcessor; +import java.lang.annotation.Annotation; +import java.util.Collection; +import java.util.Set; /** * Contract that uses Feign annotations. @@ -38,93 +34,39 @@ public class FeignContract extends AbstractAnnotationDrivenContract { */ public FeignContract() { super(); + this.registerAnnotationProcessor(Request.class, new RequestAnnotationProcessor()); + this.registerAnnotationProcessor(Headers.class, new HeadersAnnotationProcessor()); + this.registerParameterAnnotationProcessor(Param.class, new ParamAnnotationProcessor()); + this.registerParameterAnnotationProcessor(Body.class, new BodyAnnotationProcessor()); } - /** - * Process the Headers annotation. + * Support {@link Request} and {@link Headers} at the class level. * - * @param headers annotation to process. - * @param targetMethodDefinition for the request. + * @return set of supported annotations at the class level. */ - private void processHeaders(Headers headers, - TargetMethodDefinition.Builder targetMethodDefinition) { - if (headers.value().length != 0) { - Header[] header = headers.value(); - for (Header value : header) { - this.processHeader(value, targetMethodDefinition); - } - } + @Override + protected Collection> getSupportedClassAnnotations() { + return Set.of(Request.class, Headers.class); } /** - * Process the Header annotation. + * Support the same items at the class level at the method level. * - * @param header annotation to process. - * @param targetMethodDefinition for the header. + * @return a set of supported annotations at the method level. */ - private void processHeader(Header header, TargetMethodDefinition.Builder targetMethodDefinition) { - HttpHeader httpHeader = new HttpHeader(header.name()); - httpHeader.value(header.value()); - targetMethodDefinition.header(httpHeader); + @Override + protected Collection> getSupportedMethodAnnotations() { + return this.getSupportedClassAnnotations(); } /** - * Process the Param annotation. + * Support the {@link Param} and {@link Body} annotations at the parameter level. * - * @param parameter annotation to process. - * @param index of the parameter in the method signature. - * @param type of the parameter. - * @param targetMethodDefinition for the parameter. + * @return the set of supported annotations at the parameter level. */ - private void processParameter(Param parameter, Integer index, Class type, - TargetMethodDefinition.Builder targetMethodDefinition) { - - String name = parameter.value(); - String typeClass = type.getCanonicalName(); - - Class expanderClass = parameter.expander(); - String expanderClassName = expanderClass.getName(); - - targetMethodDefinition.parameterDefinition( - index, TargetMethodParameterDefinition.builder() - .name(name) - .index(index) - .type(typeClass) - .expanderClassName(expanderClassName) - .build()); + @Override + protected Collection> getSupportedParameterAnnotations() { + return Set.of(Param.class, Body.class); } - - /** - * Constructs a name for a Method that is formatted as a javadoc reference. - * - * @param targetType containing the method. - * @param method to inspect. - * @return a See Tag inspired name for the method. - */ - private String getMethodTag(Class targetType, Method method) { - StringBuilder sb = new StringBuilder() - .append(targetType.getSimpleName()) - .append("#") - .append(method.getName()) - .append("("); - List parameters = Arrays.asList(method.getGenericParameterTypes()); - Iterator iterator = parameters.iterator(); - while (iterator.hasNext()) { - Type parameter = iterator.next(); - sb.append(parameter.getTypeName()); - if (iterator.hasNext()) { - sb.append(","); - } - } - sb.append(")"); - return sb.toString(); - } - - private TypeDefinition getMethodReturnType(Method method) { - return this.typeDefinitionFactory - .create(method.getGenericReturnType(), method.getDeclaringClass()); - } - - } diff --git a/core/src/main/java/feign/contract/ParameterAnnotationProcessor.java b/core/src/main/java/feign/contract/ParameterAnnotationProcessor.java index ab450a2..18c20d6 100644 --- a/core/src/main/java/feign/contract/ParameterAnnotationProcessor.java +++ b/core/src/main/java/feign/contract/ParameterAnnotationProcessor.java @@ -1,3 +1,19 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.contract; import java.lang.annotation.Annotation; diff --git a/core/src/main/java/feign/contract/TargetMethodDefinition.java b/core/src/main/java/feign/contract/TargetMethodDefinition.java index a6c8c83..6bbe75b 100644 --- a/core/src/main/java/feign/contract/TargetMethodDefinition.java +++ b/core/src/main/java/feign/contract/TargetMethodDefinition.java @@ -22,6 +22,7 @@ import feign.http.RequestSpecification; import feign.impl.type.TypeDefinition; import feign.impl.type.TypeDefinitionFactory; +import feign.impl.type.TypeUtils; import feign.support.Assert; import feign.support.StringUtils; import feign.template.TemplateParameter; @@ -52,7 +53,7 @@ public final class TargetMethodDefinition { private final String targetType; private final String name; private String returnTypeFullyQualifiedClassName; - private transient TypeDefinition returnType; + private transient TypeDefinition returnTypeDefinition; private final Consumer target; private final String tag; private final HttpMethod method; @@ -87,9 +88,13 @@ public static Builder from(TargetMethodDefinition targetMethodDefinition) { .readTimeout(targetMethodDefinition.readTimeout) .target(targetMethodDefinition.target); - if (targetMethodDefinition.returnType != null) { - builder.returnType(targetMethodDefinition.returnTypeFullyQualifiedClassName); + if (targetMethodDefinition.returnTypeDefinition != null) { + builder.returnTypeDefinition(targetMethodDefinition.returnTypeDefinition); + } else if (targetMethodDefinition.returnTypeFullyQualifiedClassName != null) { + builder.returnTypeFullyQualifiedClassName( + targetMethodDefinition.returnTypeFullyQualifiedClassName); } + if (targetMethodDefinition.template != null) { builder.uri(targetMethodDefinition.template.toString()); } @@ -138,10 +143,12 @@ private TargetMethodDefinition(TargetMethodDefinition.Builder builder) { .collect(Collectors.toUnmodifiableMap(Entry::getKey, Entry::getValue)); } - if (builder.returnType != null) { - this.returnTypeFullyQualifiedClassName = builder.returnType; + if (builder.returnTypeDefinition != null) { + this.returnTypeDefinition = builder.returnTypeDefinition; + } else if (StringUtils.isNotEmpty(builder.returnTypeFullyQualifiedClassName)) { + this.returnTypeFullyQualifiedClassName = builder.returnTypeFullyQualifiedClassName; } else { - this.returnType = null; + this.returnTypeDefinition = null; } } @@ -163,18 +170,21 @@ public String getReturnTypeFullyQualifiedClassName() { * * @return return Type. */ - public synchronized TypeDefinition getReturnType() { - if (this.returnType == null && StringUtils.isNotEmpty(this.returnTypeFullyQualifiedClassName)) { - try { - return TypeDefinitionFactory.getInstance() - .create( - Class.forName(this.returnTypeFullyQualifiedClassName), - Class.forName(this.targetType)); - } catch (ClassNotFoundException cnfe) { - throw new IllegalStateException("Error obtaining return type definition.", cnfe); + public TypeDefinition getReturnTypeDefinition() { + if (this.returnTypeDefinition == null + && StringUtils.isNotEmpty(this.returnTypeFullyQualifiedClassName)) { + synchronized (this) { + try { + Class type = TypeUtils.getInstance(this.returnTypeFullyQualifiedClassName); + Class context = TypeUtils.getInstance(this.targetType); + return TypeDefinitionFactory.getInstance() + .create(type, context); + } catch (Exception ex) { + throw new IllegalStateException("Error obtaining return type definition.", ex); + } } } - return returnType; + return returnTypeDefinition; } /** @@ -335,7 +345,7 @@ public String toString() { .add("target=" + targetType) .add("name='" + name + "'") .add("tag='" + tag + "'") - .add("returnType=" + returnType) + .add("returnType=" + returnTypeDefinition) .add("template=" + template) .add("method=" + method) .add("followRedirects=" + followRedirects) @@ -352,7 +362,8 @@ public static class Builder { private final String targetType; private String name; private String tag; - private String returnType; + private String returnTypeFullyQualifiedClassName; + private transient TypeDefinition returnTypeDefinition; private Consumer target = RequestSpecification::uri; private UriTemplate template; private HttpMethod method = HttpMethod.GET; @@ -395,14 +406,25 @@ public Builder tag(String tag) { return this; } + /** + * The {@link TypeDefinition} of the method's return type. + * + * @param typeDefinition of the method's return type. + * @return the reference chain. + */ + public Builder returnTypeDefinition(TypeDefinition typeDefinition) { + this.returnTypeDefinition = typeDefinition; + return this; + } + /** * Method Return Type. * * @param returnTypeFullyQualifiedClassName of the method. * @return the reference chain. */ - public Builder returnType(String returnTypeFullyQualifiedClassName) { - this.returnType = returnTypeFullyQualifiedClassName; + public Builder returnTypeFullyQualifiedClassName(String returnTypeFullyQualifiedClassName) { + this.returnTypeFullyQualifiedClassName = returnTypeFullyQualifiedClassName; return this; } diff --git a/core/src/main/java/feign/contract/impl/BodyAnnotationProcessor.java b/core/src/main/java/feign/contract/impl/BodyAnnotationProcessor.java new file mode 100644 index 0000000..0b4f206 --- /dev/null +++ b/core/src/main/java/feign/contract/impl/BodyAnnotationProcessor.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.contract.impl; + +import feign.contract.Body; +import feign.contract.ParameterAnnotationProcessor; +import feign.contract.TargetMethodDefinition.Builder; + +/** + * Annotation Processor for the {@link Body} annotation. Registers which method parameters contains + * the request body. + */ +public class BodyAnnotationProcessor implements ParameterAnnotationProcessor { + + @Override + public void process(Body annotation, String name, Integer index, String type, Builder builder) { + builder.body(index); + } +} diff --git a/core/src/main/java/feign/contract/impl/HeaderAnnotationProcessor.java b/core/src/main/java/feign/contract/impl/HeaderAnnotationProcessor.java new file mode 100644 index 0000000..7505e1d --- /dev/null +++ b/core/src/main/java/feign/contract/impl/HeaderAnnotationProcessor.java @@ -0,0 +1,36 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.contract.impl; + +import feign.contract.AnnotationProcessor; +import feign.contract.Header; +import feign.contract.TargetMethodDefinition.Builder; +import feign.http.HttpHeader; + +/** + * Annotation processor for the {@link Header} annotation. Evaluates and prepares an HTTP + * Header. + */ +public class HeaderAnnotationProcessor implements AnnotationProcessor
{ + + @Override + public void process(Header annotation, Builder builder) { + HttpHeader httpHeader = new HttpHeader(annotation.name()); + httpHeader.value(annotation.value()); + builder.header(httpHeader); + } +} diff --git a/core/src/main/java/feign/contract/impl/HeadersAnnotationProcessor.java b/core/src/main/java/feign/contract/impl/HeadersAnnotationProcessor.java new file mode 100644 index 0000000..cd4cc90 --- /dev/null +++ b/core/src/main/java/feign/contract/impl/HeadersAnnotationProcessor.java @@ -0,0 +1,47 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.contract.impl; + +import feign.contract.AnnotationProcessor; +import feign.contract.Header; +import feign.contract.Headers; +import feign.contract.TargetMethodDefinition.Builder; + +/** + * Annotation Processor for the {@link Headers} annotation. + */ +public class HeadersAnnotationProcessor implements AnnotationProcessor { + + private final HeaderAnnotationProcessor headerAnnotationProcessor; + + /** + * Creates a new {@link HeadersAnnotationProcessor}. + */ + public HeadersAnnotationProcessor() { + this.headerAnnotationProcessor = new HeaderAnnotationProcessor(); + } + + @Override + public void process(Headers annotation, Builder builder) { + Header[] headers = annotation.value(); + if (headers.length != 0) { + for (Header value : headers) { + this.headerAnnotationProcessor.process(value, builder); + } + } + } +} diff --git a/core/src/main/java/feign/contract/impl/ParamAnnotationProcessor.java b/core/src/main/java/feign/contract/impl/ParamAnnotationProcessor.java new file mode 100644 index 0000000..21a9a3c --- /dev/null +++ b/core/src/main/java/feign/contract/impl/ParamAnnotationProcessor.java @@ -0,0 +1,44 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.contract.impl; + +import feign.contract.Param; +import feign.contract.ParameterAnnotationProcessor; +import feign.contract.TargetMethodDefinition.Builder; +import feign.contract.TargetMethodParameterDefinition; +import feign.template.ExpressionExpander; + +/** + * Annotation Processor for the {@link Param} annotation. Registers the parameter, along with + * it's name, type and index in the method, with the method definition. + */ +public class ParamAnnotationProcessor implements ParameterAnnotationProcessor { + + @Override + public void process(Param annotation, String name, Integer index, String type, Builder builder) { + Class expanderClass = annotation.expander(); + String expanderClassName = expanderClass.getName(); + + builder.parameterDefinition( + index, TargetMethodParameterDefinition.builder() + .name(annotation.value()) + .index(index) + .type(type) + .expanderClassName(expanderClassName) + .build()); + } +} diff --git a/core/src/main/java/feign/contract/impl/RequestAnnotationProcessor.java b/core/src/main/java/feign/contract/impl/RequestAnnotationProcessor.java index 4c2b68d..eb2039f 100644 --- a/core/src/main/java/feign/contract/impl/RequestAnnotationProcessor.java +++ b/core/src/main/java/feign/contract/impl/RequestAnnotationProcessor.java @@ -1,3 +1,19 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.contract.impl; import feign.contract.AnnotationProcessor; diff --git a/core/src/main/java/feign/impl/AbstractTargetMethodHandler.java b/core/src/main/java/feign/impl/AbstractTargetMethodHandler.java index fb9c49c..37c5636 100644 --- a/core/src/main/java/feign/impl/AbstractTargetMethodHandler.java +++ b/core/src/main/java/feign/impl/AbstractTargetMethodHandler.java @@ -246,7 +246,7 @@ protected Response request(final Request request) { * @return the desired decoded result */ protected Object decode(Response response) { - TypeDefinition typeDefinition = targetMethodDefinition.getReturnType(); + TypeDefinition typeDefinition = targetMethodDefinition.getReturnTypeDefinition(); Class returnType = typeDefinition.getType(); if (void.class == returnType || (response == null || response.body() == null)) { return null; diff --git a/core/src/main/java/feign/impl/TypeDrivenMethodHandlerFactory.java b/core/src/main/java/feign/impl/TypeDrivenMethodHandlerFactory.java index 714e734..5f046e8 100644 --- a/core/src/main/java/feign/impl/TypeDrivenMethodHandlerFactory.java +++ b/core/src/main/java/feign/impl/TypeDrivenMethodHandlerFactory.java @@ -24,8 +24,9 @@ import java.util.concurrent.Future; /** - * Target Method Handler Factory that uses the {@link TargetMethodDefinition#getReturnType()} to - * determine which Method Handler to create. + * Target Method Handler Factory that uses the + * {@link TargetMethodDefinition#getReturnTypeDefinition()} to determine which Method Handler to + * create. */ public class TypeDrivenMethodHandlerFactory implements TargetMethodHandlerFactory { @@ -41,7 +42,7 @@ public class TypeDrivenMethodHandlerFactory implements TargetMethodHandlerFactor public TargetMethodHandler create(TargetMethodDefinition targetMethodDefinition, FeignConfiguration configuration) { - TypeDefinition typeDefinition = targetMethodDefinition.getReturnType(); + TypeDefinition typeDefinition = targetMethodDefinition.getReturnTypeDefinition(); if (isFuture(typeDefinition.getType())) { return new AsyncTargetMethodHandler(targetMethodDefinition, configuration); } else { diff --git a/core/src/main/java/feign/impl/type/TypeDefinitionFactory.java b/core/src/main/java/feign/impl/type/TypeDefinitionFactory.java index 2ea61a4..c718dd4 100644 --- a/core/src/main/java/feign/impl/type/TypeDefinitionFactory.java +++ b/core/src/main/java/feign/impl/type/TypeDefinitionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2019-2020 OpenFeign Contributors + * Copyright 2019-2021 OpenFeign Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -222,4 +222,6 @@ private Type getGenericSuperType(Class type, Class context) { return type; } + + } diff --git a/core/src/main/java/feign/impl/type/TypeUtils.java b/core/src/main/java/feign/impl/type/TypeUtils.java new file mode 100644 index 0000000..6c2bf06 --- /dev/null +++ b/core/src/main/java/feign/impl/type/TypeUtils.java @@ -0,0 +1,77 @@ +/* + * Copyright 2019-2021 OpenFeign Contributors + * + * 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 + * + * http://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 feign.impl.type; + +/** + * Utility Class for working with Types and Class Name. + */ +public class TypeUtils { + + /** + * Create a new Class instance for the class name provided. + * + * @param fullyQualifiedClassName to parse. + * @return the class instance, if found. + * @throws IllegalStateException if the class could not be found. + */ + public static Class getInstance(String fullyQualifiedClassName) { + try { + return Class.forName(fullyQualifiedClassName); + } catch (ClassNotFoundException cnfe) { + if (isPrimitiveType(fullyQualifiedClassName)) { + return getPrimitiveInstance(fullyQualifiedClassName); + } + throw new IllegalStateException("Error occurred obtaining class instance.", cnfe); + } + } + + private static boolean isPrimitiveType(String type) { + return Boolean.TYPE.getName().equalsIgnoreCase(type) + || Character.TYPE.getName().equalsIgnoreCase(type) + || Byte.TYPE.getName().equalsIgnoreCase(type) + || Short.TYPE.getName().equalsIgnoreCase(type) + || Integer.TYPE.getName().equalsIgnoreCase(type) + || Long.TYPE.getName().equalsIgnoreCase(type) + || Float.TYPE.getName().equalsIgnoreCase(type) + || Double.TYPE.getName().equalsIgnoreCase(type) + || Void.TYPE.getName().equalsIgnoreCase(type); + } + + private static Class getPrimitiveInstance(String type) { + if (Boolean.TYPE.getName().equalsIgnoreCase(type)) { + return Boolean.TYPE; + } else if (Character.TYPE.getName().equalsIgnoreCase(type)) { + return Character.TYPE; + } else if (Byte.TYPE.getName().equalsIgnoreCase(type)) { + return Byte.TYPE; + } else if (Short.TYPE.getName().equalsIgnoreCase(type)) { + return Short.TYPE; + } else if (Integer.TYPE.getName().equalsIgnoreCase(type)) { + return Integer.TYPE; + } else if (Long.TYPE.getName().equalsIgnoreCase(type)) { + return Long.TYPE; + } else if (Float.TYPE.getName().equalsIgnoreCase(type)) { + return Float.TYPE; + } else if (Double.TYPE.getName().equalsIgnoreCase(type)) { + return Double.TYPE; + } else if (Void.TYPE.getName().equalsIgnoreCase(type)) { + return Void.TYPE; + } + throw new IllegalArgumentException("Not a primitive type " + type); + } + +} diff --git a/core/src/test/java/feign/contract/FeignContractTest.java b/core/src/test/java/feign/contract/FeignContractTest.java index 7d89f41..8ef475a 100644 --- a/core/src/test/java/feign/contract/FeignContractTest.java +++ b/core/src/test/java/feign/contract/FeignContractTest.java @@ -55,7 +55,7 @@ void can_parseSimpleInterface() { /* verify each method is registered */ assertThat(methodDefinitions).anyMatch( targetMethodDefinition -> targetMethodDefinition.getName().equalsIgnoreCase("get") - && targetMethodDefinition.getReturnType().getType() == String.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == String.class && targetMethodDefinition.getMethod() == HttpMethod.GET && targetMethodDefinition.getParameterDefinitions().isEmpty() && targetMethodDefinition.getBody() == -1 @@ -66,7 +66,7 @@ void can_parseSimpleInterface() { /* implicit body parameter */ assertThat(methodDefinitions).anyMatch( targetMethodDefinition -> targetMethodDefinition.getName().equalsIgnoreCase("post") - && targetMethodDefinition.getReturnType().getType() == String.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == String.class && targetMethodDefinition.getMethod() == HttpMethod.POST && targetMethodDefinition.getParameterDefinitions().contains( TargetMethodParameterDefinition.builder() @@ -80,7 +80,7 @@ void can_parseSimpleInterface() { /* explicit body parameter */ assertThat(methodDefinitions).anyMatch( targetMethodDefinition -> targetMethodDefinition.getName().equalsIgnoreCase("put") - && targetMethodDefinition.getReturnType().getType() == String.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == String.class && targetMethodDefinition.getMethod() == HttpMethod.PUT && targetMethodDefinition.getParameterDefinitions() .contains(TargetMethodParameterDefinition.builder() @@ -94,7 +94,7 @@ void can_parseSimpleInterface() { /* void return type */ assertThat(methodDefinitions).anyMatch( targetMethodDefinition -> targetMethodDefinition.getName().equalsIgnoreCase("delete") - && targetMethodDefinition.getReturnType().getType() == void.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == void.class && targetMethodDefinition.getMethod() == HttpMethod.DELETE && targetMethodDefinition.getParameterDefinitions() .contains(TargetMethodParameterDefinition.builder() @@ -108,7 +108,7 @@ void can_parseSimpleInterface() { /* request options and generic return type */ assertThat(methodDefinitions).anyMatch( targetMethodDefinition -> targetMethodDefinition.getName().equalsIgnoreCase("search") - && targetMethodDefinition.getReturnType().getType() == List.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == List.class && targetMethodDefinition.getMethod() == HttpMethod.GET && targetMethodDefinition.getParameterDefinitions().isEmpty() && targetMethodDefinition.getBody() == -1 @@ -119,7 +119,7 @@ void can_parseSimpleInterface() { /* map parameter type */ assertThat(methodDefinitions).anySatisfy(targetMethodDefinition -> { boolean properties = targetMethodDefinition.getName().equalsIgnoreCase("map") - && targetMethodDefinition.getReturnType().getType() == List.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == List.class && targetMethodDefinition.getMethod() == HttpMethod.GET && targetMethodDefinition.getBody() == -1; assertThat(properties).isTrue(); @@ -134,7 +134,7 @@ void can_parseSimpleInterface() { assertThat(methodDefinitions).anySatisfy( targetMethodDefinition -> { boolean properties = targetMethodDefinition.getName().equalsIgnoreCase("list") - && targetMethodDefinition.getReturnType().getType() == List.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == List.class && targetMethodDefinition.getMethod() == HttpMethod.GET && targetMethodDefinition.getBody() == -1; assertThat(properties).isTrue(); @@ -148,7 +148,7 @@ void can_parseSimpleInterface() { /* response return type */ assertThat(methodDefinitions).anyMatch( targetMethodDefinition -> targetMethodDefinition.getName().equalsIgnoreCase("response") - && targetMethodDefinition.getReturnType().getType() == Response.class + && targetMethodDefinition.getReturnTypeDefinition().getType() == Response.class && targetMethodDefinition.getMethod() == HttpMethod.GET && targetMethodDefinition.getParameterDefinitions() .contains(TargetMethodParameterDefinition.builder() diff --git a/core/src/test/java/feign/impl/AbstractTargetMethodHandlerTest.java b/core/src/test/java/feign/impl/AbstractTargetMethodHandlerTest.java index e3e6029..a484f71 100644 --- a/core/src/test/java/feign/impl/AbstractTargetMethodHandlerTest.java +++ b/core/src/test/java/feign/impl/AbstractTargetMethodHandlerTest.java @@ -40,13 +40,11 @@ import feign.Response; import feign.ResponseDecoder; import feign.Retry; -import feign.contract.TargetMethodDefinition; import feign.TargetMethodHandler; +import feign.contract.TargetMethodDefinition; import feign.contract.TargetMethodParameterDefinition; import feign.http.HttpMethod; import feign.http.RequestSpecification; -import feign.impl.type.TypeDefinition; -import feign.impl.type.TypeDefinitionFactory; import feign.retry.NoRetry; import feign.template.ExpanderRegistry; import feign.template.expander.CachingExpanderRegistry; @@ -92,8 +90,6 @@ class AbstractTargetMethodHandlerTest { @Mock private FeignConfiguration configuration; - private final TypeDefinitionFactory typeDefinitionFactory = new TypeDefinitionFactory(); - private final RequestInterceptor interceptor = RequestInterceptor.identity(); private final Retry retry = new NoRetry(); @@ -118,9 +114,7 @@ void setUp() { void interceptors_areApplied_ifPresent() throws Throwable { when(this.client.request(any(Request.class))).thenReturn(this.response); when(this.response.body()).thenReturn(mock(InputStream.class)); - TypeDefinition returnType = this.typeDefinitionFactory - .create(String.class, TestInterface.class); - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -147,9 +141,7 @@ void interceptors_areApplied_ifPresent() throws Throwable { void interceptors_areNotApplied_ifNotPresent() throws Throwable { when(this.client.request(any(Request.class))).thenReturn(this.response); when(this.response.body()).thenReturn(mock(InputStream.class)); - TypeDefinition returnType = this.typeDefinitionFactory - .create(String.class, TestInterface.class); - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -201,9 +193,7 @@ public byte[] getData() { } }); - TypeDefinition returnType = this.typeDefinitionFactory - .create(String.class, TestInterface.class); - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -232,10 +222,7 @@ void skipEncoding_withNoBody() throws Throwable { when(this.client.request(any(Request.class))).thenReturn(this.response); when(this.response.body()).thenReturn(mock(InputStream.class)); - TypeDefinition returnType = this.typeDefinitionFactory - .create(String.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -262,10 +249,7 @@ void skipDecode_ifReturnType_isResponse() throws Throwable { when(this.client.request(any(Request.class))).thenReturn(this.response); when(this.response.body()).thenReturn(mock(InputStream.class)); - TypeDefinition returnType = this.typeDefinitionFactory - .create(Response.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(Response.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -290,10 +274,7 @@ void skipDecode_ifReturnType_isResponse() throws Throwable { @Test void skipDecode_ifResponseIsNull() throws Throwable { - TypeDefinition returnType = this.typeDefinitionFactory - .create(Response.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(Response.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -319,10 +300,7 @@ void skipDecode_ifResponseIsNull() throws Throwable { void skipDecode_ifResponseBody_isNull() throws Throwable { when(this.client.request(any(Request.class))).thenReturn(this.response); - TypeDefinition returnType = this.typeDefinitionFactory - .create(Response.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(Response.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -348,9 +326,7 @@ void skipDecode_ifResponseBody_isNull() throws Throwable { void skipDecode_ifReturnType_Void() throws Throwable { when(this.client.request(any(Request.class))).thenReturn(this.response); - TypeDefinition returnType = this.typeDefinitionFactory - .create(void.class, TestInterface.class); - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(void.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -378,10 +354,7 @@ void whenExceptionOccursBeforeRequest_exceptionHandlerIsCalled() { throw new RuntimeException("Broken"); }; - TypeDefinition returnType = this.typeDefinitionFactory - .create(Response.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(Response.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -411,10 +384,7 @@ void whenExceptionOccursBeforeRequest_exceptionHandlerIsCalled() { void whenExceptionOccursDuringRequest_exceptionHandlerIsCalled() { when(this.client.request(any(Request.class))).thenThrow(new RuntimeException("Broken")); - TypeDefinition returnType = this.typeDefinitionFactory - .create(String.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -443,10 +413,7 @@ void exceptionHandlerCalled_ifErrorDuringDecode() { when(this.response.body()).thenReturn(mock(InputStream.class)); when(this.decoder.decode(any(Response.class), any())).thenThrow(new RuntimeException("bad")); - TypeDefinition returnType = this.typeDefinitionFactory - .create(String.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) @@ -477,10 +444,7 @@ void exceptionHandlerCalled_ifErrorDuringDecode() { @Test void ensureTemplateParameters_areCached() { - TypeDefinition returnType = this.typeDefinitionFactory - .create(String.class, TestInterface.class); - - this.targetMethodDefinition.returnType(returnType) + this.targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")) .uri("/resources/{name}") .method(HttpMethod.GET) diff --git a/core/src/test/java/feign/impl/BlockingTargetMethodHandlerTest.java b/core/src/test/java/feign/impl/BlockingTargetMethodHandlerTest.java index 7007fb6..54b40f4 100644 --- a/core/src/test/java/feign/impl/BlockingTargetMethodHandlerTest.java +++ b/core/src/test/java/feign/impl/BlockingTargetMethodHandlerTest.java @@ -26,12 +26,10 @@ import feign.Logger; import feign.RequestEncoder; import feign.ResponseDecoder; -import feign.Retry; -import feign.contract.TargetMethodDefinition; import feign.TargetMethodHandler; import feign.contract.Request; +import feign.contract.TargetMethodDefinition; import feign.http.HttpMethod; -import feign.impl.type.TypeDefinitionFactory; import feign.retry.NoRetry; import feign.support.AuditingExecutor; import java.util.Collections; @@ -46,8 +44,6 @@ class BlockingTargetMethodHandlerTest { @Mock private FeignConfiguration configuration; - private final TypeDefinitionFactory typeDefinitionFactory = new TypeDefinitionFactory(); - @Test void usingDefaultExecutor_willUseTheCallingThread() throws Throwable { AuditingExecutor executor = new AuditingExecutor(); @@ -63,7 +59,7 @@ void usingDefaultExecutor_willUseTheCallingThread() throws Throwable { .thenReturn(Collections.emptyList()); TargetMethodDefinition.Builder builder = TargetMethodDefinition.builder(Blog.class.getName()); - builder.returnType(this.typeDefinitionFactory.create(void.class, Blog.class)) + builder.returnTypeFullyQualifiedClassName(void.class.getName()) .uri("/resources/{name}") .method(HttpMethod.GET); @@ -83,6 +79,7 @@ void usingDefaultExecutor_willUseTheCallingThread() throws Throwable { assertThat(executor.getExecutionCount()).isEqualTo(6); } + @SuppressWarnings("unused") interface Blog { @Request(value = "/") diff --git a/core/src/test/java/feign/impl/TypeDrivenMethodHandlerFactoryTest.java b/core/src/test/java/feign/impl/TypeDrivenMethodHandlerFactoryTest.java index 300de92..45b6d85 100644 --- a/core/src/test/java/feign/impl/TypeDrivenMethodHandlerFactoryTest.java +++ b/core/src/test/java/feign/impl/TypeDrivenMethodHandlerFactoryTest.java @@ -29,7 +29,6 @@ import feign.Retry; import feign.TargetMethodHandler; import feign.contract.TargetMethodDefinition; -import feign.impl.type.TypeDefinitionFactory; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @@ -46,8 +45,6 @@ class TypeDrivenMethodHandlerFactoryTest { @Mock private FeignConfiguration configuration; - private final TypeDefinitionFactory typeDefinitionFactory = new TypeDefinitionFactory(); - private TargetMethodDefinition.Builder targetMethodDefinition; private TypeDrivenMethodHandlerFactory methodHandlerFactory; @@ -71,7 +68,7 @@ void setUp() { void createsBlockingHandler_byDefault() { this.targetMethodDefinition = TargetMethodDefinition.builder(Blog.class.getName()); - targetMethodDefinition.returnType(this.typeDefinitionFactory.create(String.class, Blog.class)) + targetMethodDefinition.returnTypeFullyQualifiedClassName(String.class.getName()) .target(new AbsoluteUriTarget("http://localhost")); TargetMethodHandler targetMethodHandler = @@ -84,7 +81,7 @@ void createsBlockingHandler_byDefault() { void createsAsyncHandler_whenReturnType_isFuture() { this.targetMethodDefinition = TargetMethodDefinition.builder(Blog.class.getName()); - targetMethodDefinition.returnType(this.typeDefinitionFactory.create(Future.class, Blog.class)) + targetMethodDefinition.returnTypeFullyQualifiedClassName(Future.class.getName()) .target(new AbsoluteUriTarget("http://localhost")); TargetMethodHandler targetMethodHandler = @@ -98,7 +95,7 @@ void createsAsyncHandler_whenReturnType_isCompletableFuture() { this.targetMethodDefinition = TargetMethodDefinition.builder(Blog.class.getName()); targetMethodDefinition - .returnType(this.typeDefinitionFactory.create(CompletableFuture.class, Blog.class)) + .returnTypeFullyQualifiedClassName(CompletableFuture.class.getName()) .target(new AbsoluteUriTarget("http://localhost")); TargetMethodHandler targetMethodHandler =