From 7df57e64043bb2223661307b1661aa2c7ad7c7e0 Mon Sep 17 00:00:00 2001
From: Marvin Herman Froeder These specific cases are inspired by the
- * OpenAPI specification.
+ * These specific cases are inspired by the OpenAPI
+ * specification.
+ * Calling EXPLODED.join("foo", ["bar"]) will return "foo=bar".
+ * Calling EXPLODED.join("foo", ["bar"]) will return "foo=bar".
+ * Calling CSV.join("foo", ["bar", "baz"]) will return "foo=bar,baz".
+ * Calling CSV.join("foo", ["bar", "baz"]) will return "foo=bar,baz".
+ * Null values are treated somewhat specially. With EXPLODED, the field
- * is repeated without any "=" for backwards compatibility. With all other
- * formats, null values are not included in the joined value list.
+ * Null values are treated somewhat specially. With EXPLODED, the field is repeated without any
+ * "=" for backwards compatibility. With all other formats, null values are not included in the
+ * joined value list.
+ * Here are some sample encodings:
+ *
+ * Here are some sample encodings:
*
* >() {
- }.getType();
+ type = new TypeReference
>() {}.getType();
break;
case "iterator":
decoder = JacksonIteratorDecoder.create();
- type = new TypeReference
ex.
+ * expanded before the request is submitted.
+ * ex.
+ *
*
* @Body("<v01:getResourceRecordsOfZone><zoneName>{zoneName}</zoneName><rrType>0</rrType></v01:getResourceRecordsOfZone>")
* List<Record> listByZone(@Param("zoneName") String zoneName);
*
- *
Note that if you'd like curly braces literally in the body, urlencode them first.
+ *
+ *
+ * Note that if you'd like curly braces literally in the body, urlencode them first.
*
* @see RequestTemplate#expand(String, Map)
*/
diff --git a/core/src/main/java/feign/Client.java b/core/src/main/java/feign/Client.java
index c7faa57e59..02fb8d5995 100644
--- a/core/src/main/java/feign/Client.java
+++ b/core/src/main/java/feign/Client.java
@@ -14,7 +14,6 @@
package feign;
import static java.lang.String.format;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -26,13 +25,10 @@
import java.util.Map;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
-
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
-
import feign.Request.Options;
-
import static feign.Util.CONTENT_ENCODING;
import static feign.Util.CONTENT_LENGTH;
import static feign.Util.ENCODING_DEFLATE;
@@ -73,8 +69,7 @@ public Response execute(Request request, Options options) throws IOException {
}
HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
- final HttpURLConnection
- connection =
+ final HttpURLConnection connection =
(HttpURLConnection) new URL(request.url()).openConnection();
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection sslCon = (HttpsURLConnection) connection;
@@ -92,11 +87,9 @@ HttpURLConnection convertAndSend(Request request, Options options) throws IOExce
connection.setRequestMethod(request.method());
Collection
In
- * implementation, Feign is a {@link Feign#newInstance factory} for generating {@link Target
+ * Feign's purpose is to ease development against http apis that feign restfulness.
+ * In implementation, Feign is a {@link Feign#newInstance factory} for generating {@link Target
* targeted} http apis.
*/
public abstract class Feign {
@@ -39,11 +38,13 @@ public static Builder builder() {
}
/**
- * Configuration keys are formatted as unresolved see tags. This method exposes that format, in case you need to create the same value as
+ * Configuration keys are formatted as unresolved see
+ * tags. This method exposes that format, in case you need to create the same value as
* {@link MethodMetadata#configKey()} for correlation purposes.
*
- *
*
@@ -161,11 +162,13 @@ public Builder mapAndDecode(ResponseMapper mapper, Decoder decoder) {
* This flag indicates that the {@link #decoder(Decoder) decoder} should process responses with
* 404 status, specifically returning null or empty instead of throwing {@link FeignException}.
*
- * All first-party (ex gson) decoders return well-known empty values defined by {@link
- * Util#emptyValueOf}. To customize further, wrap an existing {@link #decoder(Decoder) decoder}
- * or make your own.
+ *
+ * All first-party (ex gson) decoders return well-known empty values defined by
+ * {@link Util#emptyValueOf}. To customize further, wrap an existing {@link #decoder(Decoder)
+ * decoder} or make your own.
*
- * This flag only works with 404, as opposed to all or arbitrary status codes. This was an
+ *
+ * This flag only works with 404, as opposed to all or arbitrary status codes. This was an
* explicit decision: 404 -> empty is safe, common and doesn't complicate redirection, retry or
* fallback policy. If your server returns a different status for not-found, correct via a
* custom {@link #client(Client) client}.
@@ -216,15 +219,14 @@ public Builder invocationHandlerFactory(InvocationHandlerFactory invocationHandl
}
/**
- * This flag indicates that the response should not be automatically closed
- * upon completion of decoding the message. This should be set if you plan on
- * processing the response into a lazy-evaluated construct, such as a
- * {@link java.util.Iterator}.
+ * This flag indicates that the response should not be automatically closed upon completion of
+ * decoding the message. This should be set if you plan on processing the response into a
+ * lazy-evaluated construct, such as a {@link java.util.Iterator}.
*
- *
* ...
* @RequestLine("GET /servers/{serverId}")
* void get(@Param("serverId") String serverId, @HeaderMap Map);
* ...
*
- * The annotated parameter must be an instance of {@link Map}, and the keys must
- * be Strings. The header field value of a key will be the value of its toString
- * method, except in the following cases:
- *
* @Headers("Content-Type: application/xml")
* interface SoapApi {
@@ -37,13 +38,21 @@
* }) void post(@Param("token") String token);
* ...
*
- *
* @RequestLine("POST /")
* @Headers({
@@ -51,7 +60,10 @@
* }) void post(@Named("token") String token);
* ...
*
- *
* @POST @Path("/")
* void post(@HeaderParam("X-Ping") String token);
diff --git a/core/src/main/java/feign/Logger.java b/core/src/main/java/feign/Logger.java
index 3ce3188f70..e34dd551c6 100644
--- a/core/src/main/java/feign/Logger.java
+++ b/core/src/main/java/feign/Logger.java
@@ -19,13 +19,12 @@
import java.util.logging.FileHandler;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
-
import static feign.Util.UTF_8;
import static feign.Util.decodeOrDefault;
import static feign.Util.valuesOrEmpty;
/**
- * Simple logging abstraction for debug messages. Adapted from {@code retrofit.RestAdapter.Log}.
+ * Simple logging abstraction for debug messages. Adapted from {@code retrofit.RestAdapter.Log}.
*/
public abstract class Logger {
@@ -39,8 +38,8 @@ protected static String methodTag(String configKey) {
* request and response text.
*
* @param configKey value of {@link Feign#configKey(Class, java.lang.reflect.Method)}
- * @param format {@link java.util.Formatter format string}
- * @param args arguments applied to {@code format}
+ * @param format {@link java.util.Formatter format string}
+ * @param args arguments applied to {@code format}
*/
protected abstract void log(String configKey, String format, Object... args);
@@ -58,8 +57,7 @@ protected void logRequest(String configKey, Level logLevel, Request request) {
if (request.body() != null) {
bodyLength = request.body().length;
if (logLevel.ordinal() >= Level.FULL.ordinal()) {
- String
- bodyText =
+ String bodyText =
request.charset() != null ? new String(request.body(), request.charset()) : null;
log(configKey, ""); // CRLF
log(configKey, "%s", bodyText != null ? bodyText : "Binary data");
@@ -73,10 +71,14 @@ protected void logRetry(String configKey, Level logLevel) {
log(configKey, "---> RETRYING");
}
- protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response,
- long elapsedTime) throws IOException {
- String reason = response.reason() != null && logLevel.compareTo(Level.NONE) > 0 ?
- " " + response.reason() : "";
+ protected Response logAndRebufferResponse(String configKey,
+ Level logLevel,
+ Response response,
+ long elapsedTime)
+ throws IOException {
+ String reason =
+ response.reason() != null && logLevel.compareTo(Level.NONE) > 0 ? " " + response.reason()
+ : "";
int status = response.status();
log(configKey, "<--- HTTP/1.1 %s%s (%sms)", status, reason, elapsedTime);
if (logLevel.ordinal() >= Level.HEADERS.ordinal()) {
@@ -108,7 +110,10 @@ protected Response logAndRebufferResponse(String configKey, Level logLevel, Resp
return response;
}
- protected IOException logIOException(String configKey, Level logLevel, IOException ioe, long elapsedTime) {
+ protected IOException logIOException(String configKey,
+ Level logLevel,
+ IOException ioe,
+ long elapsedTime) {
log(configKey, "<--- ERROR %s: %s (%sms)", ioe.getClass().getSimpleName(), ioe.getMessage(),
elapsedTime);
if (logLevel.ordinal() >= Level.FULL.ordinal()) {
@@ -157,8 +162,7 @@ protected void log(String configKey, String format, Object... args) {
*/
public static class JavaLogger extends Logger {
- final java.util.logging.Logger
- logger =
+ final java.util.logging.Logger logger =
java.util.logging.Logger.getLogger(Logger.class.getName());
@Override
@@ -169,8 +173,11 @@ protected void logRequest(String configKey, Level logLevel, Request request) {
}
@Override
- protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response,
- long elapsedTime) throws IOException {
+ protected Response logAndRebufferResponse(String configKey,
+ Level logLevel,
+ Response response,
+ long elapsedTime)
+ throws IOException {
if (logger.isLoggable(java.util.logging.Level.FINE)) {
return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
}
@@ -185,8 +192,8 @@ protected void log(String configKey, String format, Object... args) {
}
/**
- * Helper that configures java.util.logging to sanely log messages at FINE level without additional
- * formatting.
+ * Helper that configures java.util.logging to sanely log messages at FINE level without
+ * additional formatting.
*/
public JavaLogger appendToFile(String logfile) {
logger.setLevel(java.util.logging.Level.FINE);
@@ -209,17 +216,18 @@ public String format(LogRecord record) {
public static class NoOpLogger extends Logger {
@Override
- protected void logRequest(String configKey, Level logLevel, Request request) {
- }
+ protected void logRequest(String configKey, Level logLevel, Request request) {}
@Override
- protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response,
- long elapsedTime) throws IOException {
+ protected Response logAndRebufferResponse(String configKey,
+ Level logLevel,
+ Response response,
+ long elapsedTime)
+ throws IOException {
return response;
}
@Override
- protected void log(String configKey, String format, Object... args) {
- }
+ protected void log(String configKey, String format, Object... args) {}
}
}
diff --git a/core/src/main/java/feign/MethodMetadata.java b/core/src/main/java/feign/MethodMetadata.java
index 431b3f86c6..d5876ca60c 100644
--- a/core/src/main/java/feign/MethodMetadata.java
+++ b/core/src/main/java/feign/MethodMetadata.java
@@ -20,7 +20,6 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-
import feign.Param.Expander;
public final class MethodMetadata implements Serializable {
@@ -43,8 +42,7 @@ public final class MethodMetadata implements Serializable {
private Map indexToEncoded = new LinkedHashMap();
private transient Map indexToExpander;
- MethodMetadata() {
- }
+ MethodMetadata() {}
/**
* Used as a reference to this method. For example, {@link Logger#log(String, String, Object...)
diff --git a/core/src/main/java/feign/Param.java b/core/src/main/java/feign/Param.java
index 0ce2ebd7c5..de1cd11366 100644
--- a/core/src/main/java/feign/Param.java
+++ b/core/src/main/java/feign/Param.java
@@ -14,13 +14,12 @@
package feign;
import java.lang.annotation.Retention;
-
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
- * A named template parameter applied to {@link Headers}, {@linkplain RequestLine} or {@linkplain
- * Body}
+ * A named template parameter applied to {@link Headers}, {@linkplain RequestLine} or
+ * {@linkplain Body}
*/
@Retention(RUNTIME)
@java.lang.annotation.Target(PARAMETER)
@@ -37,8 +36,8 @@
Class extends Expander> expander() default ToStringExpander.class;
/**
- * Specifies whether argument is already encoded
- * The value is ignored for headers (headers are never encoded)
+ * Specifies whether argument is already encoded The value is ignored for headers (headers are
+ * never encoded)
*
* @see QueryMap#encoded
*/
diff --git a/core/src/main/java/feign/QueryMap.java b/core/src/main/java/feign/QueryMap.java
index 67368e4f2f..af8b92be13 100644
--- a/core/src/main/java/feign/QueryMap.java
+++ b/core/src/main/java/feign/QueryMap.java
@@ -16,18 +16,17 @@
import java.lang.annotation.Retention;
import java.util.List;
import java.util.Map;
-
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
- * A template parameter that can be applied to a Map that contains query
- * parameters, where the keys are Strings that are the parameter names and the
- * values are the parameter values. The queries specified by the map will be
- * applied to the request after all other processing, and will take precedence
- * over any previously specified query parameters. It is not necessary to
- * reference the parameter map as a variable.
+ * A template parameter that can be applied to a Map that contains query parameters, where the keys
+ * are Strings that are the parameter names and the values are the parameter values. The queries
+ * specified by the map will be applied to the request after all other processing, and will take
+ * precedence over any previously specified query parameters. It is not necessary to reference the
+ * parameter map as a variable.
*
+ *
*
* ...
* @RequestLine("POST /servers")
@@ -38,30 +37,29 @@
* void get(@Param("serverId") String serverId, @Param("count") int count, @QueryMap Map);
* ...
*
- * The annotated parameter must be an instance of {@link Map}, and the keys must
- * be Strings. The query value of a key will be the value of its toString
- * method, except in the following cases:
+ *
+ * The annotated parameter must be an instance of {@link Map}, and the keys must be Strings. The
+ * query value of a key will be the value of its toString method, except in the following cases:
*
*
*
- * - if the value is null, the value will remain null (rather than converting
- * to the String "null")
- *
- if the value is an {@link Iterable}, it is converted to a {@link List} of
- * String objects where each value in the list is either null if the original
- * value was null or the value's toString representation otherwise.
+ *
- if the value is null, the value will remain null (rather than converting to the String
+ * "null")
+ *
- if the value is an {@link Iterable}, it is converted to a {@link List} of String objects
+ * where each value in the list is either null if the original value was null or the value's
+ * toString representation otherwise.
*
*
- * Once this conversion is applied, the query keys and resulting String values
- * follow the same contract as if they were set using
- * {@link RequestTemplate#query(String, String...)}.
+ * Once this conversion is applied, the query keys and resulting String values follow the same
+ * contract as if they were set using {@link RequestTemplate#query(String, String...)}.
*/
@Retention(RUNTIME)
@java.lang.annotation.Target(PARAMETER)
public @interface QueryMap {
- /**
- * Specifies whether parameter names and values are already encoded.
- *
- * @see Param#encoded
- */
- boolean encoded() default false;
+ /**
+ * Specifies whether parameter names and values are already encoded.
+ *
+ * @see Param#encoded
+ */
+ boolean encoded() default false;
}
diff --git a/core/src/main/java/feign/QueryMapEncoder.java b/core/src/main/java/feign/QueryMapEncoder.java
index b6909823b4..fb7de67d6f 100644
--- a/core/src/main/java/feign/QueryMapEncoder.java
+++ b/core/src/main/java/feign/QueryMapEncoder.java
@@ -32,7 +32,7 @@ public interface QueryMapEncoder {
* @param object the object to encode
* @return the map represented by the object
*/
- Map encode (Object object);
+ Map encode(Object object);
class Default implements QueryMapEncoder {
@@ -40,7 +40,7 @@ class Default implements QueryMapEncoder {
new HashMap, ObjectParamMetadata>();
@Override
- public Map encode (Object object) throws EncodeException {
+ public Map encode(Object object) throws EncodeException {
try {
ObjectParamMetadata metadata = getMetadata(object.getClass());
Map fieldNameToValue = new HashMap();
@@ -69,7 +69,7 @@ private static class ObjectParamMetadata {
private final List objectFields;
- private ObjectParamMetadata (List objectFields) {
+ private ObjectParamMetadata(List objectFields) {
this.objectFields = Collections.unmodifiableList(objectFields);
}
diff --git a/core/src/main/java/feign/ReflectiveFeign.java b/core/src/main/java/feign/ReflectiveFeign.java
index 91332e8671..36f14811aa 100644
--- a/core/src/main/java/feign/ReflectiveFeign.java
+++ b/core/src/main/java/feign/ReflectiveFeign.java
@@ -18,7 +18,6 @@
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.Map.Entry;
-
import feign.InvocationHandlerFactory.MethodHandler;
import feign.Param.Expander;
import feign.Request.Options;
@@ -26,7 +25,6 @@
import feign.codec.EncodeException;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
-
import static feign.Util.checkArgument;
import static feign.Util.checkNotNull;
@@ -36,7 +34,8 @@ public class ReflectiveFeign extends Feign {
private final InvocationHandlerFactory factory;
private final QueryMapEncoder queryMapEncoder;
- ReflectiveFeign(ParseHandlersByName targetToHandlersByName, InvocationHandlerFactory factory, QueryMapEncoder queryMapEncoder) {
+ ReflectiveFeign(ParseHandlersByName targetToHandlersByName, InvocationHandlerFactory factory,
+ QueryMapEncoder queryMapEncoder) {
this.targetToHandlersByName = targetToHandlersByName;
this.factory = factory;
this.queryMapEncoder = queryMapEncoder;
@@ -56,7 +55,7 @@ public T newInstance(Target target) {
for (Method method : target.type().getMethods()) {
if (method.getDeclaringClass() == Object.class) {
continue;
- } else if(Util.isDefault(method)) {
+ } else if (Util.isDefault(method)) {
DefaultMethodHandler handler = new DefaultMethodHandler(method);
defaultMethodHandlers.add(handler);
methodToHandler.put(method, handler);
@@ -65,9 +64,10 @@ public T newInstance(Target target) {
}
}
InvocationHandler handler = factory.create(target, methodToHandler);
- T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(), new Class>[]{target.type()}, handler);
+ T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(),
+ new Class>[] {target.type()}, handler);
- for(DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
+ for (DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
defaultMethodHandler.bindTo(proxy);
}
return proxy;
@@ -87,8 +87,7 @@ static class FeignInvocationHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("equals".equals(method.getName())) {
try {
- Object
- otherHandler =
+ Object otherHandler =
args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
} catch (IllegalArgumentException e) {
@@ -162,7 +161,7 @@ public Map apply(Target key) {
buildTemplate = new BuildTemplateByResolvingArgs(md, queryMapEncoder);
}
result.put(md.configKey(),
- factory.create(key, md, buildTemplate, options, decoder, errorDecoder));
+ factory.create(key, md, buildTemplate, options, decoder, errorDecoder));
}
return result;
}
@@ -230,15 +229,16 @@ public RequestTemplate create(Object[] argv) {
}
if (metadata.headerMapIndex() != null) {
- template = addHeaderMapHeaders((Map) argv[metadata.headerMapIndex()], template);
+ template =
+ addHeaderMapHeaders((Map) argv[metadata.headerMapIndex()], template);
}
return template;
}
- private Map toQueryMap (Object value) {
- if (value instanceof Map) {
- return (Map)value;
+ private Map toQueryMap(Object value) {
+ if (value instanceof Map) {
+ return (Map) value;
}
try {
return queryMapEncoder.encode(value);
@@ -257,7 +257,7 @@ private Object expandElements(Expander expander, Object value) {
private List expandIterable(Expander expander, Iterable value) {
List values = new ArrayList();
for (Object element : value) {
- if (element!=null) {
+ if (element != null) {
values.add(expander.expand(element));
}
}
@@ -265,7 +265,8 @@ private List expandIterable(Expander expander, Iterable value) {
}
@SuppressWarnings("unchecked")
- private RequestTemplate addHeaderMapHeaders(Map headerMap, RequestTemplate mutable) {
+ private RequestTemplate addHeaderMapHeaders(Map headerMap,
+ RequestTemplate mutable) {
for (Entry currEntry : headerMap.entrySet()) {
Collection values = new ArrayList();
@@ -286,7 +287,8 @@ private RequestTemplate addHeaderMapHeaders(Map headerMap, Reque
}
@SuppressWarnings("unchecked")
- private RequestTemplate addQueryMapQueryParameters(Map queryMap, RequestTemplate mutable) {
+ private RequestTemplate addQueryMapQueryParameters(Map queryMap,
+ RequestTemplate mutable) {
for (Entry currEntry : queryMap.entrySet()) {
Collection values = new ArrayList();
@@ -296,18 +298,23 @@ private RequestTemplate addQueryMapQueryParameters(Map queryMap,
Iterator> iter = ((Iterable>) currValue).iterator();
while (iter.hasNext()) {
Object nextObject = iter.next();
- values.add(nextObject == null ? null : encoded ? nextObject.toString() : RequestTemplate.urlEncode(nextObject.toString()));
+ values.add(nextObject == null ? null
+ : encoded ? nextObject.toString()
+ : RequestTemplate.urlEncode(nextObject.toString()));
}
} else {
- values.add(currValue == null ? null : encoded ? currValue.toString() : RequestTemplate.urlEncode(currValue.toString()));
+ values.add(currValue == null ? null
+ : encoded ? currValue.toString() : RequestTemplate.urlEncode(currValue.toString()));
}
- mutable.query(true, encoded ? currEntry.getKey() : RequestTemplate.urlEncode(currEntry.getKey()), values);
+ mutable.query(true,
+ encoded ? currEntry.getKey() : RequestTemplate.urlEncode(currEntry.getKey()), values);
}
return mutable;
}
- protected RequestTemplate resolve(Object[] argv, RequestTemplate mutable,
+ protected RequestTemplate resolve(Object[] argv,
+ RequestTemplate mutable,
Map variables) {
// Resolving which variable names are already encoded using their indices
Map variableToEncoded = new LinkedHashMap();
@@ -325,13 +332,15 @@ private static class BuildFormEncodedTemplateFromArgs extends BuildTemplateByRes
private final Encoder encoder;
- private BuildFormEncodedTemplateFromArgs(MethodMetadata metadata, Encoder encoder, QueryMapEncoder queryMapEncoder) {
+ private BuildFormEncodedTemplateFromArgs(MethodMetadata metadata, Encoder encoder,
+ QueryMapEncoder queryMapEncoder) {
super(metadata, queryMapEncoder);
this.encoder = encoder;
}
@Override
- protected RequestTemplate resolve(Object[] argv, RequestTemplate mutable,
+ protected RequestTemplate resolve(Object[] argv,
+ RequestTemplate mutable,
Map variables) {
Map formVariables = new LinkedHashMap();
for (Entry entry : variables.entrySet()) {
@@ -354,13 +363,15 @@ private static class BuildEncodedTemplateFromArgs extends BuildTemplateByResolvi
private final Encoder encoder;
- private BuildEncodedTemplateFromArgs(MethodMetadata metadata, Encoder encoder, QueryMapEncoder queryMapEncoder) {
+ private BuildEncodedTemplateFromArgs(MethodMetadata metadata, Encoder encoder,
+ QueryMapEncoder queryMapEncoder) {
super(metadata, queryMapEncoder);
this.encoder = encoder;
}
@Override
- protected RequestTemplate resolve(Object[] argv, RequestTemplate mutable,
+ protected RequestTemplate resolve(Object[] argv,
+ RequestTemplate mutable,
Map variables) {
Object body = argv[metadata.bodyIndex()];
checkArgument(body != null, "Body parameter %s was null", metadata.bodyIndex());
diff --git a/core/src/main/java/feign/Request.java b/core/src/main/java/feign/Request.java
index 8890d8102e..f3b2aa12c8 100644
--- a/core/src/main/java/feign/Request.java
+++ b/core/src/main/java/feign/Request.java
@@ -17,7 +17,6 @@
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Map;
-
import static feign.Util.checkNotNull;
import static feign.Util.valuesOrEmpty;
@@ -30,8 +29,11 @@ public final class Request {
* No parameters can be null except {@code body} and {@code charset}. All parameters must be
* effectively immutable, via safe copies, not mutating or otherwise.
*/
- public static Request create(String method, String url, Map> headers,
- byte[] body, Charset charset) {
+ public static Request create(String method,
+ String url,
+ Map> headers,
+ byte[] body,
+ Charset charset) {
return new Request(method, url, headers, body, charset);
}
@@ -42,7 +44,7 @@ public static Request create(String method, String url, Map> headers, byte[] body,
- Charset charset) {
+ Charset charset) {
this.method = checkNotNull(method, "method of %s", url);
this.url = checkNotNull(url, "url");
this.headers = checkNotNull(headers, "headers of %s %s", method, url);
@@ -66,7 +68,7 @@ public Map> headers() {
}
/**
- * The character set with which the body is encoded, or null if unknown or not applicable. When
+ * The character set with which the body is encoded, or null if unknown or not applicable. When
* this is present, you can use {@code new String(req.body(), req.charset())} to access the body
* as a String.
*/
@@ -75,7 +77,7 @@ public Charset charset() {
}
/**
- * If present, this is the replayable body to send to the server. In some cases, this may be
+ * If present, this is the replayable body to send to the server. In some cases, this may be
* interpretable as text.
*
* @see #charset()
@@ -99,7 +101,10 @@ public String toString() {
return builder.toString();
}
- /* Controls the per-request settings currently required to be implemented by all {@link Client clients} */
+ /*
+ * Controls the per-request settings currently required to be implemented by all {@link Client
+ * clients}
+ */
public static class Options {
private final int connectTimeoutMillis;
@@ -112,7 +117,7 @@ public Options(int connectTimeoutMillis, int readTimeoutMillis, boolean followRe
this.followRedirects = followRedirects;
}
- public Options(int connectTimeoutMillis, int readTimeoutMillis){
+ public Options(int connectTimeoutMillis, int readTimeoutMillis) {
this(connectTimeoutMillis, readTimeoutMillis, true);
}
diff --git a/core/src/main/java/feign/RequestInterceptor.java b/core/src/main/java/feign/RequestInterceptor.java
index 8e8deb219b..24493f5620 100644
--- a/core/src/main/java/feign/RequestInterceptor.java
+++ b/core/src/main/java/feign/RequestInterceptor.java
@@ -15,21 +15,35 @@
/**
* Zero or more {@code RequestInterceptors} may be configured for purposes such as adding headers to
- * all requests. No guarantees are give with regards to the order that interceptors are applied.
+ * all requests. No guarantees are give with regards to the order that interceptors are applied.
* Once interceptors are applied, {@link Target#apply(RequestTemplate)} is called to create the
- * immutable http request sent via {@link Client#execute(Request, feign.Request.Options)}.
+ * immutable http request sent via {@link Client#execute(Request, feign.Request.Options)}.
+ *
* For example:
+ *
*
* public void apply(RequestTemplate input) {
- * input.header("X-Auth", currentToken);
+ * input.header("X-Auth", currentToken);
* }
*
- *
Configuration
{@code RequestInterceptors} are configured via {@link
- * Feign.Builder#requestInterceptors}.
Implementation notes
Do not add
- * parameters, such as {@code /path/{foo}/bar } in your implementation of {@link
- * #apply(RequestTemplate)}.
Interceptors are applied after the template's parameters are
- * {@link RequestTemplate#resolve(java.util.Map) resolved}. This is to ensure that you can
- * implement signatures are interceptors.
Relationship to Retrofit 1.x
+ *
+ *
+ *
+ * Configuration
+ *
+ * {@code RequestInterceptors} are configured via {@link Feign.Builder#requestInterceptors}.
+ *
+ * Implementation notes
+ *
+ * Do not add parameters, such as {@code /path/{foo}/bar } in your implementation of
+ * {@link #apply(RequestTemplate)}.
+ * Interceptors are applied after the template's parameters are
+ * {@link RequestTemplate#resolve(java.util.Map) resolved}. This is to ensure that you can implement
+ * signatures are interceptors.
+ *
+ *
+ * Relationship to Retrofit 1.x
+ *
* This class is similar to {@code RequestInterceptor.intercept()}, except that the implementation
* can read, remove, or otherwise mutate any part of the request template.
*/
diff --git a/core/src/main/java/feign/RequestLine.java b/core/src/main/java/feign/RequestLine.java
index 076506c104..2398f51dca 100644
--- a/core/src/main/java/feign/RequestLine.java
+++ b/core/src/main/java/feign/RequestLine.java
@@ -14,13 +14,13 @@
package feign;
import java.lang.annotation.Retention;
-
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Expands the request-line supplied in the {@code value}, permitting path and query variables, or
* just the http method.
+ *
*
* ...
* @RequestLine("POST /servers")
@@ -34,21 +34,33 @@
* Response getNext(URI nextLink);
* ...
*
- * HTTP version suffix is optional, but permitted. There are no guarantees this version will impact
+ *
+ * HTTP version suffix is optional, but permitted. There are no guarantees this version will impact
* that sent by the client.
+ *
*
* @RequestLine("POST /servers HTTP/1.1")
* ...
*
- *
Note: Query params do not overwrite each other. All queries with the same
- * name will be included in the request.
Relationship to JAXRS
The following
- * two forms are identical.
Feign:
+ *
+ *
+ * Note: Query params do not overwrite each other. All queries with the same name
+ * will be included in the request.
+ *
+ * Relationship to JAXRS
+ *
+ * The following two forms are identical.
+ * Feign:
+ *
*
* @RequestLine("GET /servers/{serverId}?count={count}")
* void get(@Param("serverId") String serverId, @Param("count") int count);
* ...
*
- *
JAX-RS:
+ *
+ *
+ * JAX-RS:
+ *
*
* @GET @Path("/servers/{serverId}")
* void get(@PathParam("serverId") String serverId, @QueryParam("count") int count);
@@ -60,6 +72,8 @@
public @interface RequestLine {
String value();
+
boolean decodeSlash() default true;
+
CollectionFormat collectionFormat() default CollectionFormat.EXPLODED;
}
diff --git a/core/src/main/java/feign/RequestTemplate.java b/core/src/main/java/feign/RequestTemplate.java
index 35752bbd7e..37c3831934 100644
--- a/core/src/main/java/feign/RequestTemplate.java
+++ b/core/src/main/java/feign/RequestTemplate.java
@@ -27,7 +27,6 @@
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
import static feign.Util.CONTENT_LENGTH;
import static feign.Util.UTF_8;
import static feign.Util.checkArgument;
@@ -37,8 +36,12 @@
import static feign.Util.valuesOrEmpty;
/**
- * Builds a request to an http target. Not thread safe.
relationship to JAXRS
- * 2.0
A combination of {@code javax.ws.rs.client.WebTarget} and {@code
+ * Builds a request to an http target. Not thread safe.
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * A combination of {@code javax.ws.rs.client.WebTarget} and {@code
* javax.ws.rs.client.Invocation.Builder}, ensuring you can modify any part of the request. However,
* this object is mutable, so needs to be guarded with the copy constructor.
*/
@@ -58,8 +61,7 @@ public final class RequestTemplate implements Serializable {
private boolean decodeSlash = true;
private CollectionFormat collectionFormat = CollectionFormat.EXPLODED;
- public RequestTemplate() {
- }
+ public RequestTemplate() {}
/* Copy constructor. Use this when making templates. */
public RequestTemplate(RequestTemplate toCopy) {
@@ -92,11 +94,12 @@ static String urlEncode(Object arg) {
}
private static boolean isHttpUrl(CharSequence value) {
- return value.length() >= 4 && value.subSequence(0, 3).equals("http".substring(0, 3));
+ return value.length() >= 4 && value.subSequence(0, 3).equals("http".substring(0, 3));
}
private static CharSequence removeTrailingSlash(CharSequence charSequence) {
- if (charSequence != null && charSequence.length() > 0 && charSequence.charAt(charSequence.length() - 1) == '/') {
+ if (charSequence != null && charSequence.length() > 0
+ && charSequence.charAt(charSequence.length() - 1) == '/') {
return charSequence.subSequence(0, charSequence.length() - 1);
} else {
return charSequence;
@@ -105,11 +108,11 @@ private static CharSequence removeTrailingSlash(CharSequence charSequence) {
/**
* Expands a {@code template}, such as {@code username}, using the {@code variables} supplied. Any
- * unresolved parameters will remain.
Note that if you'd like curly braces literally in the
- * {@code template}, urlencode them first.
+ * unresolved parameters will remain.
+ * Note that if you'd like curly braces literally in the {@code template}, urlencode them first.
*
- * @param template URI template that can be in level 1 RFC6570
- * form.
+ * @param template URI template that can be in level 1
+ * RFC6570 form.
* @param variables to the URI template
* @return expanded template, leaving any unresolved parameters literal
*/
@@ -207,9 +210,14 @@ public RequestTemplate resolve(Map unencoded) {
/**
* Resolves any template parameters in the requests path, query, or headers against the supplied
- * unencoded arguments.
relationship to JAXRS 2.0
This call is
- * similar to {@code javax.ws.rs.client.WebTarget.resolveTemplates(templateValues, true)} , except
- * that the template values apply to any part of the request, not just the URL
+ * unencoded arguments.
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * This call is similar to
+ * {@code javax.ws.rs.client.WebTarget.resolveTemplates(templateValues, true)} , except that the
+ * template values apply to any part of the request, not just the URL
*/
RequestTemplate resolve(Map unencoded, Map alreadyEncoded) {
replaceQueryValues(unencoded, alreadyEncoded);
@@ -226,7 +234,8 @@ RequestTemplate resolve(Map unencoded, Map alreadyEn
}
url = new StringBuilder(resolvedUrl);
- Map> resolvedHeaders = new LinkedHashMap>();
+ Map> resolvedHeaders =
+ new LinkedHashMap>();
for (String field : headers.keySet()) {
Collection resolvedValues = new ArrayList();
for (String value : valuesOrEmpty(headers, field)) {
@@ -243,7 +252,9 @@ RequestTemplate resolve(Map unencoded, Map alreadyEn
return this;
}
- private String encodeValueIfNotEncoded(String key, Object objectValue, Map alreadyEncoded) {
+ private String encodeValueIfNotEncoded(String key,
+ Object objectValue,
+ Map alreadyEncoded) {
String value = String.valueOf(objectValue);
final Boolean isEncoded = alreadyEncoded.get(key);
if (isEncoded == null || !isEncoded) {
@@ -259,8 +270,7 @@ public Request request() {
return Request.create(
method, url + queryLine(),
Collections.unmodifiableMap(safeCopy),
- body, charset
- );
+ body, charset);
}
/* @see Request#method() */
@@ -269,7 +279,7 @@ public RequestTemplate method(String method) {
checkArgument(method.matches("^[A-Z]+$"), "Invalid HTTP Method: %s", method);
return this;
}
-
+
/* @see Request#method() */
public String method() {
return method;
@@ -279,7 +289,7 @@ public RequestTemplate decodeSlash(boolean decodeSlash) {
this.decodeSlash = decodeSlash;
return this;
}
-
+
public boolean decodeSlash() {
return decodeSlash;
}
@@ -302,9 +312,9 @@ public RequestTemplate append(CharSequence value) {
/* @see #url() */
public RequestTemplate insert(int pos, CharSequence value) {
- if(isHttpUrl(value)) {
+ if (isHttpUrl(value)) {
value = removeTrailingSlash(value);
- if(url.length() > 0 && url.charAt(0) != '/') {
+ if (url.length() > 0 && url.charAt(0) != '/') {
url.insert(0, '/');
}
}
@@ -317,27 +327,36 @@ public String url() {
}
/**
- * Replaces queries with the specified {@code name} with the {@code values} supplied.
- *
Values can be passed in decoded or in url-encoded form depending on the value of the
- * {@code encoded} parameter.
- *
When the {@code value} is {@code null}, all queries with the {@code configKey} are
- * removed.
relationship to JAXRS 2.0
Like {@code WebTarget.query},
- * except the values can be templatized.
ex.
+ * Replaces queries with the specified {@code name} with the {@code values} supplied.
+ * Values can be passed in decoded or in url-encoded form depending on the value of the
+ * {@code encoded} parameter.
+ * When the {@code value} is {@code null}, all queries with the {@code configKey} are removed.
+ *
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * Like {@code WebTarget.query}, except the values can be templatized.
+ * ex.
+ *
*
* template.query("Signature", "{signature}");
*
- *
Note: behavior of RequestTemplate is not consistent if a query parameter with
- * unsafe characters is passed as both encoded and unencoded, although no validation is performed.
- *
ex.
+ *
+ *
+ * Note: behavior of RequestTemplate is not consistent if a query parameter with unsafe
+ * characters is passed as both encoded and unencoded, although no validation is performed.
+ * ex.
+ *
*
* template.query(true, "param[]", "value");
* template.query(false, "param[]", "value");
*
*
- * @param encoded whether name and values are already url-encoded
- * @param name the name of the query
- * @param values can be a single null to imply removing all values. Else no values are expected
- * to be null.
+ * @param encoded whether name and values are already url-encoded
+ * @param name the name of the query
+ * @param values can be a single null to imply removing all values. Else no values are expected to
+ * be null.
* @see #queries()
*/
public RequestTemplate query(boolean encoded, String name, String... values) {
@@ -351,6 +370,7 @@ public RequestTemplate query(boolean encoded, String name, Iterable valu
/**
* Shortcut for {@code query(false, String, String...)}
+ *
* @see #query(boolean, String, String...)
*/
public RequestTemplate query(String name, String... values) {
@@ -359,6 +379,7 @@ public RequestTemplate query(String name, String... values) {
/**
* Shortcut for {@code query(false, String, Iterable)}
+ *
* @see #query(boolean, String, String...)
*/
public RequestTemplate query(String name, Iterable values) {
@@ -395,8 +416,13 @@ private static String encodeIfNotVariable(String in) {
/**
* Replaces all existing queries with the newly supplied url decoded queries.
- *
relationship to JAXRS 2.0
Like {@code WebTarget.queries}, except the
- * values can be templatized.
ex.
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * Like {@code WebTarget.queries}, except the values can be templatized.
+ * ex.
+ *
*
* template.queries(ImmutableMultimap.of("Signature", "{signature}"));
*
@@ -439,16 +465,22 @@ public Map> queries() {
/**
* Replaces headers with the specified {@code configKey} with the {@code values} supplied.
* When the {@code value} is {@code null}, all headers with the {@code configKey} are removed.
- *
relationship to JAXRS 2.0
Like {@code WebTarget.queries} and
- * {@code javax.ws.rs.client.Invocation.Builder.header}, except the values can be templatized.
- *
ex.
+ *
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * Like {@code WebTarget.queries} and {@code javax.ws.rs.client.Invocation.Builder.header}, except
+ * the values can be templatized.
+ * ex.
+ *
*
* template.query("X-Application-Version", "{version}");
*
*
- * @param name the name of the header
+ * @param name the name of the header
* @param values can be a single null to imply removing all values. Else no values are expected to
- * be null.
+ * be null.
* @see #headers()
*/
public RequestTemplate header(String name, String... values) {
@@ -472,9 +504,15 @@ public RequestTemplate header(String name, Iterable values) {
}
/**
- * Replaces all existing headers with the newly supplied headers.
relationship to
- * JAXRS 2.0
Like {@code Invocation.Builder.headers(MultivaluedMap)}, except the
- * values can be templatized.
ex.
+ * Replaces all existing headers with the newly supplied headers.
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * Like {@code Invocation.Builder.headers(MultivaluedMap)}, except the values can be templatized.
+ *
+ * ex.
+ *
*
* template.headers(mapOf("X-Application-Version", asList("{version}")));
*
@@ -501,8 +539,8 @@ public Map> headers() {
}
/**
- * replaces the {@link feign.Util#CONTENT_LENGTH} header.
Usually populated by an {@link
- * feign.codec.Encoder}.
+ * replaces the {@link feign.Util#CONTENT_LENGTH} header.
+ * Usually populated by an {@link feign.codec.Encoder}.
*
* @see Request#body()
*/
@@ -516,8 +554,8 @@ public RequestTemplate body(byte[] bodyData, Charset charset) {
}
/**
- * replaces the {@link feign.Util#CONTENT_LENGTH} header.
Usually populated by an {@link
- * feign.codec.Encoder}.
+ * replaces the {@link feign.Util#CONTENT_LENGTH} header.
+ * Usually populated by an {@link feign.codec.Encoder}.
*
* @see Request#body()
*/
@@ -527,7 +565,7 @@ public RequestTemplate body(String bodyText) {
}
/**
- * The character set with which the body is encoded, or null if unknown or not applicable. When
+ * The character set with which the body is encoded, or null if unknown or not applicable. When
* this is present, you can use {@code new String(req.body(), req.charset())} to access the body
* as a String.
*/
@@ -575,17 +613,17 @@ private StringBuilder pullAnyQueriesOutOfUrl(StringBuilder url) {
firstQueries.putAll(queries);
queries.clear();
}
- //Since we decode all queries, we want to use the
- //query()-method to re-add them to ensure that all
- //logic (such as url-encoding) are executed, giving
- //a valid queryLine()
+ // Since we decode all queries, we want to use the
+ // query()-method to re-add them to ensure that all
+ // logic (such as url-encoding) are executed, giving
+ // a valid queryLine()
for (String key : firstQueries.keySet()) {
Collection values = firstQueries.get(key);
if (allValuesAreNull(values)) {
- //Queries where all values are null will
- //be ignored by the query(key, value)-method
- //So we manually avoid this case here, to ensure that
- //we still fulfill the contract (ex. parameters without values)
+ // Queries where all values are null will
+ // be ignored by the query(key, value)-method
+ // So we manually avoid this case here, to ensure that
+ // we still fulfill the contract (ex. parameters without values)
queries.put(urlEncode(key), values);
} else {
query(key, values);
@@ -644,7 +682,8 @@ void replaceQueryValues(Map unencoded, Map alreadyEn
values.add(encodedValue);
}
} else {
- String encodedValue = encodeValueIfNotEncoded(entry.getKey(), variableValue, alreadyEncoded);
+ String encodedValue =
+ encodeValueIfNotEncoded(entry.getKey(), variableValue, alreadyEncoded);
values.add(encodedValue);
}
} else {
diff --git a/core/src/main/java/feign/Response.java b/core/src/main/java/feign/Response.java
index dfbbf7eac0..7e846dd1cb 100644
--- a/core/src/main/java/feign/Response.java
+++ b/core/src/main/java/feign/Response.java
@@ -26,7 +26,6 @@
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
-
import static feign.Util.UTF_8;
import static feign.Util.checkNotNull;
import static feign.Util.checkState;
@@ -47,73 +46,83 @@ public final class Response implements Closeable {
private Response(Builder builder) {
checkState(builder.status >= 200, "Invalid status code: %s", builder.status);
this.status = builder.status;
- this.reason = builder.reason; //nullable
+ this.reason = builder.reason; // nullable
this.headers = Collections.unmodifiableMap(caseInsensitiveCopyOf(builder.headers));
- this.body = builder.body; //nullable
- this.request = builder.request; //nullable
+ this.body = builder.body; // nullable
+ this.request = builder.request; // nullable
}
/**
- * @deprecated To be removed in Feign 10
+ * @deprecated To be removed in Feign 10
*/
@Deprecated
- public static Response create(int status, String reason, Map> headers,
- InputStream inputStream, Integer length) {
+ public static Response create(int status,
+ String reason,
+ Map> headers,
+ InputStream inputStream,
+ Integer length) {
return Response.builder()
- .status(status)
- .reason(reason)
- .headers(headers)
- .body(InputStreamBody.orNull(inputStream, length))
- .build();
+ .status(status)
+ .reason(reason)
+ .headers(headers)
+ .body(InputStreamBody.orNull(inputStream, length))
+ .build();
}
/**
- * @deprecated To be removed in Feign 10
+ * @deprecated To be removed in Feign 10
*/
@Deprecated
- public static Response create(int status, String reason, Map> headers,
+ public static Response create(int status,
+ String reason,
+ Map> headers,
byte[] data) {
return Response.builder()
- .status(status)
- .reason(reason)
- .headers(headers)
- .body(ByteArrayBody.orNull(data))
- .build();
+ .status(status)
+ .reason(reason)
+ .headers(headers)
+ .body(ByteArrayBody.orNull(data))
+ .build();
}
/**
- * @deprecated To be removed in Feign 10
+ * @deprecated To be removed in Feign 10
*/
@Deprecated
- public static Response create(int status, String reason, Map> headers,
- String text, Charset charset) {
+ public static Response create(int status,
+ String reason,
+ Map> headers,
+ String text,
+ Charset charset) {
return Response.builder()
- .status(status)
- .reason(reason)
- .headers(headers)
- .body(ByteArrayBody.orNull(text, charset))
- .build();
+ .status(status)
+ .reason(reason)
+ .headers(headers)
+ .body(ByteArrayBody.orNull(text, charset))
+ .build();
}
/**
- * @deprecated To be removed in Feign 10
+ * @deprecated To be removed in Feign 10
*/
@Deprecated
- public static Response create(int status, String reason, Map> headers,
+ public static Response create(int status,
+ String reason,
+ Map> headers,
Body body) {
return Response.builder()
- .status(status)
- .reason(reason)
- .headers(headers)
- .body(body)
- .build();
+ .status(status)
+ .reason(reason)
+ .headers(headers)
+ .body(body)
+ .build();
}
- public Builder toBuilder(){
+ public Builder toBuilder() {
return new Builder(this);
}
- public static Builder builder(){
+ public static Builder builder() {
return new Builder();
}
@@ -124,8 +133,7 @@ public static final class Builder {
Body body;
Request request;
- Builder() {
- }
+ Builder() {}
Builder(Response source) {
this.status = source.status;
@@ -135,7 +143,7 @@ public static final class Builder {
this.request = source.request;
}
- /** @see Response#status*/
+ /** @see Response#status */
public Builder status(int status) {
this.status = status;
return this;
@@ -177,11 +185,12 @@ public Builder body(String text, Charset charset) {
return this;
}
- /** @see Response#request
- *
- * NOTE: will add null check in version 10 which may require changes
- * to custom feign.Client or loggers
- */
+ /**
+ * @see Response#request
+ *
+ * NOTE: will add null check in version 10 which may require changes to custom feign.Client
+ * or loggers
+ */
public Builder request(Request request) {
this.request = request;
return this;
@@ -234,14 +243,16 @@ public Request request() {
@Override
public String toString() {
StringBuilder builder = new StringBuilder("HTTP/1.1 ").append(status);
- if (reason != null) builder.append(' ').append(reason);
+ if (reason != null)
+ builder.append(' ').append(reason);
builder.append('\n');
for (String field : headers.keySet()) {
for (String value : valuesOrEmpty(headers, field)) {
builder.append(field).append(": ").append(value).append('\n');
}
}
- if (body != null) builder.append('\n').append(body);
+ if (body != null)
+ builder.append('\n').append(body);
return builder.toString();
}
@@ -255,8 +266,11 @@ public interface Body extends Closeable {
/**
* length in bytes, if known. Null if unknown or greater than {@link Integer#MAX_VALUE}.
*
- *
Note
This is an integer as
- * most implementations cannot do bodies greater than 2GB.
+ *
+ *
+ *
+ * Note
+ * This is an integer as most implementations cannot do bodies greater than 2GB.
*/
Integer length();
@@ -280,6 +294,7 @@ private static final class InputStreamBody implements Response.Body {
private final InputStream inputStream;
private final Integer length;
+
private InputStreamBody(InputStream inputStream, Integer length) {
this.inputStream = inputStream;
this.length = length;
@@ -362,8 +377,7 @@ public Reader asReader() throws IOException {
}
@Override
- public void close() throws IOException {
- }
+ public void close() throws IOException {}
@Override
public String toString() {
@@ -372,7 +386,8 @@ public String toString() {
}
private static Map> caseInsensitiveCopyOf(Map> headers) {
- Map> result = new TreeMap>(String.CASE_INSENSITIVE_ORDER);
+ Map> result =
+ new TreeMap>(String.CASE_INSENSITIVE_ORDER);
for (Map.Entry> entry : headers.entrySet()) {
String headerName = entry.getKey();
diff --git a/core/src/main/java/feign/ResponseMapper.java b/core/src/main/java/feign/ResponseMapper.java
index d02af6adb9..18ad6918b8 100644
--- a/core/src/main/java/feign/ResponseMapper.java
+++ b/core/src/main/java/feign/ResponseMapper.java
@@ -18,9 +18,10 @@
/**
* Map function to apply to the response before decoding it.
*
- * {@code
+ *
+ * {@code
* new ResponseMapper() {
- * @Override
+ * @Override
* public Response map(Response response, Type type) {
* try {
* return response
@@ -32,7 +33,8 @@
* }
* }
* };
- * }
+ * }
+ *
*/
public interface ResponseMapper {
diff --git a/core/src/main/java/feign/RetryableException.java b/core/src/main/java/feign/RetryableException.java
index e3e912f744..79b8eafd97 100644
--- a/core/src/main/java/feign/RetryableException.java
+++ b/core/src/main/java/feign/RetryableException.java
@@ -43,7 +43,7 @@ public RetryableException(String message, Date retryAfter) {
/**
* Sometimes corresponds to the {@link feign.Util#RETRY_AFTER} header present in {@code 503}
- * status. Other times parsed from an application-specific response. Null if unknown.
+ * status. Other times parsed from an application-specific response. Null if unknown.
*/
public Date retryAfter() {
return retryAfter != null ? new Date(retryAfter) : null;
diff --git a/core/src/main/java/feign/Retryer.java b/core/src/main/java/feign/Retryer.java
index 0cacec3ffa..7944c67095 100644
--- a/core/src/main/java/feign/Retryer.java
+++ b/core/src/main/java/feign/Retryer.java
@@ -79,9 +79,9 @@ public void continueOrPropagate(RetryableException e) {
}
/**
- * Calculates the time interval to a retry attempt.
The interval increases exponentially
- * with each attempt, at a rate of nextInterval *= 1.5 (where 1.5 is the backoff factor), to the
- * maximum interval.
+ * Calculates the time interval to a retry attempt.
+ * The interval increases exponentially with each attempt, at a rate of nextInterval *= 1.5
+ * (where 1.5 is the backoff factor), to the maximum interval.
*
* @return time in nanoseconds from now until the next attempt.
*/
diff --git a/core/src/main/java/feign/SynchronousMethodHandler.java b/core/src/main/java/feign/SynchronousMethodHandler.java
index 2dd3cd4a68..1cf33ccbb7 100644
--- a/core/src/main/java/feign/SynchronousMethodHandler.java
+++ b/core/src/main/java/feign/SynchronousMethodHandler.java
@@ -16,13 +16,11 @@
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
-
import feign.InvocationHandlerFactory.MethodHandler;
import feign.Request.Options;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
-
import static feign.FeignException.errorExecuting;
import static feign.FeignException.errorReading;
import static feign.Util.checkNotNull;
@@ -47,11 +45,11 @@ final class SynchronousMethodHandler implements MethodHandler {
private final boolean closeAfterDecode;
private SynchronousMethodHandler(Target> target, Client client, Retryer retryer,
- List requestInterceptors, Logger logger,
- Logger.Level logLevel, MethodMetadata metadata,
- RequestTemplate.Factory buildTemplateFromArgs, Options options,
- Decoder decoder, ErrorDecoder errorDecoder, boolean decode404,
- boolean closeAfterDecode) {
+ List requestInterceptors, Logger logger,
+ Logger.Level logLevel, MethodMetadata metadata,
+ RequestTemplate.Factory buildTemplateFromArgs, Options options,
+ Decoder decoder, ErrorDecoder errorDecoder, boolean decode404,
+ boolean closeAfterDecode) {
this.target = checkNotNull(target, "target");
this.client = checkNotNull(client, "client for %s", target);
this.retryer = checkNotNull(retryer, "retryer for %s", target);
@@ -119,7 +117,7 @@ Object executeAndDecode(RequestTemplate template) throws Throwable {
return response;
}
if (response.body().length() == null ||
- response.body().length() > MAX_RESPONSE_BUFFER_SIZE) {
+ response.body().length() > MAX_RESPONSE_BUFFER_SIZE) {
shouldClose = false;
return response;
}
@@ -186,7 +184,7 @@ static class Factory {
private final boolean closeAfterDecode;
Factory(Client client, Retryer retryer, List requestInterceptors,
- Logger logger, Logger.Level logLevel, boolean decode404, boolean closeAfterDecode) {
+ Logger logger, Logger.Level logLevel, boolean decode404, boolean closeAfterDecode) {
this.client = checkNotNull(client, "client");
this.retryer = checkNotNull(retryer, "retryer");
this.requestInterceptors = checkNotNull(requestInterceptors, "requestInterceptors");
@@ -196,12 +194,15 @@ static class Factory {
this.closeAfterDecode = closeAfterDecode;
}
- public MethodHandler create(Target> target, MethodMetadata md,
+ public MethodHandler create(Target> target,
+ MethodMetadata md,
RequestTemplate.Factory buildTemplateFromArgs,
- Options options, Decoder decoder, ErrorDecoder errorDecoder) {
+ Options options,
+ Decoder decoder,
+ ErrorDecoder errorDecoder) {
return new SynchronousMethodHandler(target, client, retryer, requestInterceptors, logger,
- logLevel, md, buildTemplateFromArgs, options, decoder,
- errorDecoder, decode404, closeAfterDecode);
+ logLevel, md, buildTemplateFromArgs, options, decoder,
+ errorDecoder, decode404, closeAfterDecode);
}
}
}
diff --git a/core/src/main/java/feign/Target.java b/core/src/main/java/feign/Target.java
index e2e02b31da..19e6cd3ccc 100644
--- a/core/src/main/java/feign/Target.java
+++ b/core/src/main/java/feign/Target.java
@@ -17,7 +17,11 @@
import static feign.Util.emptyToNull;
/**
- *
relationship to JAXRS 2.0
Similar to {@code
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * Similar to {@code
* javax.ws.rs.client.WebTarget}, as it produces requests. However, {@link RequestTemplate} is a
* closer match to {@code WebTarget}.
*
@@ -36,15 +40,24 @@ public interface Target {
/**
* Targets a template to this target, adding the {@link #url() base url} and any target-specific
- * headers or query parameters.
For example:
+ * headers or query parameters.
+ *
+ * For example:
+ *
*
* public Request apply(RequestTemplate input) {
- * input.insert(0, url());
- * input.replaceHeader("X-Auth", currentToken);
- * return input.asRequest();
+ * input.insert(0, url());
+ * input.replaceHeader("X-Auth", currentToken);
+ * return input.asRequest();
* }
*
- *
relationship to JAXRS 2.0
This call is similar to {@code
+ *
+ *
+ *
+ *
+ * relationship to JAXRS 2.0
+ *
+ * This call is similar to {@code
* javax.ws.rs.client.WebTarget.request()}, except that we expect transient, but necessary
* decoration to be applied on invocation.
*/
@@ -95,8 +108,8 @@ public boolean equals(Object obj) {
if (obj instanceof HardCodedTarget) {
HardCodedTarget> other = (HardCodedTarget) obj;
return type.equals(other.type)
- && name.equals(other.name)
- && url.equals(other.url);
+ && name.equals(other.name)
+ && url.equals(other.url);
}
return false;
}
@@ -116,7 +129,7 @@ public String toString() {
return "HardCodedTarget(type=" + type.getSimpleName() + ", url=" + url + ")";
}
return "HardCodedTarget(type=" + type.getSimpleName() + ", name=" + name + ", url=" + url
- + ")";
+ + ")";
}
}
@@ -167,7 +180,7 @@ public boolean equals(Object obj) {
if (obj instanceof EmptyTarget) {
EmptyTarget> other = (EmptyTarget) obj;
return type.equals(other.type)
- && name.equals(other.name);
+ && name.equals(other.name);
}
return false;
}
diff --git a/core/src/main/java/feign/Types.java b/core/src/main/java/feign/Types.java
index d2f30514c0..1e642444f6 100644
--- a/core/src/main/java/feign/Types.java
+++ b/core/src/main/java/feign/Types.java
@@ -69,8 +69,8 @@ static Class> getRawType(Type type) {
} else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
- + "GenericArrayType, but <" + type + "> is of type "
- + className);
+ + "GenericArrayType, but <" + type + "> is of type "
+ + className);
}
}
@@ -91,8 +91,8 @@ static boolean equals(Type a, Type b) {
ParameterizedType pa = (ParameterizedType) a;
ParameterizedType pb = (ParameterizedType) b;
return equal(pa.getOwnerType(), pb.getOwnerType())
- && pa.getRawType().equals(pb.getRawType())
- && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
+ && pa.getRawType().equals(pb.getRawType())
+ && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
} else if (a instanceof GenericArrayType) {
if (!(b instanceof GenericArrayType)) {
@@ -109,7 +109,7 @@ static boolean equals(Type a, Type b) {
WildcardType wa = (WildcardType) a;
WildcardType wb = (WildcardType) b;
return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
- && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
+ && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
} else if (a instanceof TypeVariable) {
if (!(b instanceof TypeVariable)) {
@@ -118,7 +118,7 @@ static boolean equals(Type a, Type b) {
TypeVariable> va = (TypeVariable>) a;
TypeVariable> vb = (TypeVariable>) b;
return va.getGenericDeclaration() == vb.getGenericDeclaration()
- && va.getName().equals(vb.getName());
+ && va.getName().equals(vb.getName());
} else {
return false; // This isn't a type we support!
@@ -197,7 +197,7 @@ static Type getSupertype(Type context, Class> contextRawType, Class> superty
throw new IllegalArgumentException();
}
return resolve(context, contextRawType,
- getGenericSupertype(context, contextRawType, supertype));
+ getGenericSupertype(context, contextRawType, supertype));
}
static Type resolve(Type context, Class> contextRawType, Type toResolve) {
@@ -214,15 +214,17 @@ static Type resolve(Type context, Class> contextRawType, Type toResolve) {
Class> original = (Class>) toResolve;
Type componentType = original.getComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
- return componentType == newComponentType ? original : new GenericArrayTypeImpl(
- newComponentType);
+ return componentType == newComponentType ? original
+ : new GenericArrayTypeImpl(
+ newComponentType);
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
- return componentType == newComponentType ? original : new GenericArrayTypeImpl(
- newComponentType);
+ return componentType == newComponentType ? original
+ : new GenericArrayTypeImpl(
+ newComponentType);
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
@@ -243,8 +245,8 @@ static Type resolve(Type context, Class> contextRawType, Type toResolve) {
}
return changed
- ? new ParameterizedTypeImpl(newOwnerType, original.getRawType(), args)
- : original;
+ ? new ParameterizedTypeImpl(newOwnerType, original.getRawType(), args)
+ : original;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
@@ -254,12 +256,12 @@ static Type resolve(Type context, Class> contextRawType, Type toResolve) {
if (originalLowerBound.length == 1) {
Type lowerBound = resolve(context, contextRawType, originalLowerBound[0]);
if (lowerBound != originalLowerBound[0]) {
- return new WildcardTypeImpl(new Type[]{Object.class}, new Type[]{lowerBound});
+ return new WildcardTypeImpl(new Type[] {Object.class}, new Type[] {lowerBound});
}
} else if (originalUpperBound.length == 1) {
Type upperBound = resolve(context, contextRawType, originalUpperBound[0]);
if (upperBound != originalUpperBound[0]) {
- return new WildcardTypeImpl(new Type[]{upperBound}, EMPTY_TYPE_ARRAY);
+ return new WildcardTypeImpl(new Type[] {upperBound}, EMPTY_TYPE_ARRAY);
}
}
return original;
@@ -271,7 +273,9 @@ static Type resolve(Type context, Class> contextRawType, Type toResolve) {
}
private static Type resolveTypeVariable(
- Type context, Class> contextRawType, TypeVariable> unknown) {
+ Type context,
+ Class> contextRawType,
+ TypeVariable> unknown) {
Class> declaredByRaw = declaringClassOf(unknown);
// We can't reduce this further.
@@ -380,7 +384,7 @@ public Type getGenericComponentType() {
@Override
public boolean equals(Object o) {
return o instanceof GenericArrayType
- && Types.equals(this, (GenericArrayType) o);
+ && Types.equals(this, (GenericArrayType) o);
}
@Override
@@ -433,11 +437,11 @@ static final class WildcardTypeImpl implements WildcardType {
}
public Type[] getUpperBounds() {
- return new Type[]{upperBound};
+ return new Type[] {upperBound};
}
public Type[] getLowerBounds() {
- return lowerBound != null ? new Type[]{lowerBound} : EMPTY_TYPE_ARRAY;
+ return lowerBound != null ? new Type[] {lowerBound} : EMPTY_TYPE_ARRAY;
}
@Override
diff --git a/core/src/main/java/feign/Util.java b/core/src/main/java/feign/Util.java
index 74819d2fc9..5e355926cc 100644
--- a/core/src/main/java/feign/Util.java
+++ b/core/src/main/java/feign/Util.java
@@ -38,7 +38,6 @@
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
-
import static java.lang.String.format;
/**
@@ -84,7 +83,7 @@ public class Util {
*/
public static final Type MAP_STRING_WILDCARD =
new Types.ParameterizedTypeImpl(null, Map.class, String.class,
- new Types.WildcardTypeImpl(new Type[]{Object.class}, new Type[0]));
+ new Types.WildcardTypeImpl(new Type[] {Object.class}, new Type[0]));
private Util() { // no instances
}
@@ -134,10 +133,12 @@ public static boolean isDefault(Method method) {
// Default methods are public non-abstract, non-synthetic, and non-static instance methods
// declared in an interface.
// method.isDefault() is not sufficient for our usage as it does not check
- // for synthetic methods. As a result, it picks up overridden methods as well as actual default methods.
+ // for synthetic methods. As a result, it picks up overridden methods as well as actual default
+ // methods.
final int SYNTHETIC = 0x00001000;
- return ((method.getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC | SYNTHETIC)) ==
- Modifier.PUBLIC) && method.getDeclaringClass().isInterface();
+ return ((method.getModifiers()
+ & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC | SYNTHETIC)) == Modifier.PUBLIC)
+ && method.getDeclaringClass().isInterface();
}
/**
@@ -183,22 +184,24 @@ public static void ensureClosed(Closeable closeable) {
/**
* Resolves the last type parameter of the parameterized {@code supertype}, based on the {@code
- * genericContext}, into its upper bounds. Implementation copied from {@code
+ * genericContext}, into its upper bounds.
+ *
+ * Implementation copied from {@code
* retrofit.RestMethodInfo}.
*
* @param genericContext Ex. {@link java.lang.reflect.Field#getGenericType()}
- * @param supertype Ex. {@code Decoder.class}
+ * @param supertype Ex. {@code Decoder.class}
* @return in the example above, the type parameter of {@code Decoder}.
* @throws IllegalStateException if {@code supertype} cannot be resolved into a parameterized type
- * using {@code context}.
+ * using {@code context}.
*/
public static Type resolveLastTypeParameter(Type genericContext, Class> supertype)
throws IllegalStateException {
Type resolvedSuperType =
Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype);
checkState(resolvedSuperType instanceof ParameterizedType,
- "could not resolve %s into a parameterized type %s",
- genericContext, supertype);
+ "could not resolve %s into a parameterized type %s",
+ genericContext, supertype);
Type[] types = ParameterizedType.class.cast(resolvedSuperType).getActualTypeArguments();
for (int i = 0; i < types.length; i++) {
Type type = types[i];
@@ -214,18 +217,19 @@ public static Type resolveLastTypeParameter(Type genericContext, Class> supert
* in the following list.
*
*
- * - {@code [Bb]oolean}
- * - {@code byte[]}
- * - {@code Collection}
- * - {@code Iterator}
- * - {@code List}
- * - {@code Map}
- * - {@code Set}
+ * - {@code [Bb]oolean}
+ * - {@code byte[]}
+ * - {@code Collection}
+ * - {@code Iterator}
+ * - {@code List}
+ * - {@code Map}
+ * - {@code Set}
*
*
- * When {@link Feign.Builder#decode404() decoding HTTP 404 status}, you'll need to teach
- * decoders a default empty value for a type. This method cheaply supports typical types by only
- * looking at the raw type (vs type hierarchy). Decorate for sophistication.
+ *
+ * When {@link Feign.Builder#decode404() decoding HTTP 404 status}, you'll need to teach decoders
+ * a default empty value for a type. This method cheaply supports typical types by only looking at
+ * the raw type (vs type hierarchy). Decorate for sophistication.
*/
public static Object emptyValueOf(Type type) {
return EMPTIES.get(Types.getRawType(type));
diff --git a/core/src/main/java/feign/auth/Base64.java b/core/src/main/java/feign/auth/Base64.java
index e032bc8d7b..270ce31f8a 100644
--- a/core/src/main/java/feign/auth/Base64.java
+++ b/core/src/main/java/feign/auth/Base64.java
@@ -16,22 +16,22 @@
import java.io.UnsupportedEncodingException;
/**
- * copied from okhttp
+ * copied from okhttp
*
* @author Alexander Y. Kleymenov
*/
final class Base64 {
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
- private static final byte[] MAP = new byte[]{
+ private static final byte[] MAP = new byte[] {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '+', '/'
};
- private Base64() {
- }
+ private Base64() {}
public static byte[] decode(byte[] in) {
return decode(in, in.length);
@@ -51,7 +51,7 @@ public static byte[] decode(byte[] in, int len) {
byte chr;
// compute the number of the padding characters
// and adjust the length of the input
- for (; ; len--) {
+ for (;; len--) {
chr = in[len - 1];
// skip the neutral characters
if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) {
@@ -79,18 +79,18 @@ public static byte[] decode(byte[] in, int len) {
}
if ((chr >= 'A') && (chr <= 'Z')) {
// char ASCII value
- // A 65 0
- // Z 90 25 (ASCII - 65)
+ // A 65 0
+ // Z 90 25 (ASCII - 65)
bits = chr - 65;
} else if ((chr >= 'a') && (chr <= 'z')) {
// char ASCII value
- // a 97 26
- // z 122 51 (ASCII - 71)
+ // a 97 26
+ // z 122 51 (ASCII - 71)
bits = chr - 71;
} else if ((chr >= '0') && (chr <= '9')) {
// char ASCII value
- // 0 48 52
- // 9 57 61 (ASCII + 4)
+ // 0 48 52
+ // 9 57 61 (ASCII + 4)
bits = chr + 4;
} else if (chr == '+') {
bits = 62;
diff --git a/core/src/main/java/feign/auth/BasicAuthRequestInterceptor.java b/core/src/main/java/feign/auth/BasicAuthRequestInterceptor.java
index 202d048365..d8a32a1c4c 100644
--- a/core/src/main/java/feign/auth/BasicAuthRequestInterceptor.java
+++ b/core/src/main/java/feign/auth/BasicAuthRequestInterceptor.java
@@ -14,10 +14,8 @@
package feign.auth;
import java.nio.charset.Charset;
-
import feign.RequestInterceptor;
import feign.RequestTemplate;
-
import static feign.Util.ISO_8859_1;
import static feign.Util.checkNotNull;
@@ -45,7 +43,7 @@ public BasicAuthRequestInterceptor(String username, String password) {
*
* @param username the username to use for authentication
* @param password the password to use for authentication
- * @param charset the charset to use when encoding the credentials
+ * @param charset the charset to use when encoding the credentials
*/
public BasicAuthRequestInterceptor(String username, String password, Charset charset) {
checkNotNull(username, "username");
@@ -54,8 +52,9 @@ public BasicAuthRequestInterceptor(String username, String password, Charset cha
}
/*
- * This uses a Sun internal method; if we ever encounter a case where this method is not available, the appropriate
- * response would be to pull the necessary portions of Guava's BaseEncoding class into Util.
+ * This uses a Sun internal method; if we ever encounter a case where this method is not
+ * available, the appropriate response would be to pull the necessary portions of Guava's
+ * BaseEncoding class into Util.
*/
private static String base64Encode(byte[] bytes) {
return Base64.encode(bytes);
diff --git a/core/src/main/java/feign/codec/DecodeException.java b/core/src/main/java/feign/codec/DecodeException.java
index 2baeb84178..687a6ddfea 100644
--- a/core/src/main/java/feign/codec/DecodeException.java
+++ b/core/src/main/java/feign/codec/DecodeException.java
@@ -14,12 +14,11 @@
package feign.codec;
import feign.FeignException;
-
import static feign.Util.checkNotNull;
/**
* Similar to {@code javax.websocket.DecodeException}, raised when a problem occurs decoding a
- * message. Note that {@code DecodeException} is not an {@code IOException}, nor does it have one
+ * message. Note that {@code DecodeException} is not an {@code IOException}, nor does it have one
* set as its cause.
*/
public class DecodeException extends FeignException {
@@ -35,7 +34,7 @@ public DecodeException(String message) {
/**
* @param message possibly null reason for the failure.
- * @param cause the cause of the error.
+ * @param cause the cause of the error.
*/
public DecodeException(String message, Throwable cause) {
super(message, checkNotNull(cause, "cause"));
diff --git a/core/src/main/java/feign/codec/Decoder.java b/core/src/main/java/feign/codec/Decoder.java
index b7d24a00fb..16171872b1 100644
--- a/core/src/main/java/feign/codec/Decoder.java
+++ b/core/src/main/java/feign/codec/Decoder.java
@@ -15,16 +15,21 @@
import java.io.IOException;
import java.lang.reflect.Type;
-
import feign.Feign;
import feign.FeignException;
import feign.Response;
import feign.Util;
/**
- * Decodes an HTTP response into a single object of the given {@code type}. Invoked when {@link
- * Response#status()} is in the 2xx range and the return type is neither {@code void} nor {@code
- * Response}. Example Implementation:
+ * Decodes an HTTP response into a single object of the given {@code type}. Invoked when
+ * {@link Response#status()} is in the 2xx range and the return type is neither {@code void} nor
+ * {@code
+ * Response}.
+ *
+ *
+ * Example Implementation:
+ *
+ *
*
* public class GsonDecoder implements Decoder {
* private final Gson gson = new Gson();
@@ -43,29 +48,32 @@
* }
* }
*
- *
Implementation Note
The {@code type} parameter will correspond to the {@link
- * java.lang.reflect.Method#getGenericReturnType() generic return type} of an {@link
- * feign.Target#type() interface} processed by {@link feign.Feign#newInstance(feign.Target)}. When
- * writing your implementation of Decoder, ensure you also test parameterized types such as {@code
- * List}.
- *
Note on exception propagation
Exceptions thrown by {@link Decoder}s get wrapped in
- * a {@link DecodeException} unless they are a subclass of {@link FeignException} already, and unless
+ *
+ *
+ * Implementation Note
The {@code type} parameter will correspond to the
+ * {@link java.lang.reflect.Method#getGenericReturnType() generic return type} of an
+ * {@link feign.Target#type() interface} processed by {@link feign.Feign#newInstance(feign.Target)}.
+ * When writing your implementation of Decoder, ensure you also test parameterized types such as
+ * {@code
+ * List}.
+ * Note on exception propagation
Exceptions thrown by {@link Decoder}s get wrapped in a
+ * {@link DecodeException} unless they are a subclass of {@link FeignException} already, and unless
* the client was configured with {@link Feign.Builder#decode404()}.
*/
public interface Decoder {
/**
- * Decodes an http response into an object corresponding to its {@link
- * java.lang.reflect.Method#getGenericReturnType() generic return type}. If you need to wrap
- * exceptions, please do so via {@link DecodeException}.
+ * Decodes an http response into an object corresponding to its
+ * {@link java.lang.reflect.Method#getGenericReturnType() generic return type}. If you need to
+ * wrap exceptions, please do so via {@link DecodeException}.
*
* @param response the response to decode
- * @param type {@link java.lang.reflect.Method#getGenericReturnType() generic return type} of
- * the method corresponding to this {@code response}.
+ * @param type {@link java.lang.reflect.Method#getGenericReturnType() generic return type} of the
+ * method corresponding to this {@code response}.
* @return instance of {@code type}
- * @throws IOException will be propagated safely to the caller.
+ * @throws IOException will be propagated safely to the caller.
* @throws DecodeException when decoding failed due to a checked exception besides IOException.
- * @throws FeignException when decoding succeeds, but conveys the operation failed.
+ * @throws FeignException when decoding succeeds, but conveys the operation failed.
*/
Object decode(Response response, Type type) throws IOException, DecodeException, FeignException;
@@ -74,8 +82,10 @@ public class Default extends StringDecoder {
@Override
public Object decode(Response response, Type type) throws IOException {
- if (response.status() == 404) return Util.emptyValueOf(type);
- if (response.body() == null) return null;
+ if (response.status() == 404)
+ return Util.emptyValueOf(type);
+ if (response.body() == null)
+ return null;
if (byte[].class.equals(type)) {
return Util.toByteArray(response.body().asInputStream());
}
diff --git a/core/src/main/java/feign/codec/EncodeException.java b/core/src/main/java/feign/codec/EncodeException.java
index 9cb40cf074..517728366f 100644
--- a/core/src/main/java/feign/codec/EncodeException.java
+++ b/core/src/main/java/feign/codec/EncodeException.java
@@ -14,12 +14,11 @@
package feign.codec;
import feign.FeignException;
-
import static feign.Util.checkNotNull;
/**
* Similar to {@code javax.websocket.EncodeException}, raised when a problem occurs encoding a
- * message. Note that {@code EncodeException} is not an {@code IOException}, nor does it have one
+ * message. Note that {@code EncodeException} is not an {@code IOException}, nor does it have one
* set as its cause.
*/
public class EncodeException extends FeignException {
@@ -35,7 +34,7 @@ public EncodeException(String message) {
/**
* @param message possibly null reason for the failure.
- * @param cause the cause of the error.
+ * @param cause the cause of the error.
*/
public EncodeException(String message, Throwable cause) {
super(message, checkNotNull(cause, "cause"));
diff --git a/core/src/main/java/feign/codec/Encoder.java b/core/src/main/java/feign/codec/Encoder.java
index 7d5a43f3b6..b5f556ef4a 100644
--- a/core/src/main/java/feign/codec/Encoder.java
+++ b/core/src/main/java/feign/codec/Encoder.java
@@ -14,22 +14,24 @@
package feign.codec;
import java.lang.reflect.Type;
-
import feign.RequestTemplate;
import feign.Util;
-
import static java.lang.String.format;
/**
* Encodes an object into an HTTP request body. Like {@code javax.websocket.Encoder}. {@code
* Encoder} is used when a method parameter has no {@code @Param} annotation. For example:
*
+ *
*
* @POST
* @Path("/")
* void create(User user);
*
- * Example implementation:
+ *
+ * Example implementation:
+ *
+ *
*
* public class GsonEncoder implements Encoder {
* private final Gson gson;
@@ -45,16 +47,20 @@
* }
*
*
- * Form encoding
If any parameters are found in {@link
- * feign.MethodMetadata#formParams()}, they will be collected and passed to the Encoder as a map.
+ *
+ *
Form encoding
+ *
+ * If any parameters are found in {@link feign.MethodMetadata#formParams()}, they will be collected
+ * and passed to the Encoder as a map.
*
- *
Ex. The following is a form. Notice the parameters aren't consumed in the request line. A map
+ *
+ * Ex. The following is a form. Notice the parameters aren't consumed in the request line. A map
* including "username" and "password" keys will passed to the encoder, and the body type will be
* {@link #MAP_STRING_WILDCARD}.
+ *
*
* @RequestLine("POST /")
- * Session login(@Param("username") String username, @Param("password") String
- * password);
+ * Session login(@Param("username") String username, @Param("password") String password);
*
*/
public interface Encoder {
@@ -64,9 +70,9 @@ public interface Encoder {
/**
* Converts objects to an appropriate representation in the template.
*
- * @param object what to encode as the request body.
+ * @param object what to encode as the request body.
* @param bodyType the type the object should be encoded as. {@link #MAP_STRING_WILDCARD}
- * indicates form encoding.
+ * indicates form encoding.
* @param template the request template to populate.
* @throws EncodeException when encoding failed due to a checked exception.
*/
diff --git a/core/src/main/java/feign/codec/ErrorDecoder.java b/core/src/main/java/feign/codec/ErrorDecoder.java
index 4a52226c5b..6482203f8b 100644
--- a/core/src/main/java/feign/codec/ErrorDecoder.java
+++ b/core/src/main/java/feign/codec/ErrorDecoder.java
@@ -19,11 +19,9 @@
import java.util.Collection;
import java.util.Date;
import java.util.Map;
-
import feign.FeignException;
import feign.Response;
import feign.RetryableException;
-
import static feign.FeignException.errorStatus;
import static feign.Util.RETRY_AFTER;
import static feign.Util.checkNotNull;
@@ -35,48 +33,54 @@
* Allows you to massage an exception into a application-specific one. Converting out to a throttle
* exception are examples of this in use.
*
- * Ex:
+ *
+ * Ex:
+ *
*
* class IllegalArgumentExceptionOn404Decoder implements ErrorDecoder {
*
* @Override
* public Exception decode(String methodKey, Response response) {
- * if (response.status() == 400)
- * throw new IllegalArgumentException("bad zone name");
- * return new ErrorDecoder.Default().decode(methodKey, response);
+ * if (response.status() == 400)
+ * throw new IllegalArgumentException("bad zone name");
+ * return new ErrorDecoder.Default().decode(methodKey, response);
* }
*
* }
*
*
- * Error handling
+ *
+ * Error handling
*
- * Responses where {@link Response#status()} is not in the 2xx
- * range are classified as errors, addressed by the {@link ErrorDecoder}. That said, certain RPC
- * apis return errors defined in the {@link Response#body()} even on a 200 status. For example, in
- * the DynECT api, a job still running condition is returned with a 200 status, encoded in json.
- * When scenarios like this occur, you should raise an application-specific exception (which may be
- * {@link feign.RetryableException retryable}).
+ *
+ * Responses where {@link Response#status()} is not in the 2xx range are classified as errors,
+ * addressed by the {@link ErrorDecoder}. That said, certain RPC apis return errors defined in the
+ * {@link Response#body()} even on a 200 status. For example, in the DynECT api, a job still running
+ * condition is returned with a 200 status, encoded in json. When scenarios like this occur, you
+ * should raise an application-specific exception (which may be {@link feign.RetryableException
+ * retryable}).
*
- * Not Found Semantics
- * It is commonly the case that 404 (Not Found) status has semantic value in HTTP apis. While
- * the default behavior is to raise exeception, users can alternatively enable 404 processing via
+ *
+ * Not Found Semantics
+ *
+ * It is commonly the case that 404 (Not Found) status has semantic value in HTTP apis. While the
+ * default behavior is to raise exeception, users can alternatively enable 404 processing via
* {@link feign.Feign.Builder#decode404()}.
*/
public interface ErrorDecoder {
/**
- * Implement this method in order to decode an HTTP {@link Response} when {@link
- * Response#status()} is not in the 2xx range. Please raise application-specific exceptions where
- * possible. If your exception is retryable, wrap or subclass {@link RetryableException}
+ * Implement this method in order to decode an HTTP {@link Response} when
+ * {@link Response#status()} is not in the 2xx range. Please raise application-specific exceptions
+ * where possible. If your exception is retryable, wrap or subclass {@link RetryableException}
*
- * @param methodKey {@link feign.Feign#configKey} of the java method that invoked the request.
- * ex. {@code IAM#getUser()}
- * @param response HTTP response where {@link Response#status() status} is greater than or equal
- * to {@code 300}.
+ * @param methodKey {@link feign.Feign#configKey} of the java method that invoked the request. ex.
+ * {@code IAM#getUser()}
+ * @param response HTTP response where {@link Response#status() status} is greater than or equal
+ * to {@code 300}.
* @return Exception IOException, if there was a network error reading the response or an
- * application-specific exception decoded by the implementation. If the throwable is retryable, it
- * should be wrapped, or a subtype of {@link RetryableException}
+ * application-specific exception decoded by the implementation. If the throwable is
+ * retryable, it should be wrapped, or a subtype of {@link RetryableException}
*/
public Exception decode(String methodKey, Response response);
@@ -103,13 +107,12 @@ private T firstOrNull(Map> map, String key) {
}
/**
- * Decodes a {@link feign.Util#RETRY_AFTER} header into an absolute date, if possible.
See Retry-After format
+ * Decodes a {@link feign.Util#RETRY_AFTER} header into an absolute date, if possible.
+ * See Retry-After format
*/
static class RetryAfterDecoder {
- static final DateFormat
- RFC822_FORMAT =
+ static final DateFormat RFC822_FORMAT =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", US);
private final DateFormat rfc822Format;
@@ -128,8 +131,8 @@ protected long currentTimeMillis() {
/**
* returns a date that corresponds to the first time a request can be retried.
*
- * @param retryAfter String in Retry-After format
+ * @param retryAfter String in
+ * Retry-After format
*/
public Date apply(String retryAfter) {
if (retryAfter == null) {
diff --git a/core/src/main/java/feign/codec/StringDecoder.java b/core/src/main/java/feign/codec/StringDecoder.java
index 194f8f3d74..16f2a6f178 100644
--- a/core/src/main/java/feign/codec/StringDecoder.java
+++ b/core/src/main/java/feign/codec/StringDecoder.java
@@ -15,10 +15,8 @@
import java.io.IOException;
import java.lang.reflect.Type;
-
import feign.Response;
import feign.Util;
-
import static java.lang.String.format;
public class StringDecoder implements Decoder {
diff --git a/core/src/test/java/feign/BaseApiTest.java b/core/src/test/java/feign/BaseApiTest.java
index b1ec0e54b3..60b807639e 100644
--- a/core/src/test/java/feign/BaseApiTest.java
+++ b/core/src/test/java/feign/BaseApiTest.java
@@ -14,19 +14,14 @@
package feign;
import com.google.gson.reflect.TypeToken;
-
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
-
import org.junit.Rule;
import org.junit.Test;
-
import java.lang.reflect.Type;
import java.util.List;
-
import feign.codec.Decoder;
import feign.codec.Encoder;
-
import static feign.assertj.MockWebServerAssertions.assertThat;
public class BaseApiTest {
@@ -74,8 +69,7 @@ public void resolvesParameterizedResult() throws InterruptedException {
@Override
public Object decode(Response response, Type type) {
assertThat(type)
- .isEqualTo(new TypeToken>() {
- }.getType());
+ .isEqualTo(new TypeToken>() {}.getType());
return null;
}
})
@@ -95,16 +89,14 @@ public void resolvesBodyParameter() throws InterruptedException {
@Override
public void encode(Object object, Type bodyType, RequestTemplate template) {
assertThat(bodyType)
- .isEqualTo(new TypeToken>() {
- }.getType());
+ .isEqualTo(new TypeToken>() {}.getType());
}
})
.decoder(new Decoder() {
@Override
public Object decode(Response response, Type type) {
assertThat(type)
- .isEqualTo(new TypeToken>() {
- }.getType());
+ .isEqualTo(new TypeToken>() {}.getType());
return null;
}
})
diff --git a/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java b/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java
index 23342a9081..79882fb2b1 100644
--- a/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java
+++ b/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java
@@ -15,7 +15,6 @@
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
-
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
@@ -23,11 +22,9 @@
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-
import static feign.assertj.MockWebServerAssertions.assertThat;
public class ContractWithRuntimeInjectionTest {
@@ -100,7 +97,8 @@ public List parseAndValidatateMetadata(Class> targetType) {
List result = super.parseAndValidatateMetadata(targetType);
for (MethodMetadata md : result) {
Map indexToExpander = new LinkedHashMap();
- for (Map.Entry> entry : md.indexToExpanderClass().entrySet()) {
+ for (Map.Entry> entry : md.indexToExpanderClass()
+ .entrySet()) {
indexToExpander.put(entry.getKey(), beanFactory.getBean(entry.getValue()));
}
md.indexToExpander(indexToExpander);
diff --git a/core/src/test/java/feign/DefaultContractTest.java b/core/src/test/java/feign/DefaultContractTest.java
index fc1960ef31..cfa9fd3558 100644
--- a/core/src/test/java/feign/DefaultContractTest.java
+++ b/core/src/test/java/feign/DefaultContractTest.java
@@ -14,26 +14,23 @@
package feign;
import com.google.gson.reflect.TypeToken;
-
import org.assertj.core.api.Fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-
import java.net.URI;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
-
import static feign.assertj.FeignAssertions.assertThat;
import static java.util.Arrays.asList;
import static org.assertj.core.data.MapEntry.entry;
/**
- * Tests interfaces defined per {@link Contract.Default} are interpreted into expected {@link feign
- * .RequestTemplate template} instances.
+ * Tests interfaces defined per {@link Contract.Default} are interpreted into expected
+ * {@link feign .RequestTemplate template} instances.
*/
public class DefaultContractTest {
@@ -64,8 +61,7 @@ public void bodyParamIsGeneric() throws Exception {
assertThat(md.bodyIndex())
.isEqualTo(0);
assertThat(md.bodyType())
- .isEqualTo(new TypeToken>() {
- }.getType());
+ .isEqualTo(new TypeToken>() {}.getType());
}
@Test
@@ -75,8 +71,7 @@ public void bodyParamWithPathParam() throws Exception {
assertThat(md.bodyIndex())
.isEqualTo(1);
assertThat(md.indexToName()).containsOnly(
- entry(0, asList("id"))
- );
+ entry(0, asList("id")));
}
@Test
@@ -102,44 +97,38 @@ public void queryParamsInPathExtract() throws Exception {
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "one").template())
.hasUrl("/")
.hasQueries(
- entry("Action", asList("GetUser"))
- );
+ entry("Action", asList("GetUser")));
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "two").template())
.hasUrl("/")
.hasQueries(
entry("Action", asList("GetUser")),
- entry("Version", asList("2010-05-08"))
- );
+ entry("Version", asList("2010-05-08")));
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "three").template())
.hasUrl("/")
.hasQueries(
entry("Action", asList("GetUser")),
entry("Version", asList("2010-05-08")),
- entry("limit", asList("1"))
- );
+ entry("limit", asList("1")));
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "twoAndOneEmpty").template())
.hasUrl("/")
.hasQueries(
- entry("flag", asList(new String[]{null})),
+ entry("flag", asList(new String[] {null})),
entry("Action", asList("GetUser")),
- entry("Version", asList("2010-05-08"))
- );
+ entry("Version", asList("2010-05-08")));
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "oneEmpty").template())
.hasUrl("/")
.hasQueries(
- entry("flag", asList(new String[]{null}))
- );
+ entry("flag", asList(new String[] {null})));
assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "twoEmpty").template())
.hasUrl("/")
.hasQueries(
- entry("flag", asList(new String[]{null})),
- entry("NoErrors", asList(new String[]{null}))
- );
+ entry("flag", asList(new String[] {null})),
+ entry("NoErrors", asList(new String[] {null})));
}
@Test
@@ -157,8 +146,7 @@ public void headersOnMethodAddsContentTypeHeader() throws Exception {
assertThat(md.template())
.hasHeaders(
entry("Content-Type", asList("application/xml")),
- entry("Content-Length", asList(String.valueOf(md.template().body().length)))
- );
+ entry("Content-Length", asList(String.valueOf(md.template().body().length))));
}
@Test
@@ -168,21 +156,19 @@ public void headersOnTypeAddsContentTypeHeader() throws Exception {
assertThat(md.template())
.hasHeaders(
entry("Content-Type", asList("application/xml")),
- entry("Content-Length", asList(String.valueOf(md.template().body().length)))
- );
+ entry("Content-Length", asList(String.valueOf(md.template().body().length))));
}
@Test
public void withPathAndURIParam() throws Exception {
MethodMetadata md = parseAndValidateMetadata(WithURIParam.class,
- "uriParam", String.class, URI.class, String.class);
+ "uriParam", String.class, URI.class, String.class);
assertThat(md.indexToName())
.containsExactly(
entry(0, asList("1")),
// Skips 1 as it is a url index!
- entry(2, asList("2"))
- );
+ entry(2, asList("2")));
assertThat(md.urlIndex()).isEqualTo(1);
}
@@ -190,8 +176,8 @@ public void withPathAndURIParam() throws Exception {
@Test
public void pathAndQueryParams() throws Exception {
MethodMetadata md = parseAndValidateMetadata(WithPathAndQueryParams.class,
- "recordsByNameAndType", int.class, String.class,
- String.class);
+ "recordsByNameAndType", int.class, String.class,
+ String.class);
assertThat(md.template())
.hasQueries(entry("name", asList("{name}")), entry("type", asList("{type}")));
@@ -199,14 +185,13 @@ public void pathAndQueryParams() throws Exception {
assertThat(md.indexToName()).containsExactly(
entry(0, asList("domainId")),
entry(1, asList("name")),
- entry(2, asList("type"))
- );
+ entry(2, asList("type")));
}
@Test
public void bodyWithTemplate() throws Exception {
MethodMetadata md = parseAndValidateMetadata(FormParams.class,
- "login", String.class, String.class, String.class);
+ "login", String.class, String.class, String.class);
assertThat(md.template())
.hasBodyTemplate(
@@ -216,7 +201,7 @@ public void bodyWithTemplate() throws Exception {
@Test
public void formParamsParseIntoIndexToName() throws Exception {
MethodMetadata md = parseAndValidateMetadata(FormParams.class,
- "login", String.class, String.class, String.class);
+ "login", String.class, String.class, String.class);
assertThat(md.formParams())
.containsExactly("customer_name", "user_name", "password");
@@ -224,8 +209,7 @@ public void formParamsParseIntoIndexToName() throws Exception {
assertThat(md.indexToName()).containsExactly(
entry(0, asList("customer_name")),
entry(1, asList("user_name")),
- entry(2, asList("password"))
- );
+ entry(2, asList("password")));
}
/**
@@ -234,7 +218,7 @@ public void formParamsParseIntoIndexToName() throws Exception {
@Test
public void formParamsDoesNotSetBodyType() throws Exception {
MethodMetadata md = parseAndValidateMetadata(FormParams.class,
- "login", String.class, String.class, String.class);
+ "login", String.class, String.class, String.class);
assertThat(md.bodyType()).isNull();
}
@@ -253,7 +237,8 @@ public void headerParamsParseIntoIndexToName() throws Exception {
@Test
public void headerParamsParseIntoIndexToNameNotAtStart() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(HeaderParamsNotAtStart.class, "logout", String.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(HeaderParamsNotAtStart.class, "logout", String.class);
assertThat(md.template())
.hasHeaders(entry("Authorization", asList("Bearer {authToken}", "Foo")));
@@ -273,35 +258,40 @@ public void customExpander() throws Exception {
@Test
public void queryMap() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMap", Map.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(QueryMapTestInterface.class, "queryMap", Map.class);
assertThat(md.queryMapIndex()).isEqualTo(0);
}
@Test
public void queryMapEncodedDefault() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMap", Map.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(QueryMapTestInterface.class, "queryMap", Map.class);
assertThat(md.queryMapEncoded()).isFalse();
}
@Test
public void queryMapEncodedTrue() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMapEncoded", Map.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(QueryMapTestInterface.class, "queryMapEncoded", Map.class);
assertThat(md.queryMapEncoded()).isTrue();
}
@Test
public void queryMapEncodedFalse() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMapNotEncoded", Map.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(QueryMapTestInterface.class, "queryMapNotEncoded", Map.class);
assertThat(md.queryMapEncoded()).isFalse();
}
@Test
public void queryMapMapSubclass() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMapMapSubclass", SortedMap.class);
+ MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMapMapSubclass",
+ SortedMap.class);
assertThat(md.queryMapIndex()).isEqualTo(0);
}
@@ -309,7 +299,8 @@ public void queryMapMapSubclass() throws Exception {
@Test
public void onlyOneQueryMapAnnotationPermitted() throws Exception {
try {
- parseAndValidateMetadata(QueryMapTestInterface.class, "multipleQueryMap", Map.class, Map.class);
+ parseAndValidateMetadata(QueryMapTestInterface.class, "multipleQueryMap", Map.class,
+ Map.class);
Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class);
} catch (IllegalStateException ex) {
assertThat(ex).hasMessage("QueryMap annotation was present on multiple parameters.");
@@ -328,14 +319,16 @@ public void queryMapKeysMustBeStrings() throws Exception {
@Test
public void queryMapPojoObject() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "pojoObject", Object.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(QueryMapTestInterface.class, "pojoObject", Object.class);
assertThat(md.queryMapIndex()).isEqualTo(0);
}
@Test
public void queryMapPojoObjectEncoded() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "pojoObjectEncoded", Object.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(QueryMapTestInterface.class, "pojoObjectEncoded", Object.class);
assertThat(md.queryMapIndex()).isEqualTo(0);
assertThat(md.queryMapEncoded()).isTrue();
@@ -343,7 +336,8 @@ public void queryMapPojoObjectEncoded() throws Exception {
@Test
public void queryMapPojoObjectNotEncoded() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "pojoObjectNotEncoded", Object.class);
+ MethodMetadata md =
+ parseAndValidateMetadata(QueryMapTestInterface.class, "pojoObjectNotEncoded", Object.class);
assertThat(md.queryMapIndex()).isEqualTo(0);
assertThat(md.queryMapEncoded()).isFalse();
@@ -352,7 +346,7 @@ public void queryMapPojoObjectNotEncoded() throws Exception {
@Test
public void slashAreEncodedWhenNeeded() throws Exception {
MethodMetadata md = parseAndValidateMetadata(SlashNeedToBeEncoded.class,
- "getQueues", String.class);
+ "getQueues", String.class);
assertThat(md.template().decodeSlash()).isFalse();
@@ -373,7 +367,8 @@ public void onlyOneHeaderMapAnnotationPermitted() throws Exception {
@Test
public void headerMapSubclass() throws Exception {
- MethodMetadata md = parseAndValidateMetadata(HeaderMapInterface.class, "headerMapSubClass", SubClassHeaders.class);
+ MethodMetadata md = parseAndValidateMetadata(HeaderMapInterface.class, "headerMapSubClass",
+ SubClassHeaders.class);
assertThat(md.headerMapIndex()).isEqualTo(0);
}
@@ -459,7 +454,8 @@ interface WithURIParam {
interface WithPathAndQueryParams {
@RequestLine("GET /domains/{domainId}/records?name={name}&type={type}")
- Response recordsByNameAndType(@Param("domainId") int id, @Param("name") String nameFilter,
+ Response recordsByNameAndType(@Param("domainId") int id,
+ @Param("name") String nameFilter,
@Param("type") String typeFilter);
}
@@ -468,14 +464,16 @@ interface FormParams {
@RequestLine("POST /")
@Body("%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
void login(
- @Param("customer_name") String customer,
- @Param("user_name") String user, @Param("password") String password);
+ @Param("customer_name") String customer,
+ @Param("user_name") String user,
+ @Param("password") String password);
}
interface HeaderMapInterface {
@RequestLine("POST /")
- void multipleHeaderMap(@HeaderMap Map headers, @HeaderMap Map queries);
+ void multipleHeaderMap(@HeaderMap Map headers,
+ @HeaderMap Map queries);
@RequestLine("POST /")
void headerMapSubClass(@HeaderMap SubClassHeaders httpHeaders);
@@ -534,7 +532,8 @@ interface QueryMapTestInterface {
// invalid
@RequestLine("POST /")
- void multipleQueryMap(@QueryMap Map mapOne, @QueryMap Map mapTwo);
+ void multipleQueryMap(@QueryMap Map mapOne,
+ @QueryMap Map mapTwo);
// invalid
@RequestLine("POST /")
@@ -660,27 +659,22 @@ public void parameterizedBaseApi() throws Exception {
.containsOnlyKeys("ParameterizedApi#get(String)", "ParameterizedApi#getAll(Keys)");
assertThat(byConfigKey.get("ParameterizedApi#get(String)").returnType())
- .isEqualTo(new TypeToken>() {
- }.getType());
+ .isEqualTo(new TypeToken>() {}.getType());
assertThat(byConfigKey.get("ParameterizedApi#get(String)").template()).hasHeaders(
entry("Version", asList("1")),
- entry("Foo", asList("Bar"))
- );
+ entry("Foo", asList("Bar")));
assertThat(byConfigKey.get("ParameterizedApi#getAll(Keys)").returnType())
- .isEqualTo(new TypeToken>() {
- }.getType());
+ .isEqualTo(new TypeToken>() {}.getType());
assertThat(byConfigKey.get("ParameterizedApi#getAll(Keys)").bodyType())
- .isEqualTo(new TypeToken>() {
- }.getType());
+ .isEqualTo(new TypeToken>() {}.getType());
assertThat(byConfigKey.get("ParameterizedApi#getAll(Keys)").template()).hasHeaders(
entry("Version", asList("1")),
- entry("Foo", asList("Bar"))
- );
+ entry("Foo", asList("Bar")));
}
@Headers("Authorization: {authHdr}")
- interface ParameterizedHeaderExpandApi {
+ interface ParameterizedHeaderExpandApi {
@RequestLine("GET /api/{zoneId}")
@Headers("Accept: application/json")
String getZone(@Param("zoneId") String vhost, @Param("authHdr") String authHdr);
@@ -688,7 +682,8 @@ interface ParameterizedHeaderExpandApi {
@Test
public void parameterizedHeaderExpandApi() throws Exception {
- List md = contract.parseAndValidatateMetadata(ParameterizedHeaderExpandApi.class);
+ List md =
+ contract.parseAndValidatateMetadata(ParameterizedHeaderExpandApi.class);
assertThat(md).hasSize(1);
@@ -697,7 +692,8 @@ public void parameterizedHeaderExpandApi() throws Exception {
assertThat(md.get(0).returnType())
.isEqualTo(String.class);
assertThat(md.get(0).template())
- .hasHeaders(entry("Authorization", asList("{authHdr}")), entry("Accept", asList("application/json")));
+ .hasHeaders(entry("Authorization", asList("{authHdr}")),
+ entry("Accept", asList("application/json")));
// Ensure that the authHdr expansion was properly detected and did not create a formParam
assertThat(md.get(0).formParams())
.isEmpty();
@@ -705,8 +701,7 @@ public void parameterizedHeaderExpandApi() throws Exception {
@Test
public void parameterizedHeaderNotStartingWithCurlyBraceExpandApi() throws Exception {
- List
- md =
+ List md =
contract.parseAndValidatateMetadata(
ParameterizedHeaderNotStartingWithCurlyBraceExpandApi.class);
@@ -746,7 +741,8 @@ interface ParameterizedHeaderExpandInheritedApi extends ParameterizedHeaderBase
@Test
public void parameterizedHeaderExpandApiBaseClass() throws Exception {
- List mds = contract.parseAndValidatateMetadata(ParameterizedHeaderExpandInheritedApi.class);
+ List mds =
+ contract.parseAndValidatateMetadata(ParameterizedHeaderExpandInheritedApi.class);
Map byConfigKey = new LinkedHashMap();
for (MethodMetadata m : mds) {
@@ -755,18 +751,20 @@ public void parameterizedHeaderExpandApiBaseClass() throws Exception {
assertThat(byConfigKey)
.containsOnlyKeys("ParameterizedHeaderExpandInheritedApi#getZoneAccept(String,String)",
- "ParameterizedHeaderExpandInheritedApi#getZone(String,String)");
+ "ParameterizedHeaderExpandInheritedApi#getZone(String,String)");
- MethodMetadata md = byConfigKey.get("ParameterizedHeaderExpandInheritedApi#getZoneAccept(String,String)");
+ MethodMetadata md =
+ byConfigKey.get("ParameterizedHeaderExpandInheritedApi#getZoneAccept(String,String)");
assertThat(md.returnType())
.isEqualTo(String.class);
assertThat(md.template())
- .hasHeaders(entry("Authorization", asList("{authHdr}")), entry("Accept", asList("application/json")));
+ .hasHeaders(entry("Authorization", asList("{authHdr}")),
+ entry("Accept", asList("application/json")));
// Ensure that the authHdr expansion was properly detected and did not create a formParam
assertThat(md.formParams())
.isEmpty();
- md = byConfigKey.get("ParameterizedHeaderExpandInheritedApi#getZone(String,String)");
+ md = byConfigKey.get("ParameterizedHeaderExpandInheritedApi#getZone(String,String)");
assertThat(md.returnType())
.isEqualTo(String.class);
assertThat(md.template())
@@ -775,11 +773,12 @@ public void parameterizedHeaderExpandApiBaseClass() throws Exception {
.isEmpty();
}
- private MethodMetadata parseAndValidateMetadata(Class> targetType, String method,
+ private MethodMetadata parseAndValidateMetadata(Class> targetType,
+ String method,
Class>... parameterTypes)
throws NoSuchMethodException {
return contract.parseAndValidateMetadata(targetType,
- targetType.getMethod(method, parameterTypes));
+ targetType.getMethod(method, parameterTypes));
}
interface MissingMethod {
@@ -791,7 +790,8 @@ interface MissingMethod {
@Test
public void missingMethod() throws Exception {
thrown.expect(IllegalStateException.class);
- thrown.expectMessage("RequestLine annotation didn't start with an HTTP verb on method updateSharing");
+ thrown.expectMessage(
+ "RequestLine annotation didn't start with an HTTP verb on method updateSharing");
contract.parseAndValidatateMetadata(MissingMethod.class);
}
@@ -840,8 +840,7 @@ public void paramIsASubstringOfAQuery() throws Exception {
List mds = contract.parseAndValidatateMetadata(SubstringQuery.class);
assertThat(mds.get(0).template().queries()).containsExactly(
- entry("q", asList("body:{body}"))
- );
+ entry("q", asList("body:{body}")));
assertThat(mds.get(0).formParams()).isEmpty(); // Prevent issue 424
}
}
diff --git a/core/src/test/java/feign/DefaultQueryMapEncoderTest.java b/core/src/test/java/feign/DefaultQueryMapEncoderTest.java
index 63df04da72..0b8179b839 100644
--- a/core/src/test/java/feign/DefaultQueryMapEncoderTest.java
+++ b/core/src/test/java/feign/DefaultQueryMapEncoderTest.java
@@ -18,7 +18,6 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
diff --git a/core/src/test/java/feign/EmptyTargetTest.java b/core/src/test/java/feign/EmptyTargetTest.java
index 6f6d838058..821b312143 100644
--- a/core/src/test/java/feign/EmptyTargetTest.java
+++ b/core/src/test/java/feign/EmptyTargetTest.java
@@ -16,11 +16,8 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-
import java.net.URI;
-
import feign.Target.EmptyTarget;
-
import static feign.assertj.FeignAssertions.assertThat;
public class EmptyTargetTest {
diff --git a/core/src/test/java/feign/FeignBuilderTest.java b/core/src/test/java/feign/FeignBuilderTest.java
index 3c78598427..a69b4c681e 100644
--- a/core/src/test/java/feign/FeignBuilderTest.java
+++ b/core/src/test/java/feign/FeignBuilderTest.java
@@ -16,10 +16,8 @@
import java.util.HashMap;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
-
import org.junit.Rule;
import org.junit.Test;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
@@ -33,10 +31,8 @@
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-
import feign.codec.Decoder;
import feign.codec.Encoder;
-
import static feign.assertj.MockWebServerAssertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.junit.Assert.assertEquals;
@@ -86,13 +82,14 @@ public void testDecode404() throws Exception {
- @Test public void testNoFollowRedirect() {
- server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location","/"));
+ @Test
+ public void testNoFollowRedirect() {
+ server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location", "/"));
String url = "http://localhost:" + server.getPort();
TestInterface noFollowApi = Feign.builder()
- .options(new Request.Options(100, 600, false))
- .target(TestInterface.class, url);
+ .options(new Request.Options(100, 600, false))
+ .target(TestInterface.class, url);
Response response = noFollowApi.defaultMethodPassthrough();
assertThat(response.status()).isEqualTo(302);
@@ -100,11 +97,11 @@ public void testDecode404() throws Exception {
.isNotNull()
.isEqualTo(Collections.singletonList("/"));
- server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location","/"));
+ server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location", "/"));
server.enqueue(new MockResponse().setResponseCode(200));
TestInterface defaultApi = Feign.builder()
- .options(new Request.Options(100, 600, true))
- .target(TestInterface.class, url);
+ .options(new Request.Options(100, 600, true))
+ .target(TestInterface.class, url);
assertThat(defaultApi.defaultMethodPassthrough().status()).isEqualTo(200);
}
@@ -205,7 +202,8 @@ public Map encode(Object ignored) {
}
};
- TestInterface api = Feign.builder().queryMapEncoder(customMapEncoder).target(TestInterface.class, url);
+ TestInterface api =
+ Feign.builder().queryMapEncoder(customMapEncoder).target(TestInterface.class, url);
api.queryMapEncoded("ignored");
assertThat(server.takeRequest()).hasQueryParams(Arrays.asList("key1=value1", "key2=value2"));
@@ -299,11 +297,10 @@ public void testDefaultCallingProxiedMethod() throws Exception {
/**
* This test ensures that the doNotCloseAfterDecode flag functions.
*
- * It does so by creating a custom Decoder that lazily retrieves the
- * response body when asked for it and pops the value into an Iterator.
+ * It does so by creating a custom Decoder that lazily retrieves the response body when asked for
+ * it and pops the value into an Iterator.
*
- * Without the doNoCloseAfterDecode flag, the test will fail with a
- * "stream is closed" exception.
+ * Without the doNoCloseAfterDecode flag, the test will fail with a "stream is closed" exception.
*
* @throws Exception
*/
@@ -340,9 +337,9 @@ public Object next() {
};
TestInterface api = Feign.builder()
- .decoder(decoder)
- .doNotCloseAfterDecode()
- .target(TestInterface.class, url);
+ .decoder(decoder)
+ .doNotCloseAfterDecode()
+ .target(TestInterface.class, url);
Iterator iterator = api.decodedLazyPost();
assertTrue(iterator.hasNext());
@@ -353,8 +350,8 @@ public Object next() {
}
/**
- * When {@link Feign.Builder#doNotCloseAfterDecode()} is enabled an an exception
- * is thrown from the {@link Decoder}, the response should be closed.
+ * When {@link Feign.Builder#doNotCloseAfterDecode()} is enabled an an exception is thrown from
+ * the {@link Decoder}, the response should be closed.
*/
@Test
public void testDoNotCloseAfterDecodeDecoderFailure() throws Exception {
@@ -370,49 +367,50 @@ public Object decode(Response response, Type type) throws IOException {
final AtomicBoolean closed = new AtomicBoolean();
TestInterface api = Feign.builder()
- .client(new Client() {
- Client client = new Client.Default(null, null);
- @Override
- public Response execute(Request request, Request.Options options) throws IOException {
- final Response original = client.execute(request, options);
- return Response.builder()
- .status(original.status())
- .headers(original.headers())
- .reason(original.reason())
- .request(original.request())
- .body(new Response.Body() {
- @Override
- public Integer length() {
- return original.body().length();
- }
-
- @Override
- public boolean isRepeatable() {
- return original.body().isRepeatable();
- }
-
- @Override
- public InputStream asInputStream() throws IOException {
- return original.body().asInputStream();
- }
-
- @Override
- public Reader asReader() throws IOException {
- return original.body().asReader();
- }
-
- @Override
- public void close() throws IOException {
- closed.set(true);
- original.body().close();
- }
- })
- .build();
- }
- })
- .decoder(angryDecoder)
- .doNotCloseAfterDecode()
- .target(TestInterface.class, url);
+ .client(new Client() {
+ Client client = new Client.Default(null, null);
+
+ @Override
+ public Response execute(Request request, Request.Options options) throws IOException {
+ final Response original = client.execute(request, options);
+ return Response.builder()
+ .status(original.status())
+ .headers(original.headers())
+ .reason(original.reason())
+ .request(original.request())
+ .body(new Response.Body() {
+ @Override
+ public Integer length() {
+ return original.body().length();
+ }
+
+ @Override
+ public boolean isRepeatable() {
+ return original.body().isRepeatable();
+ }
+
+ @Override
+ public InputStream asInputStream() throws IOException {
+ return original.body().asInputStream();
+ }
+
+ @Override
+ public Reader asReader() throws IOException {
+ return original.body().asReader();
+ }
+
+ @Override
+ public void close() throws IOException {
+ closed.set(true);
+ original.body().close();
+ }
+ })
+ .build();
+ }
+ })
+ .decoder(angryDecoder)
+ .doNotCloseAfterDecode()
+ .target(TestInterface.class, url);
try {
api.decodedLazyPost();
fail("Expected an exception");
diff --git a/core/src/test/java/feign/FeignTest.java b/core/src/test/java/feign/FeignTest.java
index fcba7548ad..0ddcf744a7 100644
--- a/core/src/test/java/feign/FeignTest.java
+++ b/core/src/test/java/feign/FeignTest.java
@@ -15,11 +15,9 @@
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
-
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.mockwebserver.MockWebServer;
-
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
@@ -29,7 +27,6 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
@@ -40,7 +37,6 @@
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicReference;
-
import feign.Target.HardCodedTarget;
import feign.codec.DecodeException;
import feign.codec.Decoder;
@@ -49,7 +45,6 @@
import feign.codec.ErrorDecoder;
import feign.codec.StringDecoder;
import feign.Feign.ResponseMappingDecoder;
-
import static feign.Util.UTF_8;
import static feign.assertj.MockWebServerAssertions.assertThat;
import static org.hamcrest.CoreMatchers.isA;
@@ -147,8 +142,7 @@ public void encode(Object object, Type bodyType, RequestTemplate template) {
server.takeRequest();
- assertThat(encodedType.get()).isEqualTo(new TypeToken>() {
- }.getType());
+ assertThat(encodedType.get()).isEqualTo(new TypeToken>() {}.getType());
}
@Test
@@ -203,7 +197,7 @@ public void multipleInterceptor() throws Exception {
api.post();
assertThat(server.takeRequest()).hasHeaders("X-Forwarded-For: origin.host.com",
- "User-Agent: Feign");
+ "User-Agent: Feign");
}
@Test
@@ -254,9 +248,9 @@ public void headerMap() throws Exception {
api.headerMap(headerMap);
assertThat(server.takeRequest())
- .hasHeaders(
- MapEntry.entry("Content-Type", Arrays.asList("myContent")),
- MapEntry.entry("Custom-Header", Arrays.asList("fooValue")));
+ .hasHeaders(
+ MapEntry.entry("Content-Type", Arrays.asList("myContent")),
+ MapEntry.entry("Custom-Header", Arrays.asList("fooValue")));
}
@Test
@@ -271,9 +265,9 @@ public void headerMapWithHeaderAnnotations() throws Exception {
// header map should be additive for headers provided by annotations
assertThat(server.takeRequest())
- .hasHeaders(
- MapEntry.entry("Content-Encoding", Arrays.asList("deflate")),
- MapEntry.entry("Custom-Header", Arrays.asList("fooValue")));
+ .hasHeaders(
+ MapEntry.entry("Content-Encoding", Arrays.asList("deflate")),
+ MapEntry.entry("Custom-Header", Arrays.asList("fooValue")));
server.enqueue(new MockResponse());
headerMap.put("Content-Encoding", "overrideFromMap");
@@ -283,9 +277,9 @@ public void headerMapWithHeaderAnnotations() throws Exception {
// if header map has entry that collides with annotation, value specified
// by header map should be used
assertThat(server.takeRequest())
- .hasHeaders(
- MapEntry.entry("Content-Encoding", Arrays.asList("overrideFromMap")),
- MapEntry.entry("Custom-Header", Arrays.asList("fooValue")));
+ .hasHeaders(
+ MapEntry.entry("Content-Encoding", Arrays.asList("overrideFromMap")),
+ MapEntry.entry("Custom-Header", Arrays.asList("fooValue")));
}
@Test
@@ -300,7 +294,7 @@ public void queryMap() throws Exception {
api.queryMap(queryMap);
assertThat(server.takeRequest())
- .hasPath("/?name=alice&fooKey=fooValue");
+ .hasPath("/?name=alice&fooKey=fooValue");
}
@Test
@@ -317,13 +311,13 @@ public void queryMapIterableValuesExpanded() throws Exception {
api.queryMap(queryMap);
assertThat(server.takeRequest())
- .hasPath("/?name=Alice&name=Bob&fooKey=fooValue&emptyStringKey=");
+ .hasPath("/?name=Alice&name=Bob&fooKey=fooValue&emptyStringKey=");
}
@Test
public void queryMapWithQueryParams() throws Exception {
TestInterface api = new TestInterfaceBuilder()
- .target("http://localhost:" + server.getPort());
+ .target("http://localhost:" + server.getPort());
server.enqueue(new MockResponse());
Map queryMap = new LinkedHashMap();
@@ -331,7 +325,7 @@ public void queryMapWithQueryParams() throws Exception {
api.queryMapWithQueryParams("alice", queryMap);
// query map should be expanded after built-in parameters
assertThat(server.takeRequest())
- .hasPath("/?name=alice&fooKey=fooValue");
+ .hasPath("/?name=alice&fooKey=fooValue");
server.enqueue(new MockResponse());
queryMap = new LinkedHashMap();
@@ -339,7 +333,7 @@ public void queryMapWithQueryParams() throws Exception {
api.queryMapWithQueryParams("alice", queryMap);
// query map keys take precedence over built-in parameters
assertThat(server.takeRequest())
- .hasPath("/?name=bob");
+ .hasPath("/?name=bob");
server.enqueue(new MockResponse());
queryMap = new LinkedHashMap();
@@ -347,7 +341,7 @@ public void queryMapWithQueryParams() throws Exception {
api.queryMapWithQueryParams("alice", queryMap);
// null value for a query map key removes query parameter
assertThat(server.takeRequest())
- .hasPath("/");
+ .hasPath("/");
}
@Test
@@ -422,17 +416,17 @@ public void queryMapPojoWithEmptyParams() throws Exception {
@Test
public void configKeyFormatsAsExpected() throws Exception {
assertEquals("TestInterface#post()",
- Feign.configKey(TestInterface.class.getDeclaredMethod("post")));
+ Feign.configKey(TestInterface.class.getDeclaredMethod("post")));
assertEquals("TestInterface#uriParam(String,URI,String)",
- Feign.configKey(TestInterface.class
- .getDeclaredMethod("uriParam", String.class, URI.class,
- String.class)));
+ Feign.configKey(TestInterface.class
+ .getDeclaredMethod("uriParam", String.class, URI.class,
+ String.class)));
}
@Test
public void configKeyUsesChildType() throws Exception {
assertEquals("List#iterator()",
- Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator")));
+ Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator")));
}
@Test
@@ -526,15 +520,13 @@ public void ensureRetryerClonesItself() {
MockRetryer retryer = new MockRetryer();
TestInterface api = Feign.builder()
- .retryer(retryer)
- .errorDecoder(new ErrorDecoder()
- {
- @Override
- public Exception decode(String methodKey, Response response)
- {
- return new RetryableException("play it again sam!", null);
- }
- }).target(TestInterface.class, "http://localhost:" + server.getPort());
+ .retryer(retryer)
+ .errorDecoder(new ErrorDecoder() {
+ @Override
+ public Exception decode(String methodKey, Response response) {
+ return new RetryableException("play it again sam!", null);
+ }
+ }).target(TestInterface.class, "http://localhost:" + server.getPort());
api.post();
api.post(); // if retryer instance was reused, this statement will throw an exception
@@ -546,11 +538,11 @@ public void whenReturnTypeIsResponseNoErrorHandling() {
Map> headers = new LinkedHashMap>();
headers.put("Location", Arrays.asList("http://bar.com"));
final Response response = Response.builder()
- .status(302)
- .reason("Found")
- .headers(headers)
- .body(new byte[0])
- .build();
+ .status(302)
+ .reason("Found")
+ .headers(headers)
+ .body(new byte[0])
+ .build();
TestInterface api = Feign.builder()
.client(new Client() { // fake client as Client.Default follows redirects.
@@ -563,8 +555,7 @@ public Response execute(Request request, Request.Options options) {
assertEquals(api.response().headers().get("Location"), Arrays.asList("http://bar.com"));
}
- private static class MockRetryer implements Retryer
- {
+ private static class MockRetryer implements Retryer {
boolean tripped;
@Override
@@ -578,7 +569,7 @@ public void continueOrPropagate(RetryableException e) {
@Override
public Retryer clone() {
- return new MockRetryer();
+ return new MockRetryer();
}
}
@@ -646,11 +637,9 @@ public void encode(Object object, Type bodyType, RequestTemplate template) {
@Test
public void equalsHashCodeAndToStringWork() {
- Target
- t1 =
+ Target t1 =
new HardCodedTarget(TestInterface.class, "http://localhost:8080");
- Target
- t2 =
+ Target t2 =
new HardCodedTarget(TestInterface.class, "http://localhost:8888");
Target t3 =
new HardCodedTarget(OtherTestInterface.class, "http://localhost:8080");
@@ -689,8 +678,7 @@ public void decodeLogicSupportsByteArray() throws Exception {
byte[] expectedResponse = {12, 34, 56};
server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse)));
- OtherTestInterface
- api =
+ OtherTestInterface api =
Feign.builder().target(OtherTestInterface.class, "http://localhost:" + server.getPort());
assertThat(api.binaryResponseBody())
@@ -702,8 +690,7 @@ public void encodeLogicSupportsByteArray() throws Exception {
byte[] expectedRequest = {12, 34, 56};
server.enqueue(new MockResponse());
- OtherTestInterface
- api =
+ OtherTestInterface api =
Feign.builder().target(OtherTestInterface.class, "http://localhost:" + server.getPort());
api.binaryRequestBody(expectedRequest);
@@ -721,12 +708,13 @@ public void encodedQueryParam() throws Exception {
api.encodedQueryParam("5.2FSi+");
assertThat(server.takeRequest())
- .hasPath("/?trim=5.2FSi+");
+ .hasPath("/?trim=5.2FSi+");
}
@Test
public void responseMapperIsAppliedBeforeDelegate() throws IOException {
- ResponseMappingDecoder decoder = new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder());
+ ResponseMappingDecoder decoder =
+ new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder());
String output = (String) decoder.decode(responseWithText("response"), String.class);
assertThat(output).isEqualTo("RESPONSE");
@@ -738,9 +726,9 @@ private ResponseMapper upperCaseResponseMapper() {
public Response map(Response response, Type type) {
try {
return response
- .toBuilder()
- .body(Util.toString(response.body().asReader()).toUpperCase().getBytes())
- .build();
+ .toBuilder()
+ .body(Util.toString(response.body().asReader()).toUpperCase().getBytes())
+ .build();
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -750,10 +738,10 @@ public Response map(Response response, Type type) {
private Response responseWithText(String text) {
return Response.builder()
- .body(text, Util.UTF_8)
- .status(200)
- .headers(new HashMap>())
- .build();
+ .body(text, Util.UTF_8)
+ .status(200)
+ .headers(new HashMap>())
+ .build();
}
@Test
@@ -761,8 +749,8 @@ public void mapAndDecodeExecutesMapFunction() {
server.enqueue(new MockResponse().setBody("response!"));
TestInterface api = new Feign.Builder()
- .mapAndDecode(upperCaseResponseMapper(), new StringDecoder())
- .target(TestInterface.class, "http://localhost:" + server.getPort());
+ .mapAndDecode(upperCaseResponseMapper(), new StringDecoder())
+ .target(TestInterface.class, "http://localhost:" + server.getPort());
assertEquals(api.post(), "RESPONSE!");
}
@@ -778,8 +766,9 @@ interface TestInterface {
@RequestLine("POST /")
@Body("%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
void login(
- @Param("customer_name") String customer, @Param("user_name") String user,
- @Param("password") String password);
+ @Param("customer_name") String customer,
+ @Param("user_name") String user,
+ @Param("password") String password);
@RequestLine("POST /")
void body(List contents);
@@ -794,8 +783,9 @@ void login(
@RequestLine("POST /")
void form(
- @Param("customer_name") String customer, @Param("user_name") String user,
- @Param("password") String password);
+ @Param("customer_name") String customer,
+ @Param("user_name") String user,
+ @Param("password") String password);
@RequestLine("GET /{1}/{2}")
Response uriParam(@Param("1") String one, URI endpoint, @Param("2") String two);
@@ -826,7 +816,8 @@ void form(
void queryMapEncoded(@QueryMap(encoded = true) Map queryMap);
@RequestLine("GET /?name={name}")
- void queryMapWithQueryParams(@Param("name") String name, @QueryMap Map queryMap);
+ void queryMapWithQueryParams(@Param("name") String name,
+ @QueryMap Map queryMap);
@RequestLine("GET /?trim={trim}")
void encodedQueryParam(@Param(value = "trim", encoded = true) String trim);
diff --git a/core/src/test/java/feign/LoggerTest.java b/core/src/test/java/feign/LoggerTest.java
index d284bc685e..6f8ac7d688 100644
--- a/core/src/test/java/feign/LoggerTest.java
+++ b/core/src/test/java/feign/LoggerTest.java
@@ -15,7 +15,6 @@
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
-
import org.assertj.core.api.SoftAssertions;
import org.junit.Rule;
import org.junit.Test;
@@ -28,13 +27,11 @@
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.model.Statement;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
-
import feign.Logger.Level;
@RunWith(Enclosed.class)
@@ -46,7 +43,7 @@ public class LoggerTest {
/** Ensure expected exception handling is done before logger rule. */
@Rule
- public final RuleChain chain= RuleChain.outerRule( server ).around( logger ).around( thrown );
+ public final RuleChain chain = RuleChain.outerRule(server).around(logger).around(thrown);
interface SendsStuff {
@@ -55,8 +52,9 @@ interface SendsStuff {
@Headers("Content-Type: application/json")
@Body("%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
String login(
- @Param("customer_name") String customer,
- @Param("user_name") String user, @Param("password") String password);
+ @Param("customer_name") String customer,
+ @Param("user_name") String user,
+ @Param("password") String password);
}
@RunWith(Parameterized.class)
@@ -71,7 +69,7 @@ public LogLevelEmitsTest(Level logLevel, List expectedMessages) {
@Parameters
public static Iterable