From f5f959716e3cced6ed170a39248bc4d10443fcc7 Mon Sep 17 00:00:00 2001 From: cbornet Date: Tue, 13 Sep 2016 18:36:52 +0200 Subject: [PATCH] [retrofit2] use gson ISO8601Utils to parse dates See #3727 --- .../codegen/languages/JavaClientCodegen.java | 3 + .../libraries/okhttp-gson/ApiClient.mustache | 8 +- .../Java/libraries/okhttp-gson/JSON.mustache | 1 + .../libraries/retrofit2/ApiClient.mustache | 274 ++++-------- .../Java/libraries/retrofit2/JSON.mustache | 394 ++++++++++++++++++ .../src/main/java/io/swagger/client/JSON.java | 1 + .../java/io/swagger/client/ApiClient.java | 176 +++----- .../src/main/java/io/swagger/client/JSON.java | 299 +++++++++++++ .../java/io/swagger/client/ApiClient.java | 172 +++----- .../src/main/java/io/swagger/client/JSON.java | 299 +++++++++++++ 10 files changed, 1227 insertions(+), 400 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/JSON.mustache create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index db181498586a..78a36f2b9ec8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -126,6 +126,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); additionalProperties.put("gson", "true"); + if ("retrofit2".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); + } } else if("jersey2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); additionalProperties.put("jackson", "true"); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index f0b4cc64334c..b015848b6b06 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -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}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index d43376a992ce..ed914297740a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -71,6 +71,7 @@ public class JSON { * Set Gson. * * @param gson Gson + * @return JSON */ public JSON setGson(Gson gson) { this.gson = gson; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index f94349787043..1893394ab282 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -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 apiAuthorizations; private OkHttpClient.Builder okBuilder; private Retrofit.Builder adapterBuilder; + private JSON json; public ApiClient() { apiAuthorizations = new LinkedHashMap(); @@ -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 createService(Class 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 getApiAuthorizations() { return apiAuthorizations; } - public void setApiAuthorizations(Map apiAuthorizations) { + public ApiClient setApiAuthorizations(Map 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 { - - 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 { - - 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 { - - 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 { - - 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}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/JSON.mustache new file mode 100644 index 000000000000..31429ac566f3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/JSON.mustache @@ -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 { + + 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 { + + 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 { + + 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 { + + 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 { + + 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 { + + 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; + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 64c68da1f251..29adac4dab4c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -75,6 +75,7 @@ public class JSON { * Set Gson. * * @param gson Gson + * @return JSON */ public JSON setGson(Gson gson) { this.gson = gson; diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index be9eadc33bab..a665adcd4f39 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -1,48 +1,37 @@ package io.swagger.client; -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; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; -import retrofit2.Converter; -import retrofit2.Retrofit; - -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; +import org.joda.time.format.DateTimeFormatter; +import retrofit2.Converter; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; +import retrofit2.converter.scalars.ScalarsConverterFactory; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; import io.swagger.client.auth.OAuth.AccessTokenListener; import io.swagger.client.auth.OAuthFlow; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.util.LinkedHashMap; +import java.util.Map; public class ApiClient { private Map apiAuthorizations; private OkHttpClient.Builder okBuilder; private Retrofit.Builder adapterBuilder; + private JSON json; public ApiClient() { apiAuthorizations = new LinkedHashMap(); @@ -53,11 +42,11 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { + if (authName.equals("api_key")) { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "http_basic_test") { + } else if (authName.equals("http_basic_test")) { auth = new HttpBasicAuth(); - } else if (authName == "petstore_auth") { + } else if (authName.equals("petstore_auth")) { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); @@ -113,12 +102,7 @@ public class ApiClient { } public void createDefaultAdapter() { - Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - + json = new JSON(); okBuilder = new OkHttpClient.Builder(); String baseUrl = "http://petstore.swagger.io/v2"; @@ -128,9 +112,8 @@ public class ApiClient { adapterBuilder = new Retrofit .Builder() .baseUrl(baseUrl) - .addConverterFactory(ScalarsConverterFactory.create()) - .addConverterFactory(GsonCustomConverterFactory.create(gson)); + .addConverterFactory(GsonCustomConverterFactory.create(json.getGson())); } public S createService(Class serviceClass) { @@ -141,38 +124,63 @@ 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; + } + + public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) { + this.json.setDateTimeFormat(dateFormat); + return this; + } + + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + this.json.setLocalDateFormat(dateFormat); + return this; + } + + /** * 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; } /** @@ -206,15 +214,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; } /** @@ -222,8 +232,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; @@ -234,52 +245,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 getApiAuthorizations() { return apiAuthorizations; } - public void setApiAuthorizations(Map apiAuthorizations) { + public ApiClient setApiAuthorizations(Map 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() { @@ -299,7 +317,6 @@ public class ApiClient { public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); addAuthsToOkBuilder(this.okBuilder); - } } @@ -357,60 +374,3 @@ class GsonCustomConverterFactory extends Converter.Factory } } -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - 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 { - - 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); - } - } -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..b3f431326f55 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,299 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +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; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +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; +import java.util.Date; + +public class JSON { + private Gson gson; + private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter(); + private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + + public JSON() { + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, dateTypeAdapter) + .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) + .registerTypeAdapter(DateTime.class, dateTimeTypeAdapter) + .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) + .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; + } + + /** + * Gson TypeAdapter for Joda DateTime type + */ + public static class DateTimeTypeAdapter extends TypeAdapter { + + 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 { + + 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; + } + + /** + * 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 { + + 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 { + + 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; + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index cc82b88c4251..22eea6769c0d 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -1,48 +1,38 @@ package io.swagger.client; -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 com.google.gson.Gson; +import com.google.gson.JsonParseException; +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; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; 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 io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; import io.swagger.client.auth.OAuth.AccessTokenListener; import io.swagger.client.auth.OAuthFlow; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.util.LinkedHashMap; +import java.util.Map; public class ApiClient { private Map apiAuthorizations; private OkHttpClient.Builder okBuilder; private Retrofit.Builder adapterBuilder; + private JSON json; public ApiClient() { apiAuthorizations = new LinkedHashMap(); @@ -53,11 +43,11 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { + if (authName.equals("api_key")) { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "http_basic_test") { + } else if (authName.equals("http_basic_test")) { auth = new HttpBasicAuth(); - } else if (authName == "petstore_auth") { + } else if (authName.equals("petstore_auth")) { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); @@ -113,12 +103,7 @@ public class ApiClient { } public void createDefaultAdapter() { - Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - + json = new JSON(); okBuilder = new OkHttpClient.Builder(); String baseUrl = "http://petstore.swagger.io/v2"; @@ -130,7 +115,7 @@ public class ApiClient { .baseUrl(baseUrl) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create()) - .addConverterFactory(GsonCustomConverterFactory.create(gson)); + .addConverterFactory(GsonCustomConverterFactory.create(json.getGson())); } public S createService(Class serviceClass) { @@ -141,38 +126,63 @@ 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; + } + + public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) { + this.json.setDateTimeFormat(dateFormat); + return this; + } + + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + this.json.setLocalDateFormat(dateFormat); + return this; + } + + /** * 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; } /** @@ -206,15 +216,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; } /** @@ -222,8 +234,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; @@ -234,52 +247,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 getApiAuthorizations() { return apiAuthorizations; } - public void setApiAuthorizations(Map apiAuthorizations) { + public ApiClient setApiAuthorizations(Map 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() { @@ -299,7 +319,6 @@ public class ApiClient { public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); addAuthsToOkBuilder(this.okBuilder); - } } @@ -357,60 +376,3 @@ class GsonCustomConverterFactory extends Converter.Factory } } -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - 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 { - - 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); - } - } -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..b3f431326f55 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,299 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +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; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +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; +import java.util.Date; + +public class JSON { + private Gson gson; + private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter(); + private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + + public JSON() { + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, dateTypeAdapter) + .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) + .registerTypeAdapter(DateTime.class, dateTimeTypeAdapter) + .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) + .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; + } + + /** + * Gson TypeAdapter for Joda DateTime type + */ + public static class DateTimeTypeAdapter extends TypeAdapter { + + 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 { + + 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; + } + + /** + * 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 { + + 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 { + + 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; + } + +}