diff --git a/bin/java-petstore-retrofit2rx.json b/bin/java-petstore-retrofit2rx.json new file mode 100644 index 00000000000..c9e4301f2da --- /dev/null +++ b/bin/java-petstore-retrofit2rx.json @@ -0,0 +1,4 @@ +{ + "library": "retrofit2", + "artifactId": "swagger-petstore-retrofit2-rx" +} diff --git a/bin/java-petstore-retrofit2rx.sh b/bin/java-petstore-retrofit2rx.sh new file mode 100755 index 00000000000..b0320644142 --- /dev/null +++ b/bin/java-petstore-retrofit2rx.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true" + +java $JAVA_OPTS -jar $executable $ags 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 a1ca3245953..dab42b00071 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 @@ -1,20 +1,45 @@ package io.swagger.codegen.languages; import com.google.common.base.Strings; -import io.swagger.codegen.*; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.util.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @SuppressWarnings("hiding") @@ -22,6 +47,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String FULL_JAVA_UTIL = "fullJavaUtil"; public static final String DEFAULT_LIBRARY = ""; public static final String DATE_LIBRARY = "dateLibrary"; + public static final String USE_RX_JAVA = "useRxJava"; + + public static final String RETROFIT_1 = "retrofit"; + public static final String RETROFIT_2 = "retrofit2"; protected String dateLibrary = "default"; protected String invokerPackage = "io.swagger.client"; @@ -35,6 +64,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String javaUtilPrefix = ""; protected Boolean serializableModel = false; protected boolean serializeBigDecimalAsString = false; + protected boolean useRxJava = false; public JavaClientCodegen() { super(); @@ -88,13 +118,15 @@ public JavaClientCodegen() { cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants .SERIALIZE_BIG_DECIMAL_AS_STRING_DESC)); cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util")); + cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); - supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); - supportedLibraries.put("retrofit2", "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)"); + supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); + supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2). Enable the RxJava adapter using '-DuseRxJava=true'."); + CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); library.setEnum(supportedLibraries); @@ -183,6 +215,10 @@ public void processOpts() { if (additionalProperties.containsKey(FULL_JAVA_UTIL)) { this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString())); } + + if (additionalProperties.containsKey(USE_RX_JAVA)) { + this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); + } if (fullJavaUtil) { javaUtilPrefix = "java.util."; } @@ -240,7 +276,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); - if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { + if (!("feign".equals(getLibrary()) || usesAnyRetrofitLibrary())) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); @@ -257,7 +293,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - } else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { + } else if (usesAnyRetrofitLibrary()) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); } else if("jersey2".equals(getLibrary())) { @@ -285,6 +321,14 @@ else if ("java8".equals(dateLibrary)) { } } + private boolean usesAnyRetrofitLibrary() { + return getLibrary() != null && getLibrary().contains(RETROFIT_1); + } + + private boolean usesRetrofit2Library() { + return getLibrary() != null && getLibrary().contains(RETROFIT_2); + } + private void sanitizeConfig() { // Sanitize any config options here. We also have to update the additionalProperties because // the whole additionalProperties object is injected into the main object passed to the mustache layer @@ -598,7 +642,7 @@ public Map postProcessModels(Map objs) { @Override public Map postProcessOperations(Map objs) { - if("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { + if(usesAnyRetrofitLibrary()) { Map operations = (Map) objs.get("operations"); if (operations != null) { List ops = (List) operations.get("operation"); @@ -614,7 +658,7 @@ public Map postProcessOperations(Map objs) { if (operation.returnType == null) { operation.returnType = "Void"; } - if ("retrofit2".equals(getLibrary()) && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) + if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) operation.path = operation.path.substring(1); } } @@ -792,6 +836,10 @@ public void setFullJavaUtil(boolean fullJavaUtil) { this.fullJavaUtil = fullJavaUtil; } + public void setUseRxJava(boolean useRxJava) { + this.useRxJava = useRxJava; + } + public void setDateLibrary(String library) { this.dateLibrary = library; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index ffeebeb99eb..f3d61872c08 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -419,25 +419,6 @@ public Map postProcessModels(Map objs) { @Override public Map postProcessOperations(Map objs) { - if("retrofit".equals(getLibrary())) { - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - if (operation.hasConsumes == Boolean.TRUE) { - Map firstType = operation.consumes.get(0); - if (firstType != null) { - if ("multipart/form-data".equals(firstType.get("mediaType"))) { - operation.isMultipart = Boolean.TRUE; - } - } - } - if (operation.returnType == null) { - operation.returnType = "Void"; - } - } - } - } return objs; } 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 56e83f7d915..6cd8aa399f1 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 @@ -13,6 +13,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import retrofit.Converter; import retrofit.Retrofit; import retrofit.GsonConverterFactory; +{{#useRxJava}}import retrofit.RxJavaCallAdapterFactory;{{/useRxJava}} import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -22,6 +23,7 @@ import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.ResponseBody; + import {{invokerPackage}}.auth.HttpBasicAuth; import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; @@ -117,6 +119,7 @@ public class ApiClient { .Builder() .baseUrl(baseUrl) .client(okClient) + {{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}} .addConverterFactory(GsonCustomConverterFactory.create(gson)); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index a066a625cff..ff90557a3fa 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -2,8 +2,10 @@ package {{package}}; import {{invokerPackage}}.CollectionFormats.*; -import retrofit.Call; +{{#useRxJava}}import rx.Observable;{{/useRxJava}} +{{^useRxJava}}import retrofit.Call;{{/useRxJava}} import retrofit.http.*; + import com.squareup.okhttp.RequestBody; {{#imports}}import {{import}}; @@ -25,7 +27,7 @@ public interface {{classname}} { {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") - Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} + {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index cf0047cf283..b4f843603eb 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -20,7 +20,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' - + android { compileSdkVersion 22 buildToolsVersion '22.0.0' @@ -32,7 +32,7 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } - + // Rename the aar correctly libraryVariants.all { variant -> variant.outputs.each { output -> @@ -44,7 +44,7 @@ if(hasProperty('target') && target == 'android') { } } } - + afterEvaluate { android.libraryVariants.all { variant -> def task = project.tasks.create "jar${variant.name.capitalize()}", Jar @@ -56,12 +56,12 @@ if(hasProperty('target') && target == 'android') { artifacts.add('archives', task); } } - + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } - + artifacts { archives sourcesJar } @@ -70,16 +70,16 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - + +sourceCompatibility = JavaVersion.VERSION_1_7 +targetCompatibility = JavaVersion.VERSION_1_7 + install { repositories.mavenInstaller { pom.artifactId = '{{artifactId}}' } } - + task execute(type:JavaExec) { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath @@ -93,14 +93,26 @@ ext { gson_version = "2.4" swagger_annotations_version = "1.5.0" junit_version = "4.12" +{{#useRxJava}} + rx_java_version = "1.0.15" +{{/useRxJava}} +{{^useRxJava}}{{/useRxJava}} } dependencies { compile "com.squareup.okhttp:okhttp:$okhttp_version" + compile "com.squareup.retrofit:retrofit:$retrofit_version" - compile "com.google.code.gson:gson:$gson_version" compile "com.squareup.retrofit:converter-gson:$retrofit_version" +{{#useRxJava}} + compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version" + compile "io.reactivex:rxjava:$rx_java_version" +{{/useRxJava}} +{{^useRxJava}}{{/useRxJava}} + + compile "com.google.code.gson:gson:$gson_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index a155d04ef88..ef322cccb09 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -100,8 +100,9 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + + 1.7 + 1.7 @@ -137,6 +138,18 @@ okhttp ${okhttp-version} + {{#useRxJava}} + + io.reactivex + rxjava + ${rxjava-version} + + + com.squareup.retrofit + adapter-rxjava + ${retrofit-version} + + {{/useRxJava}} @@ -149,6 +162,7 @@ 1.5.0 2.0.0-beta2 + {{#useRxJava}}1.0.15{{/useRxJava}} 2.5.0 2.4 1.0.0 diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java index 49399b3beef..0987a0d236e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java @@ -45,7 +45,7 @@ protected void setExpectations() { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.LIBRARY_VALUE); + clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.DEFAULT_LIBRARY_VALUE); times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index 2a4d582f776..701f9586eec 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -51,7 +51,7 @@ protected void setExpectations() { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(JavaOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setLibrary(JavaOptionsProvider.LIBRARY_VALUE); + clientCodegen.setLibrary(JavaOptionsProvider.DEFAULT_LIBRARY_VALUE); times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java index a441a7984d2..f6f7b1633bc 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -46,7 +46,7 @@ protected void setExpectations() { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setLibrary(JaxRSServerOptionsProvider.LIBRARY_VALUE); + clientCodegen.setLibrary(JaxRSServerOptionsProvider.DEFAULT_LIBRARY_VALUE); times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index 32490ba659b..bf6fd0aba7d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -1,5 +1,6 @@ package io.swagger.codegen.options; +import io.swagger.codegen.Codegen; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.JavaClientCodegen; @@ -17,15 +18,19 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String LOCAL_PREFIX_VALUE = "tst"; - public static final String LIBRARY_VALUE = "jersey2"; + public static final String DEFAULT_LIBRARY_VALUE = "jersey2"; public static final String SERIALIZABLE_MODEL_VALUE = "false"; public static final String FULL_JAVA_UTIL_VALUE = "true"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + private ImmutableMap options; + + /** + * Create an options provider with the default options. + */ + public JavaOptionsProvider() { + options = new ImmutableMap.Builder() + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) @@ -37,12 +42,28 @@ public Map createOptions() { .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) - .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) + .put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE) .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") + .put(JavaClientCodegen.USE_RX_JAVA, "false") .put(JavaClientCodegen.DATE_LIBRARY, "joda") .build(); } + /** + * Use the default options, but override the ones found in additionalOptions. + */ + public JavaOptionsProvider(Map additionalOptions) { + options = new ImmutableMap.Builder() + .putAll(options) + .putAll(additionalOptions) + .build(); + } + + @Override + public Map createOptions() { + return options; + } + @Override public boolean isServer() { return false; diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java index 626255519bf..2ae76374adb 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java @@ -1,64 +1,31 @@ package io.swagger.generator.online; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfigLoader; -import io.swagger.codegen.options.AkkaScalaClientOptionsProvider; -import io.swagger.codegen.options.AndroidClientOptionsProvider; -import io.swagger.codegen.options.AsyncScalaClientOptionsProvider; -import io.swagger.codegen.options.CSharpClientOptionsProvider; -import io.swagger.codegen.options.CsharpDotNet2ClientOptionsProvider; -import io.swagger.codegen.options.DartClientOptionsProvider; -import io.swagger.codegen.options.FlashClienOptionsProvider; -import io.swagger.codegen.options.JavaInflectorServerOptionsProvider; -import io.swagger.codegen.options.JavaOptionsProvider; -import io.swagger.codegen.options.JaxRSServerOptionsProvider; -import io.swagger.codegen.options.NodeJSServerOptionsProvider; -import io.swagger.codegen.options.ObjcClientOptionsProvider; -import io.swagger.codegen.options.OptionsProvider; -import io.swagger.codegen.options.PerlClientOptionsProvider; -import io.swagger.codegen.options.PhpClientOptionsProvider; -import io.swagger.codegen.options.PythonClientOptionsProvider; -import io.swagger.codegen.options.Qt5CPPOptionsProvider; -import io.swagger.codegen.options.RubyClientOptionsProvider; -import io.swagger.codegen.options.ScalaClientOptionsProvider; -import io.swagger.codegen.options.ScalatraServerOptionsProvider; -import io.swagger.codegen.options.SilexServerOptionsProvider; -import io.swagger.codegen.options.SinatraServerOptionsProvider; -import io.swagger.codegen.options.SlimFrameworkServerOptionsProvider; -import io.swagger.codegen.options.SpringMVCServerOptionsProvider; -import io.swagger.codegen.options.StaticDocOptionsProvider; -import io.swagger.codegen.options.StaticHtmlOptionsProvider; -import io.swagger.codegen.options.SwaggerOptionsProvider; -import io.swagger.codegen.options.SwaggerYamlOptionsProvider; -import io.swagger.codegen.options.SwiftOptionsProvider; -import io.swagger.codegen.options.TizenClientOptionsProvider; -import io.swagger.codegen.options.TypeScriptAngularClientOptionsProvider; -import io.swagger.codegen.options.TypeScriptNodeClientOptionsProvider; -import io.swagger.generator.exception.ApiException; -import io.swagger.generator.model.GeneratorInput; - import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.codegen.options.*; +import io.swagger.generator.exception.ApiException; +import io.swagger.generator.model.GeneratorInput; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.util.*; -import javax.annotation.Nullable; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; public class OnlineGeneratorOptionsTest { private static final String OPTIONS_PROVIDER = "optionsProvider"; @@ -69,7 +36,16 @@ private static Object[][] listOptions() { {new AsyncScalaClientOptionsProvider()}, {new CSharpClientOptionsProvider()}, {new CsharpDotNet2ClientOptionsProvider()}, {new DartClientOptionsProvider()}, {new FlashClienOptionsProvider()}, {new JavaInflectorServerOptionsProvider()}, - {new JavaOptionsProvider()}, {new JaxRSServerOptionsProvider()}, + { + new JavaOptionsProvider(), + new JavaOptionsProvider(ImmutableMap.of(CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2) + ), + new JavaOptionsProvider(ImmutableMap.of( + CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2, + JavaClientCodegen.USE_RX_JAVA, "true") + ) + }, + {new JaxRSServerOptionsProvider()}, {new NodeJSServerOptionsProvider()}, {new ObjcClientOptionsProvider()}, {new PerlClientOptionsProvider()}, {new PhpClientOptionsProvider()}, {new PythonClientOptionsProvider()}, {new Qt5CPPOptionsProvider()}, diff --git a/pom.xml b/pom.xml index ce92a4dd8e1..c9bee1d02a0 100644 --- a/pom.xml +++ b/pom.xml @@ -342,6 +342,18 @@ samples/client/petstore/java/retrofit2 + + java-client-retrofit2-rx + + + env + java + + + + samples/client/petstore/java/retrofit2rx + + java-client-feign @@ -443,6 +455,7 @@ samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit samples/client/petstore/java/retrofit2 + samples/client/petstore/java/retrofit2rx samples/client/petstore/javascript samples/client/petstore/scala samples/server/petstore/spring-mvc diff --git a/samples/client/petstore/java/retrofit2rx/README.md b/samples/client/petstore/java/retrofit2rx/README.md new file mode 100644 index 00000000000..7673712f5a5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/README.md @@ -0,0 +1,43 @@ +# swagger-petstore-retrofit2-rx + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-petstore-retrofit2-rx + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/retrofit2rx/build.gradle b/samples/client/petstore/java/retrofit2rx/build.gradle new file mode 100644 index 00000000000..08c81cd21ea --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/build.gradle @@ -0,0 +1,114 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-retrofit2-rx' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + okhttp_version = "2.5.0" + oltu_version = "1.0.0" + retrofit_version = "2.0.0-beta2" + gson_version = "2.4" + swagger_annotations_version = "1.5.0" + junit_version = "4.12" + rx_java_version = "1.0.15" + +} + +dependencies { + compile "com.squareup.okhttp:okhttp:$okhttp_version" + + compile "com.squareup.retrofit:retrofit:$retrofit_version" + compile "com.squareup.retrofit:converter-gson:$retrofit_version" + compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version" + compile "io.reactivex:rxjava:$rx_java_version" + + + compile "com.google.code.gson:gson:$gson_version" + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/retrofit2rx/gradle.properties b/samples/client/petstore/java/retrofit2rx/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/hello.txt b/samples/client/petstore/java/retrofit2rx/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml new file mode 100644 index 00000000000..ab018917b14 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -0,0 +1,173 @@ + + 4.0.0 + io.swagger + swagger-petstore-retrofit2-rx + jar + swagger-petstore-retrofit2-rx + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.7 + + 1.7 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.retrofit + retrofit + ${retrofit-version} + + + com.squareup.retrofit + converter-gson + ${retrofit-version} + + + com.google.code.gson + gson + ${gson-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + + io.reactivex + rxjava + ${rxjava-version} + + + com.squareup.retrofit + adapter-rxjava + ${retrofit-version} + + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.0.0-beta2 + 1.0.15 + 2.5.0 + 2.4 + 1.0.0 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/retrofit2rx/settings.gradle b/samples/client/petstore/java/retrofit2rx/settings.gradle new file mode 100644 index 00000000000..6c54013a532 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-retrofit2-rx" \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/AndroidManifest.xml b/samples/client/petstore/java/retrofit2rx/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + 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 new file mode 100644 index 00000000000..869681a2ce5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,345 @@ +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 retrofit.Converter; +import retrofit.Retrofit; +import retrofit.GsonConverterFactory; +import retrofit.RxJavaCallAdapterFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.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; + + +public class ApiClient { + + private Map apiAuthorizations; + private OkHttpClient okClient; + private Retrofit.Builder adapterBuilder; + + public ApiClient() { + apiAuthorizations = new LinkedHashMap(); + createDefaultAdapter(); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { + Interceptor auth; + if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth); + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + + public void createDefaultAdapter() { + Gson gson = new GsonBuilder() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .create(); + + okClient = new OkHttpClient(); + + String baseUrl = "http://petstore.swagger.io/v2"; + if(!baseUrl.endsWith("/")) + baseUrl = baseUrl + "/"; + + adapterBuilder = new Retrofit + .Builder() + .baseUrl(baseUrl) + .client(okClient) + .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) + .addConverterFactory(GsonCustomConverterFactory.create(gson)); + } + + public S createService(Class serviceClass) { + return adapterBuilder.build().create(serviceClass); + + } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + private void setApiKey(String apiKey) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return; + } + } + } + + /** + * Helper method to configure the username/password for basic auth or password oauth + * @param username + * @param password + */ + private void setCredentials(String username, String password) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + */ + public void setAccessToken(String accessToken) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, Interceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + okClient.interceptors().add(authorization); + } + + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public Retrofit.Builder getAdapterBuilder() { + return adapterBuilder; + } + + public void setAdapterBuilder(Retrofit.Builder adapterBuilder) { + this.adapterBuilder = adapterBuilder; + } + + public OkHttpClient getOkClient() { + return okClient; + } + + public void addAuthsToOkClient(OkHttpClient okClient) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + okClient.interceptors().add(apiAuthorization); + } + } + + /** + * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the Retrofit + * @param okClient + */ + public void configureFromOkclient(OkHttpClient okClient) { + OkHttpClient clone = okClient.clone(); + addAuthsToOkClient(clone); + adapterBuilder.client(clone); + } +} + +/** + * This wrapper is to take care of this case: + * when the deserialization fails due to JsonParseException and the + * expected type is String, then just return the body string. + */ +class GsonResponseBodyConverterToString implements Converter { + private final Gson gson; + private final Type type; + + GsonResponseBodyConverterToString(Gson gson, Type type) { + this.gson = gson; + this.type = type; + } + + @Override public T convert(ResponseBody value) throws IOException { + String returned = value.string(); + try { + return gson.fromJson(returned, type); + } + catch (JsonParseException e) { + return (T) returned; + } + } +} + +class GsonCustomConverterFactory extends Converter.Factory +{ + public static GsonCustomConverterFactory create(Gson gson) { + return new GsonCustomConverterFactory(gson); + } + + private final Gson gson; + private final GsonConverterFactory gsonConverterFactory; + + private GsonCustomConverterFactory(Gson gson) { + if (gson == null) throw new NullPointerException("gson == null"); + this.gson = gson; + this.gsonConverterFactory = GsonConverterFactory.create(gson); + } + + @Override + public Converter fromResponseBody(Type type, Annotation[] annotations) { + if(type.equals(String.class)) + return new GsonResponseBodyConverterToString(gson, type); + else + return gsonConverterFactory.fromResponseBody(type, annotations); + } + + @Override + public Converter toRequestBody(Type type, Annotation[] annotations) { + return gsonConverterFactory.toRequestBody(type, annotations); + } +} + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 00000000000..c3cf5257514 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package io.swagger.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..4a8e24d7cb7 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,42 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-22T16:57:22.418+01:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..7caa426e18d --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,155 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import rx.Observable; + +import retrofit.http.*; + +import com.squareup.okhttp.RequestBody; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.util.*; + +public interface PetApi { + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return Call + */ + + @PUT("pet") + Observable updatePet( + @Body Pet body + ); + + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return Call + */ + + @POST("pet") + Observable addPet( + @Body Pet body + ); + + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @return Call> + */ + + @GET("pet/findByStatus") + Observable> findPetsByStatus( + @Query("status") List status + ); + + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return Call> + */ + + @GET("pet/findByTags") + Observable> findPetsByTags( + @Query("tags") List tags + ); + + + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Call + */ + + @GET("pet/{petId}") + Observable getPetById( + @Path("petId") Long petId + ); + + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return Call + */ + + @FormUrlEncoded + @POST("pet/{petId}") + Observable updatePetWithForm( + @Path("petId") String petId, @Field("name") String name, @Field("status") String status + ); + + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return Call + */ + + @DELETE("pet/{petId}") + Observable deletePet( + @Path("petId") Long petId, @Header("api_key") String apiKey + ); + + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return Call + */ + + @Multipart + @POST("pet/{petId}/uploadImage") + Observable uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + ); + + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Call + */ + + @GET("pet/{petId}?testing_byte_array=true") + Observable getPetByIdWithByteArray( + @Path("petId") Long petId + ); + + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @return Call + */ + + @POST("pet?testing_byte_array=true") + Observable addPetUsingByteArray( + @Body byte[] body + ); + + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..20e4dbb57fa --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,68 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import rx.Observable; + +import retrofit.http.*; + +import com.squareup.okhttp.RequestBody; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.util.*; + +public interface StoreApi { + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Call> + */ + + @GET("store/inventory") + Observable> getInventory(); + + + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Call + */ + + @POST("store/order") + Observable placeOrder( + @Body Order body + ); + + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Call + */ + + @GET("store/order/{orderId}") + Observable getOrderById( + @Path("orderId") String orderId + ); + + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return Call + */ + + @DELETE("store/order/{orderId}") + Observable deleteOrder( + @Path("orderId") String orderId + ); + + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..ec6fd019252 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,122 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import rx.Observable; + +import retrofit.http.*; + +import com.squareup.okhttp.RequestBody; + +import io.swagger.client.model.User; +import java.util.*; + +import java.util.*; + +public interface UserApi { + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return Call + */ + + @POST("user") + Observable createUser( + @Body User body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithArray") + Observable createUsersWithArrayInput( + @Body List body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithList") + Observable createUsersWithListInput( + @Body List body + ); + + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return Call + */ + + @GET("user/login") + Observable loginUser( + @Query("username") String username, @Query("password") String password + ); + + + /** + * Logs out current logged in user session + * + * @return Call + */ + + @GET("user/logout") + Observable logoutUser(); + + + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return Call + */ + + @GET("user/{username}") + Observable getUserByName( + @Path("username") String username + ); + + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return Call + */ + + @PUT("user/{username}") + Observable updateUser( + @Path("username") String username, @Body User body + ); + + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return Call + */ + + @DELETE("user/{username}") + Observable deleteUser( + @Path("username") String username + ); + + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..59d01238796 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,68 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class ApiKeyAuth implements Interceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public Response intercept(Chain chain) throws IOException { + String paramValue; + Request request = chain.request(); + + if (location == "query") { + String newQuery = request.uri().getQuery(); + paramValue = paramName + "=" + apiKey; + if (newQuery == null) { + newQuery = paramValue; + } else { + newQuery += "&" + paramValue; + } + + URI newUri; + try { + newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), + request.uri().getPath(), newQuery, request.uri().getFragment()); + } catch (URISyntaxException e) { + throw new IOException(e); + } + + request = request.newBuilder().url(newUri.toURL()).build(); + } else if (location == "header") { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build(); + } + return chain.proceed(request); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..cb7c617767b --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,49 @@ +package io.swagger.client.auth; + +import java.io.IOException; + +import com.squareup.okhttp.Credentials; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class HttpBasicAuth implements Interceptor { + + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") == null) { + String credentials = Credentials.basic(username, password); + request = request.newBuilder() + .addHeader("Authorization", credentials) + .build(); + } + return chain.proceed(request); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..80614f0f56a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,161 @@ +package io.swagger.client.auth; + +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; + +import java.io.IOException; +import java.util.Map; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.Response; + +public class OAuth implements Interceptor { + + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private OAuthClient oauthClient; + + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + + private AccessTokenListener accessTokenListener; + + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(TokenRequestBuilder requestBuilder ) { + this(new OkHttpClient(), requestBuilder); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) + throws IOException { + + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // If first time, get the token + OAuthClientRequest oAuthRequest; + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response.code() == HTTP_UNAUTHORIZED ) { + updateAccessToken(requestAccessToken); + return intercept( chain ); + } + return response; + } + + public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } catch (OAuthSystemException e) { + throw new IOException(e); + } catch (OAuthProblemException e) { + throw new IOException(e); + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..597ec99b48b --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java new file mode 100644 index 00000000000..c872901ba24 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java @@ -0,0 +1,69 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + + +public class OAuthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..d0908afd9e1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,85 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Category { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..59c5238b626 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,174 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Order { + + @SerializedName("id") + private Long id = null; + + @SerializedName("petId") + private Long petId = null; + + @SerializedName("quantity") + private Integer quantity = null; + + @SerializedName("shipDate") + private Date shipDate = null; + + +public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + @SerializedName("complete") + private Boolean complete = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..1f9462ddc3a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,176 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.*; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Pet { + + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Category category = null; + + @SerializedName("name") + private String name = null; + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("tags") + private List tags = new ArrayList(); + + +public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..a4ca1074ca1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,85 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Tag { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..072f510081a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,182 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class User { + + @SerializedName("id") + private Long id = null; + + @SerializedName("username") + private String username = null; + + @SerializedName("firstName") + private String firstName = null; + + @SerializedName("lastName") + private String lastName = null; + + @SerializedName("email") + private String email = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("phone") + private String phone = null; + + @SerializedName("userStatus") + private Integer userStatus = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 00000000000..d8450642f6f --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,254 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(PetApi.class); + } + + @Test + public void testCreateAndGetPet() throws Exception { + final Pet pet = createRandomPet(); + api.addPet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); + + } + + @Test + public void testUpdatePet() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); + + } + + @Test + public void testFindPetsByStatus() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByStatus(Arrays.asList(new String[]{"available"})).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + }); + + } + }); + + } + + @Test + public void testFindPetsByTags() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByTags(Arrays.asList(new String[]{"friendly"})).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + }); + + } + }); + + } + + @Test + public void testUpdatePetWithForm() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(final Pet fetched) { + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null) + .subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet updated) { + assertEquals(updated.getName(), "furt"); + } + }); + + } + }); + } + }); + + + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + + api.deletePet(fetched.getId(), null).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet deletedPet) { + fail("Should not have found deleted pet."); + } + + @Override + public void onError(Throwable e) { + // expected, because the pet has been deleted. + } + }); + } + }); + } + + @Test + public void testUploadFile() throws Exception { + File file = File.createTempFile("test", "hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + + writer.write("Hello world!"); + writer.close(); + + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + + RequestBody body = RequestBody.create(MediaType.parse("text/plain"), file); + api.uploadFile(pet.getId(), "a test file", body).subscribe(new SkeletonSubscriber() { + @Override + public void onError(Throwable e) { + // this also yields a 400 for other tests, so I guess it's okay... + } + }); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/SkeletonSubscriber.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/SkeletonSubscriber.java new file mode 100644 index 00000000000..5d34a1e5d5d --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/SkeletonSubscriber.java @@ -0,0 +1,30 @@ +package io.swagger.petstore.test; + +import junit.framework.TestFailure; +import rx.Subscriber; + +/** + * Skeleton subscriber for tests that will fail when onError() is called unexpectedly. + */ +public abstract class SkeletonSubscriber extends Subscriber { + + public static SkeletonSubscriber failTestOnError() { + return new SkeletonSubscriber() { + }; + } + + @Override + public void onCompleted() { + // space for rent + } + + @Override + public void onNext(T t) { + // space for rent + } + + @Override + public void onError(Throwable e) { + throw new RuntimeException("Subscriber onError() called with unhandled exception!", e); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 00000000000..d9e2c641398 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,88 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; + +import retrofit.Response; + +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(StoreApi.class); + } + + @Test + public void testGetInventory() throws Exception { + api.getInventory().subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(Map inventory) { + assertTrue(inventory.keySet().size() > 0); + } + }); + + } + + @Test + public void testPlaceOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(String.valueOf(order.getId())).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + }); + } + + @Test + public void testDeleteOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getOrderById(String.valueOf(order.getId())).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(fetched.getId(), order.getId()); + } + }); + + + api.deleteOrder(String.valueOf(order.getId())).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(String.valueOf(order.getId())) + .subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order order) { + throw new RuntimeException("Should not have found deleted order."); + } + + @Override + public void onError(Throwable e) { + // should not find deleted order. + } + } + ); + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 00000000000..59e238b457b --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,108 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + + +import java.util.Arrays; + +import org.junit.*; + +import static org.junit.Assert.*; + +/** + * NOTE: This serves as a sample and test case for the generator, which is why this is java-7 code. + * Much looks much nicer with no anonymous classes. + */ +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + final User user = createUser(); + + api.createUser(user).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getUserByName(user.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user.getId(), fetched.getId()); + } + }); + } + }); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); + } + + @Test + public void testCreateUsersWithList() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + api.loginUser(user.getUsername(), user.getPassword()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(String token) { + assertTrue(token.startsWith("logged in user session:")); + } + }); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} \ No newline at end of file