[retrofit2] use gson ISO8601Utils to parse dates

See #3727
This commit is contained in:
cbornet
2016-09-13 18:36:52 +02:00
parent 2a0574a3ad
commit f5f959716e
10 changed files with 1227 additions and 400 deletions

View File

@@ -212,13 +212,13 @@ public class ApiClient {
{{/joda}}
{{#java8}}
public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
this.json.setOffsetDateTimeFormat(dateFormat);
return this;
this.json.setOffsetDateTimeFormat(dateFormat);
return this;
}
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
this.json.setLocalDateFormat(dateFormat);
return this;
this.json.setLocalDateFormat(dateFormat);
return this;
}
{{/java8}}

View File

@@ -71,6 +71,7 @@ public class JSON {
* Set Gson.
*
* @param gson Gson
* @return JSON
*/
public JSON setGson(Gson gson) {
this.gson = gson;

View File

@@ -1,55 +1,45 @@
package {{invokerPackage}};
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
{{^java8}}
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
{{/java8}}
{{#java8}}
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
{{/java8}}
import retrofit2.Converter;
import retrofit2.Retrofit;
{{#useRxJava}}import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;{{/useRxJava}}
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
{{#joda}}
import org.joda.time.format.DateTimeFormatter;
{{/joda}}
import retrofit2.Converter;
import retrofit2.Retrofit;
{{#useRxJava}}
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
{{/useRxJava}}
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth;
import {{invokerPackage}}.auth.OAuth.AccessTokenListener;
import {{invokerPackage}}.auth.OAuthFlow;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.DateFormat;
{{#java8}}
import java.time.format.DateTimeFormatter;
{{/java8}}
import java.util.LinkedHashMap;
import java.util.Map;
public class ApiClient {
private Map<String, Interceptor> apiAuthorizations;
private OkHttpClient.Builder okBuilder;
private Retrofit.Builder adapterBuilder;
private JSON json;
public ApiClient() {
apiAuthorizations = new LinkedHashMap<String, Interceptor>();
@@ -60,7 +50,7 @@ public class ApiClient {
this();
for(String authName : authNames) { {{#hasAuthMethods}}
Interceptor auth;
{{#authMethods}}if (authName == "{{name}}") { {{#isBasic}}
{{#authMethods}}if (authName.equals("{{name}}")) { {{#isBasic}}
auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}}
@@ -119,17 +109,7 @@ public class ApiClient {
}
public void createDefaultAdapter() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
{{^java8}}
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
{{/java8}}
{{#java8}}
.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
{{/java8}}
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
json = new JSON();
okBuilder = new OkHttpClient.Builder();
String baseUrl = "{{{basePath}}}";
@@ -139,9 +119,11 @@ public class ApiClient {
adapterBuilder = new Retrofit
.Builder()
.baseUrl(baseUrl)
{{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}}
{{#useRxJava}}
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
{{/useRxJava}}
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonCustomConverterFactory.create(gson));
.addConverterFactory(GsonCustomConverterFactory.create(json.getGson()));
}
public <S> S createService(Class<S> serviceClass) {
@@ -152,38 +134,77 @@ public class ApiClient {
}
public ApiClient setDateFormat(DateFormat dateFormat) {
this.json.setDateFormat(dateFormat);
return this;
}
public ApiClient setSqlDateFormat(DateFormat dateFormat) {
this.json.setSqlDateFormat(dateFormat);
return this;
}
{{#joda}}
public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) {
this.json.setDateTimeFormat(dateFormat);
return this;
}
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
this.json.setLocalDateFormat(dateFormat);
return this;
}
{{/joda}}
{{#java8}}
public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
this.json.setOffsetDateTimeFormat(dateFormat);
return this;
}
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
this.json.setLocalDateFormat(dateFormat);
return this;
}
{{/java8}}
/**
* Helper method to configure the first api key found
* @param apiKey API key
* @return ApiClient
*/
private void setApiKey(String apiKey) {
public ApiClient setApiKey(String apiKey) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof ApiKeyAuth) {
ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization;
keyAuth.setApiKey(apiKey);
return;
return this;
}
}
return this;
}
/**
* Helper method to configure the username/password for basic auth or password oauth
* @param username Username
* @param password Password
* @return ApiClient
*/
private void setCredentials(String username, String password) {
public ApiClient setCredentials(String username, String password) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof HttpBasicAuth) {
HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization;
basicAuth.setCredentials(username, password);
return;
return this;
}
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder().setUsername(username).setPassword(password);
return;
return this;
}
}
return this;
}
/**
@@ -217,15 +238,17 @@ public class ApiClient {
/**
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
* @param accessToken Access token
* @return ApiClient
*/
public void setAccessToken(String accessToken) {
public ApiClient setAccessToken(String accessToken) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.setAccessToken(accessToken);
return;
return this;
}
}
return this;
}
/**
@@ -233,8 +256,9 @@ public class ApiClient {
* @param clientId Client ID
* @param clientSecret Client secret
* @param redirectURI Redirect URI
* @return ApiClient
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
public ApiClient configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
@@ -245,52 +269,59 @@ public class ApiClient {
oauth.getAuthenticationRequestBuilder()
.setClientId(clientId)
.setRedirectURI(redirectURI);
return;
return this;
}
}
return this;
}
/**
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener Access token listener
* @return ApiClient
*/
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
public ApiClient registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.registerAccessTokenListener(accessTokenListener);
return;
return this;
}
}
return this;
}
/**
* Adds an authorization to be used by the client
* @param authName Authentication name
* @param authorization Authorization interceptor
* @return ApiClient
*/
public void addAuthorization(String authName, Interceptor authorization) {
public ApiClient addAuthorization(String authName, Interceptor authorization) {
if (apiAuthorizations.containsKey(authName)) {
throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations");
}
apiAuthorizations.put(authName, authorization);
okBuilder.addInterceptor(authorization);
return this;
}
public Map<String, Interceptor> getApiAuthorizations() {
return apiAuthorizations;
}
public void setApiAuthorizations(Map<String, Interceptor> apiAuthorizations) {
public ApiClient setApiAuthorizations(Map<String, Interceptor> apiAuthorizations) {
this.apiAuthorizations = apiAuthorizations;
return this;
}
public Retrofit.Builder getAdapterBuilder() {
return adapterBuilder;
}
public void setAdapterBuilder(Retrofit.Builder adapterBuilder) {
public ApiClient setAdapterBuilder(Retrofit.Builder adapterBuilder) {
this.adapterBuilder = adapterBuilder;
return this;
}
public OkHttpClient.Builder getOkBuilder() {
@@ -310,7 +341,6 @@ public class ApiClient {
public void configureFromOkclient(OkHttpClient okClient) {
this.okBuilder = okClient.newBuilder();
addAuthsToOkBuilder(this.okBuilder);
}
}
@@ -368,125 +398,3 @@ class GsonCustomConverterFactory extends Converter.Factory
}
}
{{^java8}}
/**
* Gson TypeAdapter for Joda DateTime type
*/
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public DateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseDateTime(date);
}
}
}
/**
* Gson TypeAdapter for Joda LocalDate type
*/
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseLocalDate(date);
}
}
}
{{/java8}}
{{#java8}}
/**
* Gson TypeAdapter for jsr310 OffsetDateTime type
*/
class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
@Override
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public OffsetDateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
if (date.endsWith("+0000")) {
date = date.substring(0, date.length()-5) + "Z";
}
return OffsetDateTime.parse(date, formatter);
}
}
}
/**
* Gson TypeAdapter for jsr310 LocalDate type
*/
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return LocalDate.parse(date, formatter);
}
}
}
{{/java8}}

View File

@@ -0,0 +1,394 @@
{{>licenseInfo}}
package {{invokerPackage}};
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
{{#joda}}
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
{{/joda}}
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
{{#java8}}
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
{{/java8}}
import java.util.Date;
public class JSON {
private Gson gson;
private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
{{#joda}}
private DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter();
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
{{/joda}}
{{#java8}}
private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
{{/java8}}
public JSON() {
gson = new GsonBuilder()
.registerTypeAdapter(Date.class, dateTypeAdapter)
.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
{{#joda}}
.registerTypeAdapter(DateTime.class, dateTimeTypeAdapter)
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
{{/joda}}
{{#java8}}
.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
{{/java8}}
.create();
}
/**
* Get Gson.
*
* @return Gson
*/
public Gson getGson() {
return gson;
}
/**
* Set Gson.
*
* @param gson Gson
* @return JSON
*/
public JSON setGson(Gson gson) {
this.gson = gson;
return this;
}
{{#joda}}
/**
* Gson TypeAdapter for Joda DateTime type
*/
public static class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
private DateTimeFormatter formatter;
public DateTimeTypeAdapter() {
this(ISODateTimeFormat.dateTime().withOffsetParsed());
}
public DateTimeTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public DateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseDateTime(date);
}
}
}
/**
* Gson TypeAdapter for Joda LocalDate type
*/
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private DateTimeFormatter formatter;
public LocalDateTypeAdapter() {
this(ISODateTimeFormat.date());
}
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.print(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return formatter.parseLocalDate(date);
}
}
}
public JSON setDateTimeFormat(DateTimeFormatter dateFormat) {
dateTimeTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
localDateTypeAdapter.setFormat(dateFormat);
return this;
}
{{/joda}}
{{#java8}}
/**
* Gson TypeAdapter for JSR310 OffsetDateTime type
*/
public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
private DateTimeFormatter formatter;
public OffsetDateTimeTypeAdapter() {
this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public OffsetDateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
if (date.endsWith("+0000")) {
date = date.substring(0, date.length()-5) + "Z";
}
return OffsetDateTime.parse(date, formatter);
}
}
}
/**
* Gson TypeAdapter for JSR310 LocalDate type
*/
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private DateTimeFormatter formatter;
public LocalDateTypeAdapter() {
this(DateTimeFormatter.ISO_LOCAL_DATE);
}
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return LocalDate.parse(date, formatter);
}
}
}
public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
offsetDateTimeTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
localDateTypeAdapter.setFormat(dateFormat);
return this;
}
{{/java8}}
/**
* Gson TypeAdapter for java.sql.Date type
* If the dateFormat is null, a simple "yyyy-MM-dd" format will be used
* (more efficient than SimpleDateFormat).
*/
public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
private DateFormat dateFormat;
public SqlDateTypeAdapter() {
}
public SqlDateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, java.sql.Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = date.toString();
}
out.value(value);
}
}
@Override
public java.sql.Date read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
}
/**
* Gson TypeAdapter for java.util.Date type
* If the dateFormat is null, ISO8601Utils will be used.
*/
public static class DateTypeAdapter extends TypeAdapter<Date> {
private DateFormat dateFormat;
public DateTypeAdapter() {
}
public DateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = ISO8601Utils.format(date, true);
}
out.value(value);
}
}
@Override
public Date read(JsonReader in) throws IOException {
try {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
} catch (IllegalArgumentException e) {
throw new JsonParseException(e);
}
}
}
public JSON setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
}