From 730202deb280d79cb8dc11fe1a57dc91f8b2894a Mon Sep 17 00:00:00 2001 From: rostskadat Date: Sun, 8 Nov 2015 17:24:22 +0100 Subject: [PATCH 01/13] Added @RequestBody annotation in order for the generated code to properly create API Model object. @RequestBody Annotation Ref: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody --- .../src/main/resources/JavaSpringMVC/bodyParams.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache index 86546afb9ca..f1137ba7073 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file From dad28dcba01738b426ead012c140d1682df7afea Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 9 Nov 2015 16:10:55 +0100 Subject: [PATCH 02/13] don't retry if the access token doesn't change This is to avoid an infinite loop if the server always gives an invalid token --- .../libraries/retrofit/auth/OAuth.mustache | 75 +++++++++++-------- 1 file changed, 45 insertions(+), 30 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache index 68ee918601e..647ff141329 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache @@ -1,6 +1,7 @@ package {{invokerPackage}}.auth; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; import java.io.IOException; import java.util.Map; @@ -85,42 +86,55 @@ public class OAuth implements Interceptor { 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); + if (getAccessToken() != 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 != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { + if (updateAccessToken(requestAccessToken)) { + return intercept( chain ); + } + } + return response; + } else { + return chain.proceed(chain.request()); } - - 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 { + /* + * Returns true if the access token has been updated + */ + public synchronized boolean 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()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + return getAccessToken().equals(requestAccessToken); + } else { + return false; } } catch (OAuthSystemException e) { throw new IOException(e); @@ -128,6 +142,7 @@ public class OAuth implements Interceptor { throw new IOException(e); } } + return true; } public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { From d9f7944102509ce06a9e2306d95fe34de58bd0dd Mon Sep 17 00:00:00 2001 From: crissdev Date: Fri, 6 Nov 2015 19:02:25 +0200 Subject: [PATCH 03/13] typescript: mark optional model properties --- .../resources/TypeScript-Angular/model.mustache | 2 +- .../typescript-angular/API/Client/Category.ts | 4 ++-- .../typescript-angular/API/Client/Order.ts | 12 ++++++------ .../typescript-angular/API/Client/Pet.ts | 8 ++++---- .../typescript-angular/API/Client/Tag.ts | 4 ++-- .../typescript-angular/API/Client/User.ts | 16 ++++++++-------- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache index 4096e078518..f4cfe923baa 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache @@ -18,7 +18,7 @@ namespace {{package}} { * {{{description}}} */ {{/description}} - {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } diff --git a/samples/client/petstore/typescript-angular/API/Client/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts index ad34870b31a..a802fe4ebdf 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -5,9 +5,9 @@ namespace API.Client { export interface Category { - id: number; + id?: number; - name: string; + name?: string; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts index dfffcd3d828..1dd84e6d0ad 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -5,20 +5,20 @@ namespace API.Client { export interface Order { - id: number; + id?: number; - petId: number; + petId?: number; - quantity: number; + quantity?: number; - shipDate: Date; + shipDate?: Date; /** * Order Status */ - status: Order.StatusEnum; + status?: Order.StatusEnum; - complete: boolean; + complete?: boolean; } export namespace Order { diff --git a/samples/client/petstore/typescript-angular/API/Client/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts index fa86c457fcf..60431f69c83 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -5,20 +5,20 @@ namespace API.Client { export interface Pet { - id: number; + id?: number; - category: Category; + category?: Category; name: string; photoUrls: Array; - tags: Array; + tags?: Array; /** * pet status in the store */ - status: Pet.StatusEnum; + status?: Pet.StatusEnum; } export namespace Pet { diff --git a/samples/client/petstore/typescript-angular/API/Client/Tag.ts b/samples/client/petstore/typescript-angular/API/Client/Tag.ts index d206559a0ef..1c0284cce48 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -5,9 +5,9 @@ namespace API.Client { export interface Tag { - id: number; + id?: number; - name: string; + name?: string; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts index e60f84bb6c6..7c2b0b78b0c 100644 --- a/samples/client/petstore/typescript-angular/API/Client/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -5,24 +5,24 @@ namespace API.Client { export interface User { - id: number; + id?: number; - username: string; + username?: string; - firstName: string; + firstName?: string; - lastName: string; + lastName?: string; - email: string; + email?: string; - password: string; + password?: string; - phone: string; + phone?: string; /** * User Status */ - userStatus: number; + userStatus?: number; } } From 3a7204d66cbf4d89c56e4446e5cce79d08da1fa0 Mon Sep 17 00:00:00 2001 From: Emiliano Bonassi Date: Tue, 10 Nov 2015 03:20:49 +0100 Subject: [PATCH 04/13] Add support to Retrofit2 --- README.md | 11 +- bin/all-petstore.sh | 1 + bin/java-petstore-retrofit2.json | 4 + bin/java-petstore-retrofit2.sh | 31 ++ .../codegen/languages/JavaClientCodegen.java | 9 +- .../libraries/retrofit2/ApiClient.mustache | 343 ++++++++++++++++++ .../retrofit2/CollectionFormats.mustache | 95 +++++ .../Java/libraries/retrofit2/api.mustache | 34 ++ .../retrofit2/auth/ApiKeyAuth.mustache | 68 ++++ .../retrofit2/auth/HttpBasicAuth.mustache | 49 +++ .../libraries/retrofit2/auth/OAuth.mustache | 161 ++++++++ .../retrofit2/auth/OAuthOkHttpClient.mustache | 69 ++++ .../libraries/retrofit2/bodyParams.mustache | 1 + .../libraries/retrofit2/build.gradle.mustache | 106 ++++++ .../libraries/retrofit2/formParams.mustache | 1 + .../libraries/retrofit2/headerParams.mustache | 1 + .../Java/libraries/retrofit2/model.mustache | 58 +++ .../libraries/retrofit2/pathParams.mustache | 1 + .../Java/libraries/retrofit2/pom.mustache | 158 ++++++++ .../libraries/retrofit2/queryParams.mustache | 1 + .../.settings/org.eclipse.jdt.core.prefs | 12 + .../.settings/org.eclipse.m2e.core.prefs | 4 + .../petstore/java/retrofit2/build.gradle | 106 ++++++ .../petstore/java/retrofit2/gradle.properties | 2 + .../client/petstore/java/retrofit2/pom.xml | 158 ++++++++ .../petstore/java/retrofit2/settings.gradle | 1 + .../java/io/swagger/client/ApiClient.java | 342 +++++++++++++++++ .../io/swagger/client/CollectionFormats.java | 95 +++++ .../java/io/swagger/client/StringUtil.java | 51 +++ .../java/io/swagger/client/api/PetApi.java | 127 +++++++ .../java/io/swagger/client/api/StoreApi.java | 66 ++++ .../java/io/swagger/client/api/UserApi.java | 120 ++++++ .../io/swagger/client/auth/ApiKeyAuth.java | 68 ++++ .../io/swagger/client/auth/HttpBasicAuth.java | 49 +++ .../java/io/swagger/client/auth/OAuth.java | 161 ++++++++ .../io/swagger/client/auth/OAuthFlow.java | 5 + .../client/auth/OAuthOkHttpClient.java | 69 ++++ .../io/swagger/client/model/Category.java | 57 +++ .../java/io/swagger/client/model/Order.java | 142 ++++++++ .../java/io/swagger/client/model/Pet.java | 144 ++++++++ .../java/io/swagger/client/model/Tag.java | 57 +++ .../java/io/swagger/client/model/User.java | 148 ++++++++ .../io/swagger/petstore/test/PetApiTest.java | 160 ++++++++ .../swagger/petstore/test/StoreApiTest.java | 64 ++++ .../io/swagger/petstore/test/UserApiTest.java | 84 +++++ 45 files changed, 3486 insertions(+), 8 deletions(-) create mode 100644 bin/java-petstore-retrofit2.json create mode 100755 bin/java-petstore-retrofit2.sh create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/CollectionFormats.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/HttpBasicAuth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache create mode 100644 samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs create mode 100644 samples/client/petstore/java/retrofit2/.settings/org.eclipse.m2e.core.prefs create mode 100644 samples/client/petstore/java/retrofit2/build.gradle create mode 100644 samples/client/petstore/java/retrofit2/gradle.properties create mode 100644 samples/client/petstore/java/retrofit2/pom.xml create mode 100644 samples/client/petstore/java/retrofit2/settings.gradle create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java create mode 100644 samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java create mode 100644 samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java create mode 100644 samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java diff --git a/README.md b/README.md index 664b8e20ef1..28d068c8404 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ ## Overview This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. -Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. +Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. # Table of contents @@ -63,7 +63,7 @@ You need the following installed and available in your $PATH: * [Java 7](http://java.oracle.com) * [Apache maven 3.0.3 or greater](http://maven.apache.org/) - + #### OS X Users Don't forget to install Java 7. You probably have 1.6 or 1.8. @@ -173,10 +173,10 @@ OPTIONS -v, --verbose verbose mode - + -s , --skip-overwrite - specifies if the existing files should be overwritten during - the generation + specifies if the existing files should be overwritten during + the generation ``` You can then compile and run the client, as well as unit tests against it: @@ -351,6 +351,7 @@ CONFIG OPTIONS jersey2 - HTTP client: Jersey client 2.6 okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) + retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) ``` Your config file for java can look like diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 2f9d4c0c0ff..dc2b4116070 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -27,6 +27,7 @@ cd $APP_DIR ./bin/java-petstore-jersey2.sh ./bin/java-petstore-okhttp-gson.sh ./bin/java-petstore-retrofit.sh ++./bin/java-petstore-retrofit2.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/bin/java-petstore-retrofit2.json b/bin/java-petstore-retrofit2.json new file mode 100644 index 00000000000..4829fd6dd4b --- /dev/null +++ b/bin/java-petstore-retrofit2.json @@ -0,0 +1,4 @@ +{ + "library": "retrofit2", + "artifactId": "swagger-petstore-retrofit2" +} diff --git a/bin/java-petstore-retrofit2.sh b/bin/java-petstore-retrofit2.sh new file mode 100755 index 00000000000..fbd1f9779e4 --- /dev/null +++ b/bin/java-petstore-retrofit2.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-retrofit2.json -o samples/client/petstore/java/retrofit2" + +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 a54ec4e038a..7702feecbc6 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 @@ -98,6 +98,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { 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)"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); library.setEnum(supportedLibraries); @@ -214,7 +215,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); - if (!"retrofit".equals(getLibrary())) { + if (!("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); @@ -228,7 +229,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - } else if ("retrofit".equals(getLibrary())) { + } else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); } else { @@ -512,7 +513,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } public Map postProcessOperations(Map objs) { - if("retrofit".equals(getLibrary())) { + if("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { Map operations = (Map) objs.get("operations"); if (operations != null) { List ops = (List) operations.get("operation"); @@ -528,6 +529,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { if (operation.returnType == null) { operation.returnType = "Void"; } + if ("retrofit2".equals(getLibrary()) && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) + operation.path = operation.path.substring(1); } } } 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 new file mode 100644 index 00000000000..f9f7d77f470 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -0,0 +1,343 @@ +package {{invokerPackage}}; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; + +import retrofit.Converter; +import retrofit.Retrofit; +import retrofit.GsonConverterFactory; + +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 {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; +import {{invokerPackage}}.auth.OAuth.AccessTokenListener; +import {{invokerPackage}}.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) { {{#hasAuthMethods}} + Interceptor auth; + {{#authMethods}}if (authName == "{{name}}") { {{#isBasic}} + auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} + auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} + auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} + } else {{/authMethods}}{ + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}} + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}} + } + } + + /** + * 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 = "{{basePath}}"; + if(!baseUrl.endsWith("/")) + baseUrl = baseUrl + "/"; + + adapterBuilder = new Retrofit + .Builder() + .baseUrl(baseUrl) + .client(okClient) + .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/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/CollectionFormats.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/CollectionFormats.mustache new file mode 100644 index 00000000000..a549ea59d1c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/CollectionFormats.mustache @@ -0,0 +1,95 @@ +package {{invokerPackage}}; + +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/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache new file mode 100644 index 00000000000..d0205c3d0b1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -0,0 +1,34 @@ +package {{package}}; + +import {{invokerPackage}}.CollectionFormats.*; + +import retrofit.Call; +import retrofit.http.*; +import com.squareup.okhttp.RequestBody; + +{{#imports}}import {{import}}; +{{/imports}} + +{{^fullJavaUtil}} +import java.util.*; +{{/fullJavaUtil}} + +{{#operations}} +public interface {{classname}} { + {{#operation}} + /** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{paramName}} {{description}} +{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> + */ + {{#formParams}}{{#-first}} + {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + @{{httpMethod}}("{{path}}") + Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{nickname}}({{^allParams}});{{/allParams}} + {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} + );{{/hasMore}}{{/allParams}} + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache new file mode 100644 index 00000000000..fec45262e93 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache @@ -0,0 +1,68 @@ +package {{invokerPackage}}.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/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/HttpBasicAuth.mustache new file mode 100644 index 00000000000..394592f64d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/HttpBasicAuth.mustache @@ -0,0 +1,49 @@ +package {{invokerPackage}}.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/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache new file mode 100644 index 00000000000..68ee918601e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache @@ -0,0 +1,161 @@ +package {{invokerPackage}}.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/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache new file mode 100644 index 00000000000..ea195f7df04 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache @@ -0,0 +1,69 @@ +package {{invokerPackage}}.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/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache new file mode 100644 index 00000000000..f8788583db5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file 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 new file mode 100644 index 00000000000..b1efe3911a8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -0,0 +1,106 @@ +group = '{{groupId}}' +version = '{{artifactVersion}}' + +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 = '{{artifactId}}' + } + } + + 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" +} + +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' + 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/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache new file mode 100644 index 00000000000..8d9208978b5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}\"") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache new file mode 100644 index 00000000000..29206e1546b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache new file mode 100644 index 00000000000..0987aa68f34 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache @@ -0,0 +1,58 @@ +package {{package}}; + +import {{invokerPackage}}.StringUtil; +{{#imports}}import {{import}}; +{{/imports}} + +import com.google.gson.annotations.SerializedName; + +{{#serializableModel}} +import java.io.Serializable;{{/serializableModel}} + +import io.swagger.annotations.*; + +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}} + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache new file mode 100644 index 00000000000..8a8bdc74c88 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file 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 new file mode 100644 index 00000000000..a155d04ef88 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -0,0 +1,158 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 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.6 + 1.6 + + + + + + + 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} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.0.0-beta2 + 2.5.0 + 2.4 + 1.0.0 + 1.0.0 + 4.12 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache new file mode 100644 index 00000000000..3c5b1bb7e69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs b/samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000000..62492222ad2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/samples/client/petstore/java/retrofit2/.settings/org.eclipse.m2e.core.prefs b/samples/client/petstore/java/retrofit2/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 00000000000..f897a7f1cb2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle new file mode 100644 index 00000000000..0deeeea2e37 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -0,0 +1,106 @@ +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' + } + } + + 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" +} + +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' + 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/retrofit2/gradle.properties b/samples/client/petstore/java/retrofit2/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml new file mode 100644 index 00000000000..109cbc0d95c --- /dev/null +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -0,0 +1,158 @@ + + 4.0.0 + io.swagger + swagger-petstore-retrofit2 + jar + swagger-petstore-retrofit2 + 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.6 + 1.6 + + + + + + + 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} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.0.0-beta2 + 2.5.0 + 2.4 + 1.0.0 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/retrofit2/settings.gradle b/samples/client/petstore/java/retrofit2/settings.gradle new file mode 100644 index 00000000000..c42bfff90c4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-retrofit2" \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..a58542bf3a9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,342 @@ +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 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) + .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/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 00000000000..c3cf5257514 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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/retrofit2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..33dc56510e3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-10T03:03:11.515+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(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..a55cf74da76 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,127 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import retrofit.Call; +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") + Call 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") + Call 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") + Call> 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") + Call> 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}") + Call 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}") + Call 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}") + Call 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") + Call uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + ); + + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..2fca1e02e39 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,66 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import retrofit.Call; +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") + Call> getInventory(); + + + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Call + */ + + @POST("store/order") + Call 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}") + Call 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}") + Call deleteOrder( + @Path("orderId") String orderId + ); + + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..928bd623020 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,120 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import retrofit.Call; +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") + Call createUser( + @Body User body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithArray") + Call createUsersWithArrayInput( + @Body List body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithList") + Call 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") + Call loginUser( + @Query("username") String username, @Query("password") String password + ); + + + /** + * Logs out current logged in user session + * + * @return Call + */ + + @GET("user/logout") + Call logoutUser(); + + + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return Call + */ + + @GET("user/{username}") + Call 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}") + Call 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}") + Call deleteUser( + @Path("username") String username + ); + + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..59d01238796 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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/retrofit2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..cb7c617767b --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..80614f0f56a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..597ec99b48b --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java new file mode 100644 index 00000000000..c872901ba24 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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/retrofit2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..0a7023ac7a5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@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 String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..df8e77b6fb3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,142 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import java.util.Date; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@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 String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..9ab5457e26a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,144 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import io.swagger.client.model.Category; +import java.util.*; +import io.swagger.client.model.Tag; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@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 String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..9935b744f2d --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@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 String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..cba6abef8dd --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,148 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@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 String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 00000000000..8522c4f30ad --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,160 @@ +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 retrofit.Response; + +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 { + Pet pet = createRandomPet(); + Response rp2 = api.addPet(pet).execute(); + + Response rp = api.getPetById(pet.getId()).execute(); + Pet fetched = rp.body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet).execute(); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})).execute().body(); + 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 { + 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).execute(); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})).execute().body(); + 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 { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null).execute(); + Pet updated = api.getPetById(fetched.getId()).execute().body(); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + api.deletePet(fetched.getId(), null).execute(); + + assertFalse(api.getPetById(fetched.getId()).execute().isSuccess()); + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", RequestBody.create(MediaType.parse("text/plain"), file)).execute(); + } + + 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/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 00000000000..786b0708702 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,64 @@ +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 { + Map inventory = api.getInventory().execute().body(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order).execute(); + + Order fetched = api.getOrderById(String.valueOf(order.getId())).execute().body(); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + Response aa = api.placeOrder(order).execute(); + + Order fetched = api.getOrderById(String.valueOf(order.getId())).execute().body(); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())).execute(); + + api.getOrderById(String.valueOf(order.getId())).execute(); + //also in retrofit 1 should return an error but don't, check server api impl. + } + + 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/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 00000000000..d496144c9f2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,84 @@ +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.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user).execute(); + + User fetched = api.getUserByName(user.getUsername()).execute().body(); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user).execute(); + + String token = api.loginUser(user.getUsername(), user.getPassword()).execute().body(); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser().execute(); + } + + 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 From aaafd0632cc90d4ff348b34a271c4f9a788dbb3b Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 10 Nov 2015 12:04:29 +0800 Subject: [PATCH 05/13] Fix error with array of enum in Java client ref: https://github.com/swagger-api/swagger-codegen/pull/1457#issuecomment-155185530 --- .../io/swagger/codegen/languages/JavaClientCodegen.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) 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 4e6f1b9910a..31b963cf142 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 @@ -496,7 +496,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } allowableValues.put("enumVars", enumVars); // handle default value for enum, e.g. available => StatusEnum.AVAILABLE - if (var.defaultValue != null && !"null".equals(var.defaultValue)) { + if (var.defaultValue != null) { String enumName = null; for (Map enumVar : enumVars) { if (var.defaultValue.equals(enumVar.get("value"))) { @@ -504,10 +504,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { break; } } - if (enumName == null) { - throw new RuntimeException("default value of property \"" + var.baseName + "\" is not in allowed values: " + var.defaultValue); + if (enumName != null) { + var.defaultValue = var.datatypeWithEnum + "." + enumName; } - var.defaultValue = var.datatypeWithEnum + "." + enumName; } } } From c07e30b8cf487282680f33693fc77cda917272ab Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 10 Nov 2015 13:22:06 +0800 Subject: [PATCH 06/13] Update testCreateUser to avoid occasional failures --- .../src/test/java/io/swagger/petstore/test/UserApiTest.java | 2 +- .../src/test/java/io/swagger/petstore/test/UserApiTest.java | 2 +- .../src/test/java/io/swagger/petstore/test/UserApiTest.java | 2 +- .../src/test/java/io/swagger/petstore/test/UserApiTest.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java index 26e46bfa602..a3f257f568b 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -73,7 +73,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java index 26e46bfa602..a3f257f568b 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -73,7 +73,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java index 26e46bfa602..a3f257f568b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -73,7 +73,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java index 373218465f0..f99d7f513cc 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -71,7 +71,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); From 47f4396fb7bd24ed36cab8ac16ca9d59736b0e49 Mon Sep 17 00:00:00 2001 From: Emiliano Bonassi Date: Tue, 10 Nov 2015 12:30:13 +0100 Subject: [PATCH 07/13] - fix source/target java version to 1.6 - add test profile for CI --- .../Java/libraries/retrofit2/ApiClient.mustache | 2 +- pom.xml | 12 ++++++++++++ .../retrofit2/.settings/org.eclipse.jdt.core.prefs | 12 ------------ .../src/main/java/io/swagger/client/ApiClient.java | 2 +- .../src/main/java/io/swagger/client/StringUtil.java | 2 +- 5 files changed, 15 insertions(+), 15 deletions(-) delete mode 100644 samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs 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 f9f7d77f470..56e83f7d915 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 @@ -330,7 +330,7 @@ class GsonCustomConverterFactory extends Converter.Factory @Override public Converter fromResponseBody(Type type, Annotation[] annotations) { if(type.equals(String.class)) - return new GsonResponseBodyConverterToString<>(gson, type); + return new GsonResponseBodyConverterToString(gson, type); else return gsonConverterFactory.fromResponseBody(type, annotations); } diff --git a/pom.xml b/pom.xml index 94d4741f185..31a34489f15 100644 --- a/pom.xml +++ b/pom.xml @@ -353,6 +353,18 @@ samples/client/petstore/java/retrofit + + java-client-retrofit2 + + + env + java + + + + samples/client/petstore/java/retrofit2 + + scala-client diff --git a/samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs b/samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 62492222ad2..00000000000 --- a/samples/client/petstore/java/retrofit2/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,12 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.7 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.7 diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index a58542bf3a9..2138c3a172b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -329,7 +329,7 @@ class GsonCustomConverterFactory extends Converter.Factory @Override public Converter fromResponseBody(Type type, Annotation[] annotations) { if(type.equals(String.class)) - return new GsonResponseBodyConverterToString<>(gson, type); + return new GsonResponseBodyConverterToString(gson, type); else return gsonConverterFactory.fromResponseBody(type, annotations); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java index 33dc56510e3..5125ae3e55b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-10T03:03:11.515+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-10T12:25:26.227+01:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). From e104803781270b91c964a2cc17dbaeb1e11e35ea Mon Sep 17 00:00:00 2001 From: Emiliano Bonassi Date: Tue, 10 Nov 2015 12:39:30 +0100 Subject: [PATCH 08/13] fix pom.xml added retrofit2 as a module --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 31a34489f15..e6d319c42d7 100644 --- a/pom.xml +++ b/pom.xml @@ -439,6 +439,7 @@ samples/client/petstore/java/jersey2 samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit + samples/client/petstore/java/retrofit2 samples/client/petstore/scala samples/server/petstore/spring-mvc From cbd1b98bf53928e6c9979a4536ddcaa6260ef522 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 11 Nov 2015 16:35:17 +0800 Subject: [PATCH 09/13] better scala test (UserApi) --- .../scala/src/test/scala/UserApiTest.scala | 64 +++++++++---------- 1 file changed, 31 insertions(+), 33 deletions(-) diff --git a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala index ea0fda03d9a..f965510344f 100644 --- a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala @@ -11,21 +11,41 @@ import scala.collection.JavaConverters._ import scala.beans.BeanProperty @RunWith(classOf[JUnitRunner]) -class UserApiTest extends FlatSpec with Matchers { +class UserApiTest extends FlatSpec with Matchers with BeforeAndAfterAll { behavior of "UserApi" val api = new UserApi api.apiInvoker.defaultHeaders += "api_key" -> "special-key" + // preparation before running a test + override def beforeAll() { + val user = User( + 11222, + "scala-test-username", + "scala-test-first", + "scala-test-last", + "scala_test@fail.com", + "SCALATEST", + "408-867-5309", + 1) + + api.createUser(user) + } + + // cleanup after running a test + override def afterAll() { + api.deleteUser("scala-test-username") + } + it should "fetch a user" in { - api.getUserByName("user1") match { + api.getUserByName("scala-test") match { case Some(user) => { - user.id should be(1) - user.username should be("user1") - user.password should be("XXXXXXXXXXX") - user.email should be("email1@test.com") - user.firstName should be("first name 1") - user.lastName should be("last name 1") - user.phone should be("123-456-7890") + user.id should be(11222) + user.username should be("scala-test-username") + user.password should be("SCALATEST") + user.email should be("scala_test@fail.com") + user.firstName should be("scala-test-first") + user.lastName should be("scala-test-last") + user.phone should be("408-867-5309") user.userStatus should be(1) } case None => @@ -33,7 +53,7 @@ class UserApiTest extends FlatSpec with Matchers { } it should "authenticate a user" in { - api.loginUser("user1", "XXXXXXXXXXX") match { + api.loginUser("scala-test-username", "SCALATEST") match { case Some(status) => status.startsWith("logged in user session") match { case true => // success! case _ => fail("didn't get expected message " + status) @@ -46,28 +66,6 @@ class UserApiTest extends FlatSpec with Matchers { api.logoutUser } - it should "create a user" in { - val user = User( - 1002, - "johnny", - "Johnny", - "Rocket", - "johnny@fail.com", - "XXXXXXXXXXX", - "408-867-5309", - 1) - - api.createUser(user) - - api.getUserByName("johnny") match { - case Some(user) => { - user.id should be(1002) - user.username should be("johnny") - } - case None => - } - } - it should "create 2 users" in { val userArray = (for (i <- (1 to 2)) yield { User( @@ -149,4 +147,4 @@ class UserApiTest extends FlatSpec with Matchers { case None => } } -} \ No newline at end of file +} From 05efd193c0e8c966bae90bd1a07317f578ee2232 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 11 Nov 2015 16:42:00 +0800 Subject: [PATCH 10/13] update test username for scala --- samples/client/petstore/scala/src/test/scala/UserApiTest.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala index f965510344f..77614a5dbbb 100644 --- a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala @@ -37,7 +37,7 @@ class UserApiTest extends FlatSpec with Matchers with BeforeAndAfterAll { } it should "fetch a user" in { - api.getUserByName("scala-test") match { + api.getUserByName("scala-test-username") match { case Some(user) => { user.id should be(11222) user.username should be("scala-test-username") From 2886ca0312a0b71600ab3bc3f019955e630a1e61 Mon Sep 17 00:00:00 2001 From: aersamkull Date: Wed, 11 Nov 2015 11:54:42 +0100 Subject: [PATCH 11/13] Adds comments to TypeScript Generator --- .../src/main/resources/TypeScript-Angular/api.mustache | 7 ++++++- .../src/main/resources/TypeScript-node/api.mustache | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 000ed2707b3..fc787b6437f 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -33,7 +33,12 @@ namespace {{package}} { } {{#operation}} - + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}} + */ public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { const path = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index e2a440bb846..266dbaa412f 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -167,7 +167,12 @@ export class {{classname}} { return objA; } {{#operation}} - + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}} + */ public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> { const path = this.url + this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; From 684062ccbfe613db778055b6b4e553957fbf46e0 Mon Sep 17 00:00:00 2001 From: aersamkull Date: Wed, 11 Nov 2015 13:47:09 +0100 Subject: [PATCH 12/13] Updates samples --- .../typescript-angular/API/Client/Category.ts | 11 + .../typescript-angular/API/Client/Order.ts | 35 + .../typescript-angular/API/Client/Pet.ts | 35 + .../typescript-angular/API/Client/PetApi.ts | 146 ++ .../typescript-angular/API/Client/StoreApi.ts | 59 + .../typescript-angular/API/Client/Tag.ts | 11 + .../typescript-angular/API/Client/User.ts | 24 + .../typescript-angular/API/Client/UserApi.ts | 124 ++ .../typescript-angular/API/Client/api.d.ts | 30 +- .../client/petstore/typescript-node/api.ts | 1403 +++++++++++------ 10 files changed, 1416 insertions(+), 462 deletions(-) diff --git a/samples/client/petstore/typescript-angular/API/Client/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts index a802fe4ebdf..5e0a12f2122 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -3,11 +3,22 @@ namespace API.Client { 'use strict'; + + + export interface Category { + + id?: number; + + name?: string; + } + + + } diff --git a/samples/client/petstore/typescript-angular/API/Client/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts index 1dd84e6d0ad..874efb18c7e 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -3,30 +3,65 @@ namespace API.Client { 'use strict'; + + + export interface Order { + + id?: number; + + petId?: number; + + quantity?: number; + + shipDate?: Date; + + /** * Order Status */ + status?: Order.StatusEnum; + + complete?: boolean; + } + export namespace Order { + + + + + + + + + + export enum StatusEnum { placed = 'placed', approved = 'approved', delivered = 'delivered', } + + + + } + + + } diff --git a/samples/client/petstore/typescript-angular/API/Client/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts index 60431f69c83..bf1560de85c 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -3,30 +3,65 @@ namespace API.Client { 'use strict'; + + + export interface Pet { + + id?: number; + + category?: Category; + + name: string; + + photoUrls: Array; + + tags?: Array; + + /** * pet status in the store */ + status?: Pet.StatusEnum; + } + export namespace Pet { + + + + + + + + + + + + export enum StatusEnum { available = 'available', pending = 'pending', sold = 'sold', } + + } + + + } diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 7c89b754914..2e936fdddd1 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -2,9 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ + namespace API.Client { 'use strict'; + export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; @@ -27,11 +29,25 @@ namespace API.Client { } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + + */ public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + + + let httpRequestParams: any = { method: 'PUT', url: path, @@ -50,11 +66,25 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + + */ public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + + + let httpRequestParams: any = { method: 'POST', url: path, @@ -73,15 +103,30 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * 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 + + */ public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { const path = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + if (status !== undefined) { queryParameters['status'] = status; } + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -99,15 +144,30 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * 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 + + */ public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { const path = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + if (tags !== undefined) { queryParameters['tags'] = tags; } + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -125,16 +185,31 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * 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 + + */ public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } + + + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -152,24 +227,49 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * 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 + + */ public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } + + + + + + + + + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['name'] = name; + formParams['status'] = status; + let httpRequestParams: any = { method: 'POST', url: path, @@ -188,18 +288,37 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + + */ public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } + + + + + + headerParams['api_key'] = apiKey; + + + let httpRequestParams: any = { method: 'DELETE', url: path, @@ -217,24 +336,49 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + + */ public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } + + + + + + + + + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['additionalMetadata'] = additionalMetadata; + formParams['file'] = file; + let httpRequestParams: any = { method: 'POST', url: path, @@ -252,5 +396,7 @@ namespace API.Client { return this.$http(httpRequestParams); } + } } + diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 801a86a4a04..492ef6885fe 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -2,9 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ + namespace API.Client { 'use strict'; + export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; @@ -27,11 +29,22 @@ namespace API.Client { } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + + */ public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { const path = this.basePath + '/store/inventory'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -49,11 +62,25 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + + */ public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/store/order'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + + + let httpRequestParams: any = { method: 'POST', url: path, @@ -72,16 +99,31 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * 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 + + */ public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } + + + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -99,16 +141,31 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * 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 + + */ public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } + + + + + + let httpRequestParams: any = { method: 'DELETE', url: path, @@ -125,5 +182,7 @@ namespace API.Client { return this.$http(httpRequestParams); } + } } + diff --git a/samples/client/petstore/typescript-angular/API/Client/Tag.ts b/samples/client/petstore/typescript-angular/API/Client/Tag.ts index 1c0284cce48..66666719d89 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -3,11 +3,22 @@ namespace API.Client { 'use strict'; + + + export interface Tag { + + id?: number; + + name?: string; + } + + + } diff --git a/samples/client/petstore/typescript-angular/API/Client/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts index 7c2b0b78b0c..69e94835d30 100644 --- a/samples/client/petstore/typescript-angular/API/Client/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -3,26 +3,50 @@ namespace API.Client { 'use strict'; + + + export interface User { + + id?: number; + + username?: string; + + firstName?: string; + + lastName?: string; + + email?: string; + + password?: string; + + phone?: string; + + /** * User Status */ + userStatus?: number; + } + + + } diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 4deb8bc6ebe..036508eb69d 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -2,9 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ + namespace API.Client { 'use strict'; + export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; @@ -27,11 +29,25 @@ namespace API.Client { } + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + + */ public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + + + let httpRequestParams: any = { method: 'POST', url: path, @@ -50,11 +66,25 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + + + let httpRequestParams: any = { method: 'POST', url: path, @@ -73,11 +103,25 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/createWithList'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + + + let httpRequestParams: any = { method: 'POST', url: path, @@ -96,19 +140,38 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + + */ public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/user/login'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + + if (username !== undefined) { queryParameters['username'] = username; } + if (password !== undefined) { queryParameters['password'] = password; } + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -126,11 +189,22 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Logs out current logged in user session + * + + */ public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/logout'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -148,16 +222,31 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + + */ public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } + + + + + + let httpRequestParams: any = { method: 'GET', url: path, @@ -175,16 +264,34 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * 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 + + */ public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } + + + + + + + + let httpRequestParams: any = { method: 'PUT', url: path, @@ -203,16 +310,31 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + + */ public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); + + + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } + + + + + + let httpRequestParams: any = { method: 'DELETE', url: path, @@ -229,5 +351,7 @@ namespace API.Client { return this.$http(httpRequestParams); } + } } + diff --git a/samples/client/petstore/typescript-angular/API/Client/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts index 19c60623dc9..7a4f79f38b1 100644 --- a/samples/client/petstore/typescript-angular/API/Client/api.d.ts +++ b/samples/client/petstore/typescript-angular/API/Client/api.d.ts @@ -1,9 +1,37 @@ + + /// + + + /// + + + /// + + + /// + + + /// + + + + + /// -/// + + + /// + + + +/// + + + diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 47026929d81..4728b6f8c14 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -8,69 +8,181 @@ import http = require('http'); /* tslint:disable:no-unused-variable */ + + + export class User { + + id: number; + + username: string; + + firstName: string; + + lastName: string; + + email: string; + + password: string; + + phone: string; + + /** * User Status */ + userStatus: number; + } + + + + + export class Category { + + id: number; + + name: string; + } + + + + + export class Pet { + + id: number; + + category: Category; + + name: string; + + photoUrls: Array; + + tags: Array; + + /** * pet status in the store */ + status: Pet.StatusEnum; + } + export namespace Pet { + + + + + + + + + + + + export enum StatusEnum { available = 'available', pending = 'pending', sold = 'sold', } -} -export class Tag { - id: number; - name: string; + + } -export class Order { + + + + +export class Tag { + + id: number; + + + name: string; + +} + + + + + + +export class Order { + + + id: number; + + petId: number; + + quantity: number; + + shipDate: Date; + + /** * Order Status */ + status: Order.StatusEnum; + + complete: boolean; + } + export namespace Order { + + + + + + + + + + export enum StatusEnum { placed = 'placed', approved = 'approved', delivered = 'delivered', } + + + + } + + + interface Authentication { /** * Apply authentication settings to header and query params. @@ -117,6 +229,10 @@ class VoidAuth implements Authentication { } } + + + + export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; protected defaultHeaders : any = {}; @@ -125,13 +241,34 @@ export class UserApi { public authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), + + + + 'petstore_auth': new OAuth(), + + + + + 'api_key': new ApiKeyAuth('header', 'api_key'), + + + } constructor(url: string, basePath?: string); + + + + + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { if (password) { + + + + + if (basePath) { this.basePath = basePath; } @@ -142,9 +279,20 @@ export class UserApi { } } + + + + + + + + set apiKey(key: string) { this.authentications.api_key.apiKey = key; } + + + private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ @@ -154,6 +302,12 @@ export class UserApi { return objA; } + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + + */ public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user'; let queryParameters: any = {}; @@ -161,8 +315,11 @@ export class UserApi { let formParams: any = {}; + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -171,9 +328,12 @@ export class UserApi { headers: headerParams, uri: path, json: true, + body: body, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -199,6 +359,12 @@ export class UserApi { return deferred.promise; } + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/createWithArray'; let queryParameters: any = {}; @@ -206,8 +372,11 @@ export class UserApi { let formParams: any = {}; + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -216,9 +385,12 @@ export class UserApi { headers: headerParams, uri: path, json: true, + body: body, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -244,6 +416,12 @@ export class UserApi { return deferred.promise; } + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/createWithList'; let queryParameters: any = {}; @@ -251,8 +429,11 @@ export class UserApi { let formParams: any = {}; + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -261,9 +442,12 @@ export class UserApi { headers: headerParams, uri: path, json: true, + body: body, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -289,6 +473,13 @@ export class UserApi { return deferred.promise; } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + + */ public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { const path = this.url + this.basePath + '/user/login'; let queryParameters: any = {}; @@ -296,16 +487,21 @@ export class UserApi { let formParams: any = {}; + if (username !== undefined) { queryParameters['username'] = username; } + if (password !== undefined) { queryParameters['password'] = password; } + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); let requestOptions: request.Options = { @@ -314,8 +510,10 @@ export class UserApi { headers: headerParams, uri: path, json: true, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -341,6 +539,11 @@ export class UserApi { return deferred.promise; } + /** + * Logs out current logged in user session + * + + */ public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/logout'; let queryParameters: any = {}; @@ -348,8 +551,11 @@ export class UserApi { let formParams: any = {}; + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -358,8 +564,10 @@ export class UserApi { headers: headerParams, uri: path, json: true, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -385,6 +593,12 @@ export class UserApi { return deferred.promise; } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + + */ public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { const path = this.url + this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -398,8 +612,11 @@ export class UserApi { throw new Error('Missing required parameter username when calling getUserByName'); } + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); let requestOptions: request.Options = { @@ -408,8 +625,10 @@ export class UserApi { headers: headerParams, uri: path, json: true, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -435,6 +654,13 @@ export class UserApi { return deferred.promise; } + /** + * 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 + + */ public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -448,8 +674,11 @@ export class UserApi { throw new Error('Missing required parameter username when calling updateUser'); } + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -458,9 +687,12 @@ export class UserApi { headers: headerParams, uri: path, json: true, + body: body, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -486,6 +718,12 @@ export class UserApi { return deferred.promise; } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + + */ public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -499,8 +737,11 @@ export class UserApi { throw new Error('Missing required parameter username when calling deleteUser'); } + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -509,8 +750,10 @@ export class UserApi { headers: headerParams, uri: path, json: true, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -535,465 +778,12 @@ export class UserApi { return deferred.promise; } + } -export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - protected defaultHeaders : any = {}; - public authentications = { - 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), - } - constructor(url: string, basePath?: string); - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { - if (password) { - if (basePath) { - this.basePath = basePath; - } - } else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername - } - } - } - - set apiKey(key: string) { - this.authentications.api_key.apiKey = key; - } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - - public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - let useFormData = false; - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'PUT', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - body: body, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - let useFormData = false; - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - body: body, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - const path = this.url + this.basePath + '/pet/findByStatus'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - if (status !== undefined) { - queryParameters['status'] = status; - } - - let useFormData = false; - - let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - const path = this.url + this.basePath + '/pet/findByTags'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - if (tags !== undefined) { - queryParameters['tags'] = tags; - } - - let useFormData = false; - - let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { - const path = this.url + this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - - let useFormData = false; - - let deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.api_key.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - - let useFormData = false; - - if (name !== undefined) { - formParams['name'] = name; - } - - if (status !== undefined) { - formParams['status'] = status; - } - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - - headerParams['api_key'] = apiKey; - - let useFormData = false; - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(petId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - - let useFormData = false; - - if (additionalMetadata !== undefined) { - formParams['additionalMetadata'] = additionalMetadata; - } - - if (file !== undefined) { - formParams['file'] = file; - } - useFormData = true; - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } -} export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; protected defaultHeaders : any = {}; @@ -1002,13 +792,34 @@ export class StoreApi { public authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), + + + + 'petstore_auth': new OAuth(), + + + + + 'api_key': new ApiKeyAuth('header', 'api_key'), + + + } constructor(url: string, basePath?: string); + + + + + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { if (password) { + + + + + if (basePath) { this.basePath = basePath; } @@ -1019,9 +830,20 @@ export class StoreApi { } } + + + + + + + + set apiKey(key: string) { this.authentications.api_key.apiKey = key; } + + + private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ @@ -1031,6 +853,11 @@ export class StoreApi { return objA; } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + + */ public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const path = this.url + this.basePath + '/store/inventory'; let queryParameters: any = {}; @@ -1038,8 +865,11 @@ export class StoreApi { let formParams: any = {}; + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); let requestOptions: request.Options = { @@ -1048,10 +878,13 @@ export class StoreApi { headers: headerParams, uri: path, json: true, + } + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1077,6 +910,12 @@ export class StoreApi { return deferred.promise; } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + + */ public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { const path = this.url + this.basePath + '/store/order'; let queryParameters: any = {}; @@ -1084,8 +923,11 @@ export class StoreApi { let formParams: any = {}; + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); let requestOptions: request.Options = { @@ -1094,9 +936,12 @@ export class StoreApi { headers: headerParams, uri: path, json: true, + body: body, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1122,6 +967,12 @@ export class StoreApi { return deferred.promise; } + /** + * 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 + + */ public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { const path = this.url + this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); @@ -1135,8 +986,11 @@ export class StoreApi { throw new Error('Missing required parameter orderId when calling getOrderById'); } + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); let requestOptions: request.Options = { @@ -1145,8 +999,10 @@ export class StoreApi { headers: headerParams, uri: path, json: true, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1172,6 +1028,12 @@ export class StoreApi { return deferred.promise; } + /** + * 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 + + */ public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); @@ -1185,8 +1047,11 @@ export class StoreApi { throw new Error('Missing required parameter orderId when calling deleteOrder'); } + + let useFormData = false; + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1195,8 +1060,10 @@ export class StoreApi { headers: headerParams, uri: path, json: true, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1221,4 +1088,618 @@ export class StoreApi { return deferred.promise; } + } + + + + +export class PetApi { + protected basePath = 'http://petstore.swagger.io/v2'; + protected defaultHeaders : any = {}; + + + + public authentications = { + 'default': new VoidAuth(), + + + + + 'petstore_auth': new OAuth(), + + + + + 'api_key': new ApiKeyAuth('header', 'api_key'), + + + + } + + constructor(url: string, basePath?: string); + + + + + + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + + + + + + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + + + + + + + + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + + + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + + */ + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + + + let useFormData = false; + + + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + body: body, + + } + + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + + */ + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + + + let useFormData = false; + + + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + body: body, + + } + + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + /** + * 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 + + */ + public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + const path = this.url + this.basePath + '/pet/findByStatus'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + + if (status !== undefined) { + queryParameters['status'] = status; + } + + + + let useFormData = false; + + + let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + } + + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + /** + * 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 + + */ + public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + const path = this.url + this.basePath + '/pet/findByTags'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + + + let useFormData = false; + + + let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + } + + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + /** + * 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 + + */ + public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { + const path = this.url + this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + + + + let useFormData = false; + + + let deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + } + + + this.authentications.api_key.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + /** + * 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 + + */ + public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + + + + let useFormData = false; + + + if (name !== undefined) { + formParams['name'] = name; + } + + + + if (status !== undefined) { + formParams['status'] = status; + } + + + + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + } + + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + + */ + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + + + + headerParams['api_key'] = apiKey; + + + let useFormData = false; + + + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + } + + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + + */ + public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + + + + let useFormData = false; + + + if (additionalMetadata !== undefined) { + formParams['additionalMetadata'] = additionalMetadata; + } + + + + if (file !== undefined) { + formParams['file'] = file; + } + + useFormData = true; + + + + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + + } + + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + +} + + + From cbc63d3285c14764c2fef027bea7b93834ea13f5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 12 Nov 2015 16:13:10 +0800 Subject: [PATCH 13/13] remove line break in TS methods' comment --- .../resources/TypeScript-Angular/api.mustache | 3 +- .../resources/TypeScript-node/api.mustache | 3 +- .../typescript-angular/API/Client/Category.ts | 11 - .../typescript-angular/API/Client/Order.ts | 35 - .../typescript-angular/API/Client/Pet.ts | 35 - .../typescript-angular/API/Client/PetApi.ts | 109 --- .../typescript-angular/API/Client/StoreApi.ts | 44 - .../typescript-angular/API/Client/Tag.ts | 11 - .../typescript-angular/API/Client/User.ts | 24 - .../typescript-angular/API/Client/UserApi.ts | 91 -- .../typescript-angular/API/Client/api.d.ts | 30 +- .../client/petstore/typescript-node/api.ts | 880 +++++------------- 12 files changed, 245 insertions(+), 1031 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index fc787b6437f..9efea198f36 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -37,8 +37,7 @@ namespace {{package}} { * {{summary}} * {{notes}} {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}} - */ + {{/allParams}}*/ public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { const path = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 266dbaa412f..c1f311fec19 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -171,8 +171,7 @@ export class {{classname}} { * {{summary}} * {{notes}} {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}} - */ + {{/allParams}}*/ public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> { const path = this.url + this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; diff --git a/samples/client/petstore/typescript-angular/API/Client/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts index 5e0a12f2122..a802fe4ebdf 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -3,22 +3,11 @@ namespace API.Client { 'use strict'; - - - export interface Category { - - id?: number; - - name?: string; - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts index 874efb18c7e..1dd84e6d0ad 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -3,65 +3,30 @@ namespace API.Client { 'use strict'; - - - export interface Order { - - id?: number; - - petId?: number; - - quantity?: number; - - shipDate?: Date; - - /** * Order Status */ - status?: Order.StatusEnum; - - complete?: boolean; - } - export namespace Order { - - - - - - - - - - export enum StatusEnum { placed = 'placed', approved = 'approved', delivered = 'delivered', } - - - - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts index bf1560de85c..60431f69c83 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -3,65 +3,30 @@ namespace API.Client { 'use strict'; - - - export interface Pet { - - id?: number; - - category?: Category; - - name: string; - - photoUrls: Array; - - tags?: Array; - - /** * pet status in the store */ - status?: Pet.StatusEnum; - } - export namespace Pet { - - - - - - - - - - - - export enum StatusEnum { available = 'available', pending = 'pending', sold = 'sold', } - - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 2e936fdddd1..11ef0aa3d5a 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -2,11 +2,9 @@ /* tslint:disable:no-unused-variable member-ordering */ - namespace API.Client { 'use strict'; - export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; @@ -28,26 +26,16 @@ namespace API.Client { return objA; } - /** * Update an existing pet * * @param body Pet object that needs to be added to the store - */ public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - - - let httpRequestParams: any = { method: 'PUT', url: path, @@ -65,26 +53,16 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Add a new pet to the store * * @param body Pet object that needs to be added to the store - */ public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - - - let httpRequestParams: any = { method: 'POST', url: path, @@ -102,31 +80,20 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * 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 - */ public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { const path = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - if (status !== undefined) { queryParameters['status'] = status; } - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -143,31 +110,20 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * 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 - */ public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { const path = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - if (tags !== undefined) { queryParameters['tags'] = tags; } - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -184,12 +140,10 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * 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 - */ public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/pet/{petId}' @@ -197,19 +151,10 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } - - - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -226,14 +171,12 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * 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 - */ public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet/{petId}' @@ -241,35 +184,18 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - - - - - - - - - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - formParams['name'] = name; - formParams['status'] = status; - let httpRequestParams: any = { method: 'POST', url: path, @@ -287,13 +213,11 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Deletes a pet * * @param petId Pet id to delete * @param apiKey - */ public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet/{petId}' @@ -301,24 +225,12 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - - - - - - headerParams['api_key'] = apiKey; - - - let httpRequestParams: any = { method: 'DELETE', url: path, @@ -335,14 +247,12 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * uploads an image * * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - */ public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet/{petId}/uploadImage' @@ -350,35 +260,18 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } - - - - - - - - - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - formParams['additionalMetadata'] = additionalMetadata; - formParams['file'] = file; - let httpRequestParams: any = { method: 'POST', url: path, @@ -396,7 +289,5 @@ namespace API.Client { return this.$http(httpRequestParams); } - } } - diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 492ef6885fe..3d3c445a144 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -2,11 +2,9 @@ /* tslint:disable:no-unused-variable member-ordering */ - namespace API.Client { 'use strict'; - export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; @@ -28,23 +26,15 @@ namespace API.Client { return objA; } - /** * Returns pet inventories by status * Returns a map of status codes to quantities - */ public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { const path = this.basePath + '/store/inventory'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -61,26 +51,16 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Place an order for a pet * * @param body order placed for purchasing the pet - */ public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/store/order'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - - - let httpRequestParams: any = { method: 'POST', url: path, @@ -98,12 +78,10 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * 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 - */ public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/store/order/{orderId}' @@ -111,19 +89,10 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } - - - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -140,12 +109,10 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * 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 - */ public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/store/order/{orderId}' @@ -153,19 +120,10 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } - - - - - - let httpRequestParams: any = { method: 'DELETE', url: path, @@ -182,7 +140,5 @@ namespace API.Client { return this.$http(httpRequestParams); } - } } - diff --git a/samples/client/petstore/typescript-angular/API/Client/Tag.ts b/samples/client/petstore/typescript-angular/API/Client/Tag.ts index 66666719d89..1c0284cce48 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -3,22 +3,11 @@ namespace API.Client { 'use strict'; - - - export interface Tag { - - id?: number; - - name?: string; - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts index 69e94835d30..7c2b0b78b0c 100644 --- a/samples/client/petstore/typescript-angular/API/Client/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -3,50 +3,26 @@ namespace API.Client { 'use strict'; - - - export interface User { - - id?: number; - - username?: string; - - firstName?: string; - - lastName?: string; - - email?: string; - - password?: string; - - phone?: string; - - /** * User Status */ - userStatus?: number; - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 036508eb69d..376bdb8935a 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -2,11 +2,9 @@ /* tslint:disable:no-unused-variable member-ordering */ - namespace API.Client { 'use strict'; - export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; @@ -28,26 +26,16 @@ namespace API.Client { return objA; } - /** * Create user * This can only be done by the logged in user. * @param body Created user object - */ public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - - - let httpRequestParams: any = { method: 'POST', url: path, @@ -65,26 +53,16 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Creates list of users with given input array * * @param body List of user object - */ public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - - - let httpRequestParams: any = { method: 'POST', url: path, @@ -102,26 +80,16 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Creates list of users with given input array * * @param body List of user object - */ public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/createWithList'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - - - let httpRequestParams: any = { method: 'POST', url: path, @@ -139,39 +107,25 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Logs user into the system * * @param username The user name for login * @param password The password for login in clear text - */ public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/user/login'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - - if (username !== undefined) { queryParameters['username'] = username; } - if (password !== undefined) { queryParameters['password'] = password; } - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -188,23 +142,15 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Logs out current logged in user session * - */ public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/logout'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -221,12 +167,10 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. - */ public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/user/{username}' @@ -234,19 +178,10 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } - - - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -263,13 +198,11 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * 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 - */ public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/{username}' @@ -277,21 +210,10 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } - - - - - - - - let httpRequestParams: any = { method: 'PUT', url: path, @@ -309,12 +231,10 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted - */ public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/user/{username}' @@ -322,19 +242,10 @@ namespace API.Client { let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } - - - - - - let httpRequestParams: any = { method: 'DELETE', url: path, @@ -351,7 +262,5 @@ namespace API.Client { return this.$http(httpRequestParams); } - } } - diff --git a/samples/client/petstore/typescript-angular/API/Client/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts index 7a4f79f38b1..19c60623dc9 100644 --- a/samples/client/petstore/typescript-angular/API/Client/api.d.ts +++ b/samples/client/petstore/typescript-angular/API/Client/api.d.ts @@ -1,37 +1,9 @@ - - /// - - - /// - - - /// - - - /// - - - /// - - - - - /// - - - -/// - - - /// - - - +/// diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 4728b6f8c14..ab5f05b46cb 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -8,181 +8,69 @@ import http = require('http'); /* tslint:disable:no-unused-variable */ - - - export class User { - - id: number; - - username: string; - - firstName: string; - - lastName: string; - - email: string; - - password: string; - - phone: string; - - /** * User Status */ - userStatus: number; - } - - - - - export class Category { - - id: number; - - name: string; - } - - - - - export class Pet { - - id: number; - - category: Category; - - name: string; - - photoUrls: Array; - - tags: Array; - - /** * pet status in the store */ - status: Pet.StatusEnum; - } - export namespace Pet { - - - - - - - - - - - - export enum StatusEnum { available = 'available', pending = 'pending', sold = 'sold', } - - } - - - - - export class Tag { - - id: number; - - name: string; - } - - - - - export class Order { - - id: number; - - petId: number; - - quantity: number; - - shipDate: Date; - - /** * Order Status */ - status: Order.StatusEnum; - - complete: boolean; - } - export namespace Order { - - - - - - - - - - export enum StatusEnum { placed = 'placed', approved = 'approved', delivered = 'delivered', } - - - - } - - - interface Authentication { /** * Apply authentication settings to header and query params. @@ -229,10 +117,6 @@ class VoidAuth implements Authentication { } } - - - - export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; protected defaultHeaders : any = {}; @@ -241,34 +125,13 @@ export class UserApi { public authentications = { 'default': new VoidAuth(), - - - - - 'petstore_auth': new OAuth(), - - - - 'api_key': new ApiKeyAuth('header', 'api_key'), - - - + 'petstore_auth': new OAuth(), } constructor(url: string, basePath?: string); - - - - - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { if (password) { - - - - - if (basePath) { this.basePath = basePath; } @@ -279,20 +142,9 @@ export class UserApi { } } - - - - - - - - set apiKey(key: string) { this.authentications.api_key.apiKey = key; } - - - private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ @@ -301,12 +153,10 @@ export class UserApi { } return objA; } - /** * Create user * This can only be done by the logged in user. * @param body Created user object - */ public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user'; @@ -315,11 +165,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -328,12 +175,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -358,12 +202,10 @@ export class UserApi { return deferred.promise; } - /** * Creates list of users with given input array * * @param body List of user object - */ public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/createWithArray'; @@ -372,11 +214,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -385,12 +224,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -415,12 +251,10 @@ export class UserApi { return deferred.promise; } - /** * Creates list of users with given input array * * @param body List of user object - */ public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/createWithList'; @@ -429,11 +263,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -442,12 +273,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -472,13 +300,11 @@ export class UserApi { return deferred.promise; } - /** * Logs user into the system * * @param username The user name for login * @param password The password for login in clear text - */ public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { const path = this.url + this.basePath + '/user/login'; @@ -487,21 +313,16 @@ export class UserApi { let formParams: any = {}; - if (username !== undefined) { queryParameters['username'] = username; } - if (password !== undefined) { queryParameters['password'] = password; } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); let requestOptions: request.Options = { @@ -510,10 +331,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -538,11 +357,9 @@ export class UserApi { return deferred.promise; } - /** * Logs out current logged in user session * - */ public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/logout'; @@ -551,11 +368,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -564,10 +378,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -592,12 +404,10 @@ export class UserApi { return deferred.promise; } - /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. - */ public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { const path = this.url + this.basePath + '/user/{username}' @@ -612,11 +422,8 @@ export class UserApi { throw new Error('Missing required parameter username when calling getUserByName'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); let requestOptions: request.Options = { @@ -625,10 +432,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -653,13 +458,11 @@ export class UserApi { return deferred.promise; } - /** * 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 - */ public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/{username}' @@ -674,11 +477,8 @@ export class UserApi { throw new Error('Missing required parameter username when calling updateUser'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -687,12 +487,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -717,12 +514,10 @@ export class UserApi { return deferred.promise; } - /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted - */ public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/{username}' @@ -737,11 +532,8 @@ export class UserApi { throw new Error('Missing required parameter username when calling deleteUser'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -750,10 +542,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -778,322 +568,7 @@ export class UserApi { return deferred.promise; } - } - - - - -export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - protected defaultHeaders : any = {}; - - - - public authentications = { - 'default': new VoidAuth(), - - - - - 'petstore_auth': new OAuth(), - - - - - 'api_key': new ApiKeyAuth('header', 'api_key'), - - - - } - - constructor(url: string, basePath?: string); - - - - - - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { - if (password) { - - - - - - if (basePath) { - this.basePath = basePath; - } - } else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername - } - } - } - - - - - - - - - - set apiKey(key: string) { - this.authentications.api_key.apiKey = key; - } - - - - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - - */ - public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { - const path = this.url + this.basePath + '/store/inventory'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - } - - - this.authentications.api_key.applyToRequest(requestOptions); - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - - */ - public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { - const path = this.url + this.basePath + '/store/order'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - body: body, - - } - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - /** - * 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 - - */ - public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { - const path = this.url + this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - } - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - /** - * 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 - - */ - public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - } - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - -} - - - - export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; protected defaultHeaders : any = {}; @@ -1102,34 +577,13 @@ export class PetApi { public authentications = { 'default': new VoidAuth(), - - - - - 'petstore_auth': new OAuth(), - - - - 'api_key': new ApiKeyAuth('header', 'api_key'), - - - + 'petstore_auth': new OAuth(), } constructor(url: string, basePath?: string); - - - - - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { if (password) { - - - - - if (basePath) { this.basePath = basePath; } @@ -1140,20 +594,9 @@ export class PetApi { } } - - - - - - - - set apiKey(key: string) { this.authentications.api_key.apiKey = key; } - - - private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ @@ -1162,12 +605,10 @@ export class PetApi { } return objA; } - /** * Update an existing pet * * @param body Pet object that needs to be added to the store - */ public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet'; @@ -1176,11 +617,8 @@ export class PetApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1189,15 +627,11 @@ export class PetApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1222,12 +656,10 @@ export class PetApi { return deferred.promise; } - /** * Add a new pet to the store * * @param body Pet object that needs to be added to the store - */ public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet'; @@ -1236,11 +668,8 @@ export class PetApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1249,15 +678,11 @@ export class PetApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1282,12 +707,10 @@ export class PetApi { return deferred.promise; } - /** * 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 - */ public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const path = this.url + this.basePath + '/pet/findByStatus'; @@ -1296,16 +719,12 @@ export class PetApi { let formParams: any = {}; - if (status !== undefined) { queryParameters['status'] = status; } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { @@ -1314,13 +733,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1345,12 +761,10 @@ export class PetApi { return deferred.promise; } - /** * 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 - */ public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const path = this.url + this.basePath + '/pet/findByTags'; @@ -1359,16 +773,12 @@ export class PetApi { let formParams: any = {}; - if (tags !== undefined) { queryParameters['tags'] = tags; } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { @@ -1377,13 +787,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1408,12 +815,10 @@ export class PetApi { return deferred.promise; } - /** * 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 - */ public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { const path = this.url + this.basePath + '/pet/{petId}' @@ -1428,11 +833,8 @@ export class PetApi { throw new Error('Missing required parameter petId when calling getPetById'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); let requestOptions: request.Options = { @@ -1441,13 +843,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1472,14 +871,12 @@ export class PetApi { return deferred.promise; } - /** * 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 - */ public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet/{petId}' @@ -1494,23 +891,16 @@ export class PetApi { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - - let useFormData = false; - if (name !== undefined) { formParams['name'] = name; } - - if (status !== undefined) { formParams['status'] = status; } - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1519,13 +909,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1550,13 +937,11 @@ export class PetApi { return deferred.promise; } - /** * Deletes a pet * * @param petId Pet id to delete * @param apiKey - */ public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet/{petId}' @@ -1571,14 +956,10 @@ export class PetApi { throw new Error('Missing required parameter petId when calling deletePet'); } - - headerParams['api_key'] = apiKey; - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1587,13 +968,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1618,14 +996,12 @@ export class PetApi { return deferred.promise; } - /** * uploads an image * * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - */ public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet/{petId}/uploadImage' @@ -1640,25 +1016,17 @@ export class PetApi { throw new Error('Missing required parameter petId when calling uploadFile'); } - - let useFormData = false; - if (additionalMetadata !== undefined) { formParams['additionalMetadata'] = additionalMetadata; } - - if (file !== undefined) { formParams['file'] = file; } - useFormData = true; - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1667,13 +1035,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1698,8 +1063,247 @@ export class PetApi { return deferred.promise; } - } +export class StoreApi { + protected basePath = 'http://petstore.swagger.io/v2'; + protected defaultHeaders : any = {}; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + const path = this.url + this.basePath + '/store/inventory'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + const path = this.url + this.basePath + '/store/order'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + /** + * 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 + */ + public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + const path = this.url + this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + /** + * 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 + */ + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +}